1
use conjure_cp::ast::{Atom, Expression as Expr, Literal};
2
use conjure_cp::ast::{SATIntEncoding, SymbolTable};
3
use conjure_cp::rule_engine::ApplicationError;
4
use conjure_cp::rule_engine::{
5
    ApplicationError::RuleNotApplicable, ApplicationResult, Reduction, register_rule,
6
};
7

            
8
use crate::sat::boolean::{tseytin_and, tseytin_iff, tseytin_not, tseytin_or};
9
use conjure_cp::ast::Metadata;
10
use conjure_cp::ast::Moo;
11
use conjure_cp::into_matrix_expr;
12

            
13
/// This function confirms that all of the input expressions are order SATInts, and returns vectors for each input of their bits
14
/// This function also normalizes order SATInt operands to a common value range.
15
2637
pub fn validate_order_int_operands(
16
2637
    exprs: Vec<Expr>,
17
2637
) -> Result<(Vec<Vec<Expr>>, i32, i32), ApplicationError> {
18
    // Iterate over all inputs
19
    // Check they are order and calulate a lower and upper bound
20
2637
    let mut global_min: i32 = i32::MAX;
21
2637
    let mut global_max: i32 = i32::MIN;
22

            
23
4851
    for operand in &exprs {
24
3483
        let Expr::SATInt(_, SATIntEncoding::Order, _, (local_min, local_max)) = operand else {
25
1368
            return Err(RuleNotApplicable);
26
        };
27
3483
        global_min = global_min.min(*local_min);
28
3483
        global_max = global_max.max(*local_max);
29
    }
30

            
31
    // build out by iterating over each operand and expanding it to match the new bounds
32
1269
    let out: Vec<Vec<Expr>> = exprs
33
1269
        .into_iter()
34
2538
        .map(|expr| {
35
2538
            let Expr::SATInt(_, SATIntEncoding::Order, inner, (local_min, local_max)) = expr else {
36
                return Err(RuleNotApplicable);
37
            };
38

            
39
2538
            let Some(v) = inner.as_ref().clone().unwrap_list() else {
40
                return Err(RuleNotApplicable);
41
            };
42

            
43
            // calulcate how many trues/falses to prepend/append
44
2538
            let prefix_len = (local_min - global_min) as usize;
45
2538
            let postfix_len = (global_max - local_max) as usize;
46

            
47
2538
            let mut bits = Vec::with_capacity(v.len() + prefix_len + postfix_len);
48

            
49
            // add `true`s to start
50
2538
            bits.extend(std::iter::repeat_n(
51
2538
                Expr::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(true))),
52
2538
                prefix_len,
53
            ));
54

            
55
2538
            bits.extend(v);
56

            
57
            // add `false`s to end
58
2538
            bits.extend(std::iter::repeat_n(
59
2538
                Expr::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(false))),
60
2538
                postfix_len,
61
            ));
62

            
63
2538
            Ok(bits)
64
2538
        })
65
1269
        .collect::<Result<_, _>>()?;
66

            
67
1269
    Ok((out, global_min, global_max))
68
2637
}
69

            
70
/// Encodes a < b for order integers.
71
///
72
/// `x < y` iff `exists i . (NOT x_i AND y_i)`
73
1035
fn sat_order_lt(
74
1035
    a_bits: Vec<Expr>,
75
1035
    b_bits: Vec<Expr>,
76
1035
    clauses: &mut Vec<conjure_cp::ast::CnfClause>,
77
1035
    symbols: &mut SymbolTable,
78
1035
) -> Expr {
79
1035
    let mut result = Expr::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(false)));
80

            
81
7191
    for (a_i, b_i) in a_bits.iter().zip(b_bits.iter()) {
82
        // (NOT a_i AND b_i)
83
7191
        let not_a_i = tseytin_not(a_i.clone(), clauses, symbols);
84
7191
        let current_term = tseytin_and(&vec![not_a_i, b_i.clone()], clauses, symbols);
85
7191

            
86
        // accumulate (NOT a_i AND b_i) into OR term
87
7191
        result = tseytin_or(&vec![result, current_term], clauses, symbols);
88
7191
    }
89
1035
    result
