1
//! Retain safe lookup definitions until library clause generation.
2
use conjure_cp::ast::{
3
    Expression as Expr, GroundDomain, Metadata, Moo, Reference, SatEncodingDecision, SymbolTable,
4
};
5
use conjure_cp::rule_engine::{
6
    ApplicationError::RuleNotApplicable, ApplicationResult, RuleEffect, register_rule,
7
};
8

            
9
/// Materialise scalar matrix entries with their actual numeric index labels.
10
936504
pub(super) fn matrix_data(subject: &Expr) -> Option<(Vec<Expr>, Vec<i64>)> {
11
936504
    let subject = crate::shared::utils::table_operand(subject);
12
936504
    let list = subject.is_list();
13
936504
    let (entries, domain) = subject.unwrap_matrix_unchecked()?;
14
700137
    let labels = if list {
15
473697
        (1..=entries.len())
16
3202569
            .map(|value| i64::try_from(value).ok())
17
            .collect::<Option<Vec<_>>>()?
18
    } else {
19
226440
        let domain = domain.resolve().ok()?;
20
226440
        match domain.as_ref() {
21
            GroundDomain::Bool => vec![0, 1],
22
226440
            domain => domain
23
226440
                .values_i32()
24
226440
                .ok()?
25
                .into_iter()
26
226440
                .map(i64::from)
27
                .collect(),
28
        }
29
    };
30
700137
    (entries.len() == labels.len()).then_some((entries, labels))
31
936504
}
32

            
33
/// Hoist a total safe value; bubbling continues to govern undefined unsafe expressions.
34
#[register_rule("SAT", 18400, [SafeIndex])]
35
11705544
fn introduce_element(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
36
11705544
    let Expr::SafeIndex(_, subject, indices) = expr else {
37
27
        return Err(RuleNotApplicable);
38
    };
39
11705517
    if indices.len() != 1 || conjure_cp::ast::eval_constant(&indices[0]).is_some() {
40
11382498
        return Err(RuleNotApplicable);
41
323019
    }
42
323019
    let (entries, _) = matrix_data(subject).ok_or(RuleNotApplicable)?;
43
86652
    if entries.is_empty() {
44
        return Err(RuleNotApplicable);
45
86652
    }
46
86652
    let domain = expr.domain_of().ok_or(RuleNotApplicable)?;
47
86652
    let mut symbols = symbols.clone();
48
86652
    let value = Reference::new(symbols.gen_find_auxiliary(&domain));
49
86652
    let value: Expr = value.into();
50
86652
    let definition = Expr::SatElement(
51
86652
        Metadata::new(),
52
86652
        subject.clone(),
53
86652
        Moo::new(indices[0].clone()),
54
86652
        Moo::new(value.clone()),
55
86652
    );
56
86652
    Ok(RuleEffect::new(value, vec![definition], symbols))
57
11705544
}
58

            
59
/// Select whole-value equalities through the same element algorithms as scalar values.
60
#[register_rule("SAT", 18400, [SatElement])]
61
500589
fn introduce_compound_element(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
62
500589
    let Expr::SatElement(_, subject, index, value) = expr else {
63
27
        return Err(RuleNotApplicable);
64
    };
65
500562
    let domain = value.domain_of().ok_or(RuleNotApplicable)?;
66
500562
    if domain.is_int() || domain.is_bool() {
67
494208
        return Err(RuleNotApplicable);
68
6354
    }
69
6354
    let (entries, labels) = matrix_data(subject).ok_or(RuleNotApplicable)?;
70
6354
    let mut symbols = symbols.clone();
71
6354
    let mut definitions = Vec::new();
72
6354
    let comparisons = entries
73
6354
        .into_iter()
74
12708
        .map(|entry| {
75
12708
            let output = super::boolean::create_bool_aux(&mut symbols);
76
12708
            definitions.push(Expr::Iff(
77
12708
                Metadata::new(),
78
12708
                Moo::new(output.clone()),
79
12708
                Moo::new(Expr::Eq(Metadata::new(), value.clone(), Moo::new(entry))),
80
12708
            ));
81
12708
            output
82
12708
        })
83
        .collect();
84
6354
    let labels = labels
85
6354
        .into_iter()
86
12708
        .map(|label| i32::try_from(label).map(conjure_cp::ast::Range::Single))
87
        .collect::<Result<Vec<_>, _>>()
88
        .map_err(|_| RuleNotApplicable)?;
89
    let comparisons =
90
6354
        conjure_cp::into_matrix_expr![comparisons; conjure_cp::ast::Domain::int(labels)];
91
6354
    Ok(RuleEffect::new(
92
6354
        Expr::SatElement(
93
6354
            Metadata::new(),
94
6354
            Moo::new(comparisons),
95
6354
            index.clone(),
96
6354
            Moo::new(true.into()),
97
6354
        ),
98
6354
        definitions,
99
6354
        symbols,
100
6354
    ))
101
500589
}
102

            
103
/// Numeric views retain actual sparse values and physical representation invariants.
104
#[register_rule("SAT", 18500, [SatElement])]
105
603666
fn select_element(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
106
603666
    let Expr::SatElement(_, subject, index, value) = expr else {
107
27
        return Err(RuleNotApplicable);
108
    };
109
603639
    let (entries, labels) = matrix_data(subject).ok_or(RuleNotApplicable)?;
110
603639
    let index = super::pseudo_boolean::integer_view(index).ok_or(RuleNotApplicable)?;
111
202851
    let value = super::pseudo_boolean::integer_view(value).ok_or(RuleNotApplicable)?;
112
129483
    let entries = entries
113
129483
        .iter()
114
129483
        .zip(labels)
115
524259
        .map(|(entry, label)| super::pseudo_boolean::integer_view(entry).map(|view| (label, view)))
116
        .collect::<Option<Vec<_>>>()
117
129483
        .ok_or(RuleNotApplicable)?;
118
86643
    Ok(RuleEffect::sat(
119
86643
        true.into(),
120
86643
        vec![SatEncodingDecision::Element {
121
86643
            index_view: index,
122
86643
            value,
123
86643
            entries,
124
86643
            encoding: None,
125
86643
            pb_encoding: None,
126
86643
        }],
127
86643
        symbols.clone(),
128
86643
    ))
129
603666
}