90
1035
}
91

            
92
/// Converts an integer literal to SATInt form
93
///
94
/// ```text
95
///  3
96
///  ~~>
97
///  SATInt([true;int(1..), (3, 3)])
98
///
99
/// ```
100
#[register_rule(("SAT_Order", 9500))]
101
180603
fn literal_sat_order_int(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
102
873
    let value = {
103
8064
        if let Expr::Atomic(_, Atom::Literal(Literal::Int(value))) = expr {
104
873
            *value
105
        } else {
106
179730
            return Err(RuleNotApplicable);
107
        }
108
    };
109

            
110
873
    Ok(Reduction::pure(Expr::SATInt(
111
873
        Metadata::new(),
112
873
        SATIntEncoding::Order,
113
873
        Moo::new(into_matrix_expr!(vec![Expr::Atomic(
114
873
            Metadata::new(),
115
873
            Atom::Literal(Literal::Bool(true)),
116
873
        )])),
117
873
        (value, value),
118
873
    )))
119
180603
}
120

            
121
/// Builds CNF for equality between two order SATInt bit-vectors.
122
/// This function is used by both eq and neq rules, with the output negated for neq.
123
/// Returns (expr, clauses, symbols).
124
234
fn sat_order_eq_expr(
125
234
    lhs_bits: &[Expr],
126
234
    rhs_bits: &[Expr],
127
234
    symbols: &SymbolTable,
128
234
) -> (Expr, Vec<conjure_cp::ast::CnfClause>, SymbolTable) {
129
234
    let bit_count = lhs_bits.len();
130

            
131
234
    let mut output = true.into();
132
234
    let mut new_symbols = symbols.clone();
133
234
    let mut new_clauses = vec![];
134

            
135
1197
    for i in 0..bit_count {
136
1197
        let comparison = tseytin_iff(
137
1197
            lhs_bits[i].clone(),
138
1197
            rhs_bits[i].clone(),
139
1197
            &mut new_clauses,
140
1197
            &mut new_symbols,
141
1197
        );
142
1197
        output = tseytin_and(
143
1197
            &vec![comparison, output],
144
1197
            &mut new_clauses,
145
1197
            &mut new_symbols,
146
1197
        );
147
1197
    }
148

            
149
234
    (output, new_clauses, new_symbols)
150
234
}
151

            
152
/// Converts a = expression between two order SATInts to a boolean expression in cnf
153
///
154
/// ```text
155
/// SATInt(a) = SATInt(b) ~> Bool
156
/// ```
157
#[register_rule(("SAT_Order", 9100))]
158
50436
fn eq_sat_order(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
159
50436
    let Expr::Eq(_, lhs, rhs) = expr else {
160
50229
        return Err(RuleNotApplicable);
161
    };
162

            
163
198
    let (binding, _, _) =
164
207
        validate_order_int_operands(vec![lhs.as_ref().clone(), rhs.as_ref().clone()])?;
165
198
    let [lhs_bits, rhs_bits] = binding.as_slice() else {
166
        return Err(RuleNotApplicable);
167
    };
168

            
169
198
    let (output, new_clauses, new_symbols) = sat_order_eq_expr(lhs_bits, rhs_bits, symbols);
170

            
171
198
    Ok(Reduction::cnf(output, new_clauses, new_symbols))
172
50436
}
173

            
174
/// Converts a != expression between two order SATInts to a boolean expression in cnf
175
#[register_rule(("SAT_Order", 9100))]
176
50436
fn neq_sat_order(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
177
50436
    let Expr::Neq(_, lhs, rhs) = expr else {
178
50391
        return Err(RuleNotApplicable);
179
    }; // considered covered
180

            
181
36
    let (binding, _, _) =
182
45
        validate_order_int_operands(vec![lhs.as_ref().clone(), rhs.as_ref().clone()])?;
183
36
    let [lhs_bits, rhs_bits] = binding.as_slice() else {
184
        return Err(RuleNotApplicable); // consider covered
185
    };
186

            
187
36
    let (mut output, mut new_clauses, mut new_symbols) =
188
36
        sat_order_eq_expr(lhs_bits, rhs_bits, symbols);
189

            
190
36
    output = tseytin_not(output, &mut new_clauses, &mut new_symbols);
191

            
192
36
    Ok(Reduction::cnf(output, new_clauses, new_symbols))
193
50436
}
194

            
195
/// Converts a </>/<=/>= expression between two order SATInts to a boolean expression in cnf
196
///
197
/// ```text
198
/// SATInt(a) </>/<=/>= SATInt(b) ~> Bool
199
///
200
/// ```
201
/// Note: < and <= are rewritten by swapping operands to reuse lt logic.
202
#[register_rule(("SAT_Order", 9100))]
203
50436
fn ineq_sat_order(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
204
50436
    let (lhs, rhs, negate) = match expr {
205
        // A < B -> sat_order_lt(A, B)
206
36
        Expr::Lt(_, x, y) => (x, y, false),
207
        // A > B -> sat_order_lt(B, A)
208
9
        Expr::Gt(_, x, y) => (y, x, false),
209
        // A <= B -> NOT (B < A)
210
1458
        Expr::Leq(_, x, y) => (y, x, true),
211
        // A >= B -> NOT (A < B)
212
882
        Expr::Geq(_, x, y) => (x, y, true),
213
48051
        _ => return Err(RuleNotApplicable),
214
    };
215

            
216
1035
    let (binding, _, _) =
217
2385
        validate_order_int_operands(vec![lhs.as_ref().clone(), rhs.as_ref().clone()])?;
218
1035
    let [lhs_bits, rhs_bits] = binding.as_slice() else {
219
        return Err(RuleNotApplicable);
220
    };
221

            
222
1035
    let mut new_symbols = symbols.clone();
223
1035
    let mut new_clauses = vec![];
224

            
225
1035
    let mut output = sat_order_lt(
226
1035
        lhs_bits.clone(),
227
1035
        rhs_bits.clone(),
228
1035
        &mut new_clauses,
229
1035
        &mut new_symbols,
230
    );
231

            
232
1035
    if negate {
233
990
        output = tseytin_not(output, &mut new_clauses, &mut new_symbols);
234
990
    }
235

            
236
1035
    Ok(Reduction::cnf(output, new_clauses, new_symbols))
237
50436
}