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

            
7
use conjure_cp::ast::AbstractLiteral::Matrix;
8
use conjure_cp::ast::Metadata;
9
use conjure_cp::ast::Moo;
10
use conjure_cp::into_matrix_expr;
11

            
12
use itertools::Itertools;
13

            
14
use super::materialise::{bit_magnitude, match_bits_length, validate_log_int_operands};
15
use crate::backends::sat::boolean::{
16
    tseytin_and, tseytin_iff, tseytin_imply, tseytin_mux, tseytin_not, tseytin_or, tseytin_xor,
17
};
18

            
19
use conjure_cp::ast::SatEncodingDecision;
20

            
21
use std::cmp;
22

            
23
// Creates a boolean expression for > or >=
24
// a > b or a >= b
25
// This can also be used for < and <= by reversing the order of the inputs
26
// Returns result, new symbol table, new decisions
27
13860
fn inequality_boolean(
28
13860
    a: Vec<Expr>,
29
13860
    b: Vec<Expr>,
30
13860
    strict: bool,
31
13860
    decisions: &mut Vec<SatEncodingDecision>,
32
13860
    symbols: &mut SymbolTable,
33
13860
) -> Expr {
34
    let mut notb;
35
    let mut output;
36

            
37
13860
    if strict {
38
13860
        notb = tseytin_not(b[0].clone(), decisions, symbols);
39
13860
        output = tseytin_and(&[a[0].clone(), notb], decisions, symbols);
40
    } else {
41
        output = tseytin_imply(b[0].clone(), a[0].clone(), decisions, symbols);
42
    }
43

            
44
    //TODO: There may be room for simplification, and constant optimisation
45

            
46
13860
    let bit_count = a.len();
47

            
48
    let mut lhs;
49
    let mut rhs;
50
    let mut iff;
51
13860
    for n in 1..(bit_count - 1) {
52
22680
        notb = tseytin_not(b[n].clone(), decisions, symbols);
53
22680
        lhs = tseytin_and(&[a[n].clone(), notb.clone()], decisions, symbols);
54
22680
        iff = tseytin_iff(a[n].clone(), b[n].clone(), decisions, symbols);
55
22680
        rhs = tseytin_and(&[iff.clone(), output.clone()], decisions, symbols);
56
22680
        output = tseytin_or(&[lhs.clone(), rhs.clone()], decisions, symbols);
57
    }
58

            
59
    // final bool is the sign bit and should be handled inversely
60
13860
    let nota = tseytin_not(a[bit_count - 1].clone(), decisions, symbols);
61
13860
    lhs = tseytin_and(&[nota, b[bit_count - 1].clone()], decisions, symbols);
62
13860
    iff = tseytin_iff(
63
13860
        a[bit_count - 1].clone(),
64
13860
        b[bit_count - 1].clone(),
65
13860
        decisions,
66
13860
        symbols,
67
13860
    );
68
13860
    rhs = tseytin_and(&[iff, output.clone()], decisions, symbols);
69
13860
    output = tseytin_or(&[lhs, rhs], decisions, symbols);
70

            
71
13860
    output
72
13860
}
73

            
74
/// Returns result, new symbol table, new decisions
75
/// This function expects bits to match the lengths of x and y
76
2062746
fn tseytin_int_adder(
77
2062746
    x: &[Expr],
78
2062746
    y: &[Expr],
79
2062746
    bits: usize,
80
2062746
    decisions: &mut Vec<SatEncodingDecision>,
81
2062746
    symbols: &mut SymbolTable,
82
2062746
) -> Vec<Expr> {
83
    //TODO: Optimizing for constants
84
    let (mut result, mut carry) =
85
2062746
        tseytin_half_adder(x[0].clone(), y[0].clone(), decisions, symbols);
86

            
87
2062746
    let mut output = vec![result];
88
2062746
    for i in 1..bits {
89
21036240
        (result, carry) = tseytin_full_adder(
90
21036240
            x[i].clone(),
91
21036240
            y[i].clone(),
92
21036240
            carry.clone(),
93
21036240
            decisions,
94
21036240
            symbols,
95
21036240
        );
96
21036240
        output.push(result);
97
    }
98

            
99
2062746
    output
100
2062746
}
101

            
102
/// This function adds two booleans and a carry boolean using the full-adder logic circuit, it is intended for use in a binary adder.
103
21036240
fn tseytin_full_adder(
104
21036240
    a: Expr,
105
21036240
    b: Expr,
106
21036240
    carry: Expr,
107
21036240
    decisions: &mut Vec<SatEncodingDecision>,
108
21036240
    symbols: &mut SymbolTable,
109
21036240
) -> (Expr, Expr) {
110
21036240
    let axorb = tseytin_xor(a.clone(), b.clone(), decisions, symbols);
111
21036240
    let result = tseytin_xor(axorb.clone(), carry.clone(), decisions, symbols);
112
21036240
    let aandb = tseytin_and(&[a, b], decisions, symbols);
113
21036240
    let carryandaxorb = tseytin_and(&[carry, axorb], decisions, symbols);
114
21036240
    let carryout = tseytin_or(&[aandb, carryandaxorb], decisions, symbols);
115

            
116
21036240
    (result, carryout)
117
21036240
}
118

            
119
/// This function adds two booleans using the half-adder logic circuit, it is intended for use in a binary adder.
120
2062746
fn tseytin_half_adder(
121
2062746
    a: Expr,
122
2062746
    b: Expr,
123
2062746
    decisions: &mut Vec<SatEncodingDecision>,
124
2062746
    symbols: &mut SymbolTable,
125
2062746
) -> (Expr, Expr) {
126
2062746
    let result = tseytin_xor(a.clone(), b.clone(), decisions, symbols);
127
2062746
    let carry = tseytin_and(&[a, b], decisions, symbols);
128

            
129
2062746
    (result, carry)
130
2062746
}
131

            
132
/// this function is for specifically adding a power of two constant to a cnf int.
133
1262448
fn tseytin_add_two_power(
134
1262448
    expr: &[Expr],
135
1262448
    exponent: usize,
136
1262448
    bits: usize,
137
1262448
    decisions: &mut Vec<SatEncodingDecision>,
138
1262448
    symbols: &mut SymbolTable,
139
1262448
) -> Vec<Expr> {
140
1262448
    let mut result = vec![];
141
1262448
    let mut product = expr[exponent].clone();
142

            
143
1262448
    for item in expr.iter().take(exponent) {
144
        result.push(item.clone());
145
    }
146

            
147
1262448
    result.push(tseytin_not(expr[exponent].clone(), decisions, symbols));
148

            
149
1262448
    for item in expr.iter().take(bits).skip(exponent + 1) {
150
6477516
        result.push(tseytin_xor(
151
6477516
            product.clone(),
152
6477516
            item.clone(),
153
6477516
            decisions,
154
6477516
            symbols,
155
6477516
        ));
156
6477516
        product = tseytin_and(&[product, item.clone()], decisions, symbols);
157
    }
158

            
159
1262448
    result
160
1262448
}
161

            
162
/// This function multiplies two binary values using the shift-add multiplication algorithm.
163
46494
fn cnf_shift_add_multiply(
164
46494
    x: &[Expr],
165
46494
    y: &[Expr],
166
46494
    bits: usize,
167
46494
    decisions: &mut Vec<SatEncodingDecision>,
168
46494
    symbols: &mut SymbolTable,
169
46494
) -> Vec<Expr> {
170
46494
    let mut x = x.to_owned();
171
46494
    let mut y = y.to_owned();
172

            
173
    //TODO Optimizing for constants
174
    //TODO Optimize addition for i left shifted values - skip first i bits
175

            
176
    // extend sign bits of operands to 2*`bits`
177
46494
    x.extend(std::iter::repeat_n(x[bits - 1].clone(), bits));
178
46494
    y.extend(std::iter::repeat_n(y[bits - 1].clone(), bits));
179

            
180
46494
    let mut s: Vec<Expr> = vec![];
181
    let mut x_0andy_i;
182

            
183
46494
    for bit in &y {
184
493668
        x_0andy_i = tseytin_and(&[x[0].clone(), bit.clone()], decisions, symbols);
185
493668
        s.push(x_0andy_i);
186
    }
187

            
188
    let mut sum;
189
    let mut if_true;
190
    let mut not_x_n;
191
    let mut if_false;
192

            
193
    // Include the extended sign bits in the full-width modular product.
194
46494
    for item in x.iter().take(bits * 2).skip(1) {
195
        // y << 1
196
447174
        for i in (1..bits * 2).rev() {
197
6967206
            y[i] = y[i - 1].clone();
198
        }
199
447174
        y[0] = false.into();
200

            
201
        // TODO switch to multiplexer
202
447174
        sum = tseytin_int_adder(&s, &y, bits * 2, decisions, symbols);
203
447174
        not_x_n = tseytin_not(item.clone(), decisions, symbols);
204

            
205
447174
        for i in 0..(bits * 2) {
206
7414380
            if_true = tseytin_and(&[item.clone(), sum[i].clone()], decisions, symbols);
207
7414380
            if_false = tseytin_and(&[not_x_n.clone(), s[i].clone()], decisions, symbols);
208
7414380
            s[i] = tseytin_or(&[if_true.clone(), if_false.clone()], decisions, symbols);
209
        }
210
    }
211

            
212
46494
    s
213
46494
}
214

            
215
/// This function calculates the range of the product of multiple integers.
216
/// E.g.
217
/// a : [2, 5], b : [-1, 2], c : [-10, -6], d : [0, 3]
218
/// a * b * c *d : [-300, 150]
219
68436
fn product_of_ranges(ranges: Vec<&(i32, i32)>) -> (i32, i32) {
220
68436
    if ranges.is_empty() {
221
        return (1, 1); // product of zero numbers = 1
222
68436
    }
223

            
224
68436
    let &(mut min_prod, mut max_prod) = ranges[0];
225

            
226
68436
    for &(a, b) in &ranges[1..] {
227
70866
        let candidates = [min_prod * a, min_prod * b, max_prod * a, max_prod * b];
228
70866
        min_prod = *candidates.iter().min().unwrap();
229
70866
        max_prod = *candidates.iter().max().unwrap();
230
    }
231

            
232
68436
    (min_prod, max_prod)
233
68436
}
234

            
235
/// Converts product of SATInts to a single SATInt
236
///
237
/// ```text
238
/// Product(SATInt(a), SATInt(b), ...) ~> SATInt(c)
239
///
240
/// ```
241
#[register_rule("SAT", 9000, [Product])]
242
194643
fn cnf_int_product(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
243
    // Constant scaling belongs to the selected linear encoder, not multiplication circuits.
244
194643
    if crate::backends::sat::pseudo_boolean::integer_view(expr).is_some() {
245
43623
        return Err(RuleNotApplicable);
246
151020
    }
247
151020
    let Expr::Product(_, exprs) = expr else {
248
27
        return Err(RuleNotApplicable);
249
    };
250

            
251
150993
    let Expr::AbstractLiteral(_, Matrix(exprs_list, _)) = exprs.as_ref() else {
252
9
        return Err(RuleNotApplicable);
253
    };
254

            
255
150984
    let ranges: Result<Vec<_>, _> = exprs_list
256
150984
        .iter()
257
272565
        .map(|e| match e {
258
190017
            Expr::SATInt(_, _, _, x) => Ok(x),
259
82548
            _ => Err(RuleNotApplicable),
260
272565
        })
261
        .collect();
262

            
263
150984
    let ranges = ranges?; // propagate error if any
264

            
265
68436
    let (min, max) = product_of_ranges(ranges.clone());
266

            
267
68436
    let exprs_bits = validate_log_int_operands(exprs_list.clone(), None)?;
268

            
269
30132
    let mut new_symbols = symbols.clone();
270
30132
    let mut new_sat_decisions = vec![];
271

            
272
30132
    let (result, _) = exprs_bits
273
30132
        .iter()
274
30132
        .cloned()
275
30132
        .zip(ranges.into_iter().copied())
276
31410
        .reduce(|lhs, rhs| {
277
            // Make both bit vectors the same length
278
31410
            let (lhs_bits, rhs_bits) = match_bits_length(lhs.0.clone(), rhs.0.clone());
279

            
280
            // Multiply operands
281
31410
            let mut values = cnf_shift_add_multiply(
282
31410
                &lhs_bits,
283
31410
                &rhs_bits,
284
31410
                lhs_bits.len(),
285
31410
                &mut new_sat_decisions,
286
31410
                &mut new_symbols,
287
31410
            );
288

            
289
            // Determine new range of result
290
31410
            let (mut cum_min, mut cum_max) = lhs.1;
291
31410
            let candidates = [
292
31410
                cum_min * rhs.1.0,
293
31410
                cum_min * rhs.1.1,
294
31410
                cum_max * rhs.1.0,
295
31410
                cum_max * rhs.1.1,
296
31410
            ];
297
31410
            cum_min = *candidates.iter().min().unwrap();
298
31410
            cum_max = *candidates.iter().max().unwrap();
299

            
300
31410
            let new_bit_count = bit_magnitude(cum_min).max(bit_magnitude(cum_max));
301
31410
            values.truncate(new_bit_count);
302

            
303
31410
            (values, (cum_min, cum_max))
304
31410
        })
305
        .unwrap();
306

            
307
30132
    Ok(RuleEffect::sat(
308
30132
        Expr::SATInt(
309
30132
            Metadata::new(),
310
30132
            SATIntEncoding::Log,
311
30132
            Moo::new(into_matrix_expr!(result)),
312
30132
            (min, max),
313
30132
        ),
314
30132
        new_sat_decisions,
315
30132
        new_symbols,
316
30132
    ))
317
194643
}
318

            
319
1259289
fn tseytin_negate(
320
1259289
    expr: &Vec<Expr>,
321
1259289
    bits: usize,
322
1259289
    decisions: &mut Vec<SatEncodingDecision>,
323
1259289
    symbols: &mut SymbolTable,
324
1259289
) -> Vec<Expr> {
325
1259289
    let mut result = vec![];
326
    // invert bits
327
1259289
    for bit in expr {
328
7727490
        result.push(tseytin_not(bit.clone(), decisions, symbols));
329
    }
330

            
331
    // add one
332
1259289
    result = tseytin_add_two_power(&result, 0, bits, decisions, symbols);
333

            
334
1259289
    result
335
1259289
}
336

            
337
/// Converts min of SATInts to a single SATInt
338
///
339
/// ```text
340
/// Min(SATInt(a), SATInt(b), ...) ~> SATInt(c)
341
///
342
/// ```
343
#[register_rule("SAT", 4100, [Min])]
344
13977
fn cnf_int_min(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
345
13977
    let Expr::Min(_, exprs) = expr else {
346
27
        return Err(RuleNotApplicable);
347
    };
348

            
349
13950
    let Expr::AbstractLiteral(_, Matrix(exprs_list, _)) = exprs.as_ref() else {
350
        return Err(RuleNotApplicable);
351
    };
352

            
353
13950
    let ranges: Result<Vec<_>, _> = exprs_list
354
13950
        .iter()
355
29700
        .map(|e| match e {
356
29700
            Expr::SATInt(_, _, _, x) => Ok(x),
357
            _ => Err(RuleNotApplicable),
358
29700
        })
359
        .collect();
360

            
361
13950
    let ranges = ranges?; // propagate error if any
362

            
363
    // Is this optimal?
364
29700
    let min = ranges.iter().map(|(a, _)| *a).min().unwrap();
365
29700
    let max = ranges.iter().map(|(_, b)| *b).min().unwrap();
366

            
367
13950
    let mut exprs_bits = validate_log_int_operands(exprs_list.clone(), None)?;
368

            
369
6930
    let mut new_symbols = symbols.clone();
370
    let mut values;
371
6930
    let mut new_sat_decisions = vec![];
372

            
373
14490
    while exprs_bits.len() > 1 {
374
7560
        let mut next = Vec::with_capacity(exprs_bits.len().div_ceil(2));
375
7560
        let mut iter = exprs_bits.into_iter();
376

            
377
15750
        while let Some(a) = iter.next() {
378
8190
            if let Some(b) = iter.next() {
379
7560
                values =
380
7560
                    tseytin_binary_min_max(&a, &b, true, &mut new_sat_decisions, &mut new_symbols);
381
7560
                next.push(values);
382
            } else {
383
630
                next.push(a);
384
            }
385
        }
386

            
387
7560
        exprs_bits = next;
388
    }
389

            
390
6930
    let result = exprs_bits.pop().unwrap();
391

            
392
6930
    Ok(RuleEffect::sat(
393
6930
        Expr::SATInt(
394
6930
            Metadata::new(),
395
6930
            SATIntEncoding::Log,
396
6930
            Moo::new(into_matrix_expr!(result)),
397
6930
            (min, max),
398
6930
        ),
399
6930
        new_sat_decisions,
400
6930
        new_symbols,
401
6930
    ))
402
13977
}
403

            
404
/// General function for getting the min or max of two log integers.
405
13860
fn tseytin_binary_min_max(
406
13860
    x: &[Expr],
407
13860
    y: &[Expr],
408
13860
    min: bool,
409
13860
    decisions: &mut Vec<SatEncodingDecision>,
410
13860
    symbols: &mut SymbolTable,
411
13860
) -> Vec<Expr> {
412
13860
    let mask = if min {
413
        // mask is 1 if x > y
414
7560
        inequality_boolean(x.to_owned(), y.to_owned(), true, decisions, symbols)
415
    } else {
416
        // flip the args if getting maximum x < y -> 1
417
6300
        inequality_boolean(y.to_owned(), x.to_owned(), true, decisions, symbols)
418
    };
419

            
420
13860
    tseytin_select_array(mask, x, y, decisions, symbols)
421
13860
}
422

            
423
// Selects between two boolean vectors depending on a condition (both vectors must be the same length)
424
/// cond ? b : a
425
///
426
/// cond = 1 => b
427
/// cond = 0 => a
428
1273149
fn tseytin_select_array(
429
1273149
    cond: Expr,
430
1273149
    a: &[Expr],
431
1273149
    b: &[Expr],
432
1273149
    decisions: &mut Vec<SatEncodingDecision>,
433
1273149
    symbols: &mut SymbolTable,
434
1273149
) -> Vec<Expr> {
435
1273149
    assert_eq!(
436
1273149
        a.len(),
437
1273149
        b.len(),
438
        "Input vectors 'a' and 'b' must have the same length"
439
    );
440

            
441
1273149
    let mut out = vec![];
442

            
443
1273149
    let bit_count = a.len();
444

            
445
1273149
    for i in 0..bit_count {
446
6428628
        out.push(tseytin_mux(
447
6428628
            cond.clone(),
448
6428628
            a[i].clone(),
449
6428628
            b[i].clone(),
450
6428628
            decisions,
451
6428628
            symbols,
452
6428628
        ));
453
    }
454

            
455
1273149
    out
456
1273149
}
457

            
458
/// Converts max of SATInts to a single SATInt
459
///
460
/// ```text
461
/// Max(SATInt(a), SATInt(b), ...) ~> SATInt(c)
462
///
463
/// ```
464
#[register_rule("SAT", 4100, [Max])]
465
12132
fn cnf_int_max(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
466
12132
    let Expr::Max(_, exprs) = expr else {
467
27
        return Err(RuleNotApplicable);
468
    };
469

            
470
12105
    let Expr::AbstractLiteral(_, Matrix(exprs_list, _)) = exprs.as_ref() else {
471
        return Err(RuleNotApplicable);
472
    };
473

            
474
12105
    let ranges: Result<Vec<_>, _> = exprs_list
475
12105
        .iter()
476
25425
        .map(|e| match e {
477
25425
            Expr::SATInt(_, _, _, x) => Ok(x),
478
            _ => Err(RuleNotApplicable),
479
25425
        })
480
        .collect();
481

            
482
12105
    let ranges = ranges?; // propagate error if any
483

            
484
    // Is this optimal?
485
25425
    let min = ranges.iter().map(|(a, _)| *a).max().unwrap();
486
25425
    let max = ranges.iter().map(|(_, b)| *b).max().unwrap();
487

            
488
12105
    let mut exprs_bits = validate_log_int_operands(exprs_list.clone(), None)?;
489

            
490
5670
    let mut new_symbols = symbols.clone();
491
    let mut values;
492
5670
    let mut new_sat_decisions = vec![];
493

            
494
11970
    while exprs_bits.len() > 1 {
495
6300
        let mut next = Vec::with_capacity(exprs_bits.len().div_ceil(2));
496
6300
        let mut iter = exprs_bits.into_iter();
497

            
498
13230
        while let Some(a) = iter.next() {
499
6930
            if let Some(b) = iter.next() {
500
6300
                values =
501
6300
                    tseytin_binary_min_max(&a, &b, false, &mut new_sat_decisions, &mut new_symbols);
502
6300
                next.push(values);
503
            } else {
504
630
                next.push(a);
505
            }
506
        }
507

            
508
6300
        exprs_bits = next;
509
    }
510

            
511
5670
    let result = exprs_bits.pop().unwrap();
512

            
513
5670
    Ok(RuleEffect::sat(
514
5670
        Expr::SATInt(
515
5670
            Metadata::new(),
516
5670
            SATIntEncoding::Log,
517
5670
            Moo::new(into_matrix_expr!(result)),
518
5670
            (min, max),
519
5670
        ),
520
5670
        new_sat_decisions,
521
5670
        new_symbols,
522
5670
    ))
523
12132
}
524

            
525
/// Converts Abs of a SATInt to a SATInt
526
///
527
/// ```text
528
/// |SATInt(a)| ~> SATInt(b)
529
///
530
/// ```
531
#[register_rule("SAT", 4100, [Abs])]
532
7425
fn cnf_int_abs(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
533
7425
    let Expr::Abs(_, expr) = expr else {
534
27
        return Err(RuleNotApplicable);
535
    };
536

            
537
7398
    let Expr::SATInt(_, _, _, (min, max)) = expr.as_ref() else {
538
810
        return Err(RuleNotApplicable);
539
    };
540

            
541
6588
    let range = (
542
6588
        cmp::max(0, cmp::max(*min, -*max)),
543
6588
        cmp::max(min.abs(), max.abs()),
544
6588
    );
545

            
546
6588
    let binding = validate_log_int_operands(vec![expr.as_ref().clone()], None)?;
547
3159
    let [bits] = binding.as_slice() else {
548
        return Err(RuleNotApplicable);
549
    };
550

            
551
3159
    let mut new_sat_decisions = vec![];
552
3159
    let mut new_symbols = symbols.clone();
553

            
554
3159
    let mut result = vec![];
555

            
556
    // How does this handle negatives edge cases: -(-8) = 8, an extra bit is needed
557

            
558
    // invert bits
559
3159
    for bit in bits {
560
12474
        result.push(tseytin_not(
561
12474
            bit.clone(),
562
12474
            &mut new_sat_decisions,
563
12474
            &mut new_symbols,
564
12474
        ));
565
    }
566

            
567
3159
    let bit_count = result.len();
568

            
569
    // add one
570
3159
    result = tseytin_add_two_power(
571
3159
        &result,
572
3159
        0,
573
3159
        bit_count,
574
3159
        &mut new_sat_decisions,
575
3159
        &mut new_symbols,
576
3159
    );
577

            
578
3159
    for i in 0..bit_count {
579
12474
        result[i] = tseytin_mux(
580
12474
            bits[bit_count - 1].clone(),
581
12474
            bits[i].clone(),
582
12474
            result[i].clone(),
583
12474
            &mut new_sat_decisions,
584
12474
            &mut new_symbols,
585
12474
        )
586
    }
587

            
588
3159
    Ok(RuleEffect::sat(
589
3159
        Expr::SATInt(
590
3159
            Metadata::new(),
591
3159
            SATIntEncoding::Log,
592
3159
            Moo::new(into_matrix_expr!(result)),
593
3159
            range,
594
3159
        ),
595
3159
        new_sat_decisions,
596
3159
        new_symbols,
597
3159
    ))
598
7425
}
599

            
600
/// Converts SafeDiv of SATInts to a single SATInt
601
///
602
/// ```text
603
/// SafeDiv(SATInt(a), SATInt(b)) ~> SATInt(c)
604
///
605
/// ```
606
#[register_rule("SAT", 4100, [SafeDiv])]
607
194868
fn cnf_int_safediv(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
608
194868
    let Expr::SafeDiv(_, numer, denom) = expr else {
609
27
        return Err(RuleNotApplicable);
610
    };
611
194841
    encode_div_mod(numer, denom, symbols, false)
612
194868
}
613

            
614
/// Reuses restoring division's remainder, with Essence's floor-modulo semantics.
615
#[register_rule("SAT", 4100, [SafeMod])]
616
644805
fn cnf_int_safemod(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
617
644805
    let Expr::SafeMod(_, numer, denom) = expr else {
618
27
        return Err(RuleNotApplicable);
619
    };
620
644778
    encode_div_mod(numer, denom, symbols, true)
621
644805
}
622

            
623
839619
fn encode_div_mod(
624
839619
    numer: &Expr,
625
839619
    denom: &Expr,
626
839619
    symbols: &SymbolTable,
627
839619
    modulo: bool,
628
839619
) -> ApplicationResult {
629
    // Restoring division computes both quotient and remainder magnitudes.
630

            
631
839619
    let Expr::SATInt(_, _, _, (numer_min, numer_max)) = numer else {
632
162945
        return Err(RuleNotApplicable);
633
    };
634

            
635
676674
    let Expr::SATInt(_, _, _, (denom_min, denom_max)) = denom else {
636
1620
        return Err(RuleNotApplicable);
637
    };
638

            
639
675054
    let (min, max) = if modulo {
640
        // Remainders have the divisor's sign; include the safe zero-divisor dummy.
641
        (
642
483228
            if *denom_min < 0 { denom_min + 1 } else { 0 },
643
483228
            if *denom_max > 0 { denom_max - 1 } else { 0 },
644
        )
645
    } else {
646
191826
        division_bounds((*numer_min, *numer_max), (*denom_min, *denom_max))
647
191826
            .ok_or(RuleNotApplicable)?
648
    };
649

            
650
675054
    let binding = validate_log_int_operands(vec![numer.clone(), denom.clone()], None)?;
651
266310
    let [numer_bits, denom_bits] = binding.as_slice() else {
652
        return Err(RuleNotApplicable);
653
    };
654

            
655
    // Widen before taking absolute values: abs(MIN) needs an additional sign bit.
656
266310
    let mut numer_bits = numer_bits.clone();
657
266310
    let mut denom_bits = denom_bits.clone();
658
266310
    numer_bits.push(numer_bits.last().unwrap().clone());
659
266310
    denom_bits.push(denom_bits.last().unwrap().clone());
660
266310
    let bit_count = numer_bits.len();
661

            
662
266310
    let mut new_symbols = symbols.clone();
663
266310
    let mut new_sat_decisions = vec![];
664
266310
    let mut quotient = vec![false.into(); bit_count];
665

            
666
266310
    let minus_numer = tseytin_negate(
667
266310
        &numer_bits.clone(),
668
266310
        bit_count,
669
266310
        &mut new_sat_decisions,
670
266310
        &mut new_symbols,
671
266310
    );
672
266310
    let minus_denom = tseytin_negate(
673
266310
        &denom_bits.clone(),
674
266310
        bit_count,
675
266310
        &mut new_sat_decisions,
676
266310
        &mut new_symbols,
677
266310
    );
678

            
679
266310
    let denom_sign = denom_bits[bit_count - 1].clone();
680
266310
    let sign_bit = tseytin_xor(
681
266310
        numer_bits[bit_count - 1].clone(),
682
266310
        denom_bits[bit_count - 1].clone(),
683
266310
        &mut new_sat_decisions,
684
266310
        &mut new_symbols,
685
266310
    );
686

            
687
266310
    let numer_bits = tseytin_select_array(
688
266310
        numer_bits[bit_count - 1].clone(),
689
266310
        &numer_bits.clone(),
690
266310
        &minus_numer,
691
266310
        &mut new_sat_decisions,
692
266310
        &mut new_symbols,
693
266310
    );
694
266310
    let denom_bits = tseytin_select_array(
695
266310
        denom_bits[bit_count - 1].clone(),
696
266310
        &denom_bits.clone(),
697
266310
        &minus_denom,
698
266310
        &mut new_sat_decisions,
699
266310
        &mut new_symbols,
700
266310
    );
701

            
702
266310
    let mut r = numer_bits;
703
266310
    r.extend(std::iter::repeat_n(r[bit_count - 1].clone(), bit_count));
704
266310
    let mut d = std::iter::repeat_n(false.into(), bit_count).collect_vec();
705
266310
    d.extend(denom_bits.clone());
706

            
707
266310
    let minus_d = tseytin_negate(
708
266310
        &d.clone(),
709
266310
        2 * bit_count,
710
266310
        &mut new_sat_decisions,
711
266310
        &mut new_symbols,
712
266310
    );
713
    let mut rminusd;
714

            
715
266310
    for i in (0..bit_count).rev() {
716
        // r << 1
717
1349262
        for j in (1..bit_count * 2).rev() {
718
12986082
            r[j] = r[j - 1].clone();
719
        }
720
1349262
        r[0] = false.into();
721

            
722
1349262
        rminusd = tseytin_int_adder(
723
1349262
            &r.clone(),
724
1349262
            &minus_d.clone(),
725
1349262
            2 * bit_count,
726
1349262
            &mut new_sat_decisions,
727
1349262
            &mut new_symbols,
728
1349262
        );
729

            
730
1349262
        quotient[i] = tseytin_not(
731
            // q[i] = inverse of sign bit - 1 if positive, 0 if negative
732
1349262
            rminusd[2 * bit_count - 1].clone(),
733
1349262
            &mut new_sat_decisions,
734
1349262
            &mut new_symbols,
735
1349262
        );
736

            
737
1349262
        for j in 0..(2 * bit_count) {
738
14335344
            r[j] = tseytin_mux(
739
14335344
                quotient[i].clone(),
740
14335344
                r[j].clone(),       // use r if negative
741
14335344
                rminusd[j].clone(), // use r-d if positive
742
14335344
                &mut new_sat_decisions,
743
14335344
                &mut new_symbols,
744
14335344
            );
745
        }
746
    }
747

            
748
    // Opposite signs and a nonzero remainder require one more unit of magnitude
749
    // before negation to obtain floor division rather than truncating division.
750
266310
    let remainder_nonzero = tseytin_or(&r, &mut new_sat_decisions, &mut new_symbols);
751
266310
    let round_down = tseytin_and(
752
266310
        &[sign_bit.clone(), remainder_nonzero],
753
266310
        &mut new_sat_decisions,
754
266310
        &mut new_symbols,
755
266310
    );
756
266310
    let out = if modulo {
757
194049
        let remainder = r[bit_count..].to_vec();
758
194049
        let minus_remainder = tseytin_negate(
759
194049
            &remainder,
760
194049
            bit_count,
761
194049
            &mut new_sat_decisions,
762
194049
            &mut new_symbols,
763
194049
        );
764
194049
        let complement = tseytin_int_adder(
765
194049
            &denom_bits,
766
194049
            &minus_remainder,
767
194049
            bit_count,
768
194049
            &mut new_sat_decisions,
769
194049
            &mut new_symbols,
770
194049
        );
771
194049
        let magnitude = tseytin_select_array(
772
194049
            round_down,
773
194049
            &remainder,
774
194049
            &complement,
775
194049
            &mut new_sat_decisions,
776
194049
            &mut new_symbols,
777
194049
        );
778
194049
        let negative = tseytin_negate(
779
194049
            &magnitude,
780
194049
            bit_count,
781
194049
            &mut new_sat_decisions,
782
194049
            &mut new_symbols,
783
194049
        );
784
194049
        tseytin_select_array(
785
194049
            denom_sign,
786
194049
            &magnitude,
787
194049
            &negative,
788
194049
            &mut new_sat_decisions,
789
194049
            &mut new_symbols,
790
194049
        )
791
    } else {
792
72261
        let mut correction = vec![false.into(); bit_count];
793
72261
        correction[0] = round_down;
794
72261
        quotient = tseytin_int_adder(
795
72261
            &quotient,
796
72261
            &correction,
797
72261
            bit_count,
798
72261
            &mut new_sat_decisions,
799
72261
            &mut new_symbols,
800
72261
        );
801

            
802
72261
        let minus_quotient = tseytin_negate(
803
72261
            &quotient.clone(),
804
72261
            bit_count,
805
72261
            &mut new_sat_decisions,
806
72261
            &mut new_symbols,
807
72261
        );
808

            
809
72261
        tseytin_select_array(
810
72261
            sign_bit,
811
72261
            &quotient,
812
72261
            &minus_quotient,
813
72261
            &mut new_sat_decisions,
814
72261
            &mut new_symbols,
815
72261
        )
816
    };
817

            
818
    // Safe division and modulo must keep zero-divisor dummy values within their bounds.
819
    // Definedness is handled separately by the bubble rules, including under negation.
820
266310
    let nonzero = tseytin_or(&denom_bits, &mut new_sat_decisions, &mut new_symbols);
821
266310
    let out = tseytin_select_array(
822
266310
        nonzero,
823
266310
        &vec![false.into(); bit_count],
824
266310
        &out,
825
266310
        &mut new_sat_decisions,
826
266310
        &mut new_symbols,
827
266310
    );
828

            
829
266310
    Ok(RuleEffect::sat(
830
266310
        Expr::SATInt(
831
266310
            Metadata::new(),
832
266310
            SATIntEncoding::Log,
833
266310
            Moo::new(into_matrix_expr!(out)),
834
266310
            (min, max),
835
266310
        ),
836
266310
        new_sat_decisions,
837
266310
        new_symbols,
838
266310
    ))
839
839619
}
840

            
841
// Quotient extrema can occur at the nonzero denominators closest to zero.
842
191826
fn division_bounds(numerator: (i32, i32), denominator: (i32, i32)) -> Option<(i32, i32)> {
843
191826
    let mut values = Vec::new();
844
191826
    for divisor in [denominator.0, denominator.1, -1, 1] {
845
767304
        if divisor == 0 || divisor < denominator.0 || divisor > denominator.1 {
846
309807
            continue;
847
457497
        }
848
457497
        for dividend in [numerator.0, numerator.1] {
849
914994
            values.push(super::super::floor_div(dividend, divisor)?);
850
        }
851
    }
852
191826
    if denominator.0 <= 0 && denominator.1 >= 0 {
853
8685
        values.push(0);
854
183141
    }
855
191826
    Some((*values.iter().min()?, *values.iter().max()?))
856
191826
}
857

            
858
/// Lower power using exponentiation by squaring and the existing Boolean circuit decisions.
859
/// Undefined inputs retain a harmless value; their definedness is handled by the bubble rules.
860
#[register_rule("SAT", 4100, [SafePow])]
861
16911
fn cnf_int_safepow(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
862
16911
    let Expr::SafePow(_, base, exponent) = expr else {
863
27
        return Err(RuleNotApplicable);
864
    };
865
    let (
866
        Expr::SATInt(_, SATIntEncoding::Log, _, base_bounds),
867
        Expr::SATInt(_, SATIntEncoding::Log, exponent_bits, exponent_bounds),
868
16884
    ) = (base.as_ref(), exponent.as_ref())
869
    else {
870
11187
        return Err(RuleNotApplicable);
871
    };
872
    // Endpoints bound both parities; include zero and the unspecified values 0/1.
873
    // Decline machine-overflowing ranges instead of silently wrapping their mathematical powers.
874
5697
    let mut bounds = (0, 1);
875
5697
    if exponent_bounds.1 > 31 && (base_bounds.0 < -1 || base_bounds.1 > 1) {
876
        return Err(RuleNotApplicable);
877
5697
    }
878
5697
    for power in 0..=exponent_bounds.1.clamp(0, 31) {
879
24651
        for value in [base_bounds.0, base_bounds.1] {
880
49302
            let result = value.checked_pow(power as u32).ok_or(RuleNotApplicable)?;
881
49302
            bounds.0 = bounds.0.min(result);
882
49302
            bounds.1 = bounds.1.max(result);
883
        }
884
    }
885
5697
    let width = bit_magnitude(bounds.0).max(bit_magnitude(bounds.1)).max(2);
886
    let mut factor =
887
5697
        validate_log_int_operands(vec![(**base).clone()], Some(width as u32))?.remove(0);
888
5697
    let exponent_bits = exponent_bits.unwrap_list_cow().ok_or(RuleNotApplicable)?;
889
5697
    let mut result = vec![Expr::from(false); width];
890
5697
    result[0] = true.into();
891
5697
    let mut decisions = vec![];
892
5697
    let mut symbols = symbols.clone();
893
5697
    let mut result_is_one = true;
894
    // Only non-sign bits can participate in a defined, non-negative exponent.
895
5697
    for (index, selected) in exponent_bits[..exponent_bits.len() - 1].iter().enumerate() {
896
13734
        let selected_constant = conjure_cp::ast::eval_constant(selected);
897
13734
        if selected_constant != Some(false.into()) {
898
12744
            let mut product = if result_is_one {
899
5697
                factor.clone()
900
            } else {
901
7047
                cnf_shift_add_multiply(&result, &factor, width, &mut decisions, &mut symbols)
902
            };
903
12744
            product.truncate(width);
904
12744
            result = if selected_constant == Some(true.into()) {
905
990
                product
906
            } else {
907
11754
                result
908
11754
                    .iter()
909
11754
                    .zip(product)
910
111222
                    .map(|(old, new)| {
911
111222
                        tseytin_mux(
912
111222
                            selected.clone(),
913
111222
                            old.clone(),
914
111222
                            new,
915
111222
                            &mut decisions,
916
111222
                            &mut symbols,
917
111222
                        )
918
111222
                    })
919
                    .collect()
920
            };
921
12744
            result_is_one = false;
922
990
        }
923
13734
        if index + 1 < exponent_bits.len() - 1 {
924
8037
            factor = cnf_shift_add_multiply(&factor, &factor, width, &mut decisions, &mut symbols);
925
8037
            factor.truncate(width);
926
5697
        }
927
    }
928
5697
    let negative = exponent_bits.last().ok_or(RuleNotApplicable)?;
929
5697
    if conjure_cp::ast::eval_constant(negative) != Some(false.into()) {
930
2952
        for bit in &mut result {
931
23526
            *bit = tseytin_mux(
932
23526
                negative.clone(),
933
23526
                bit.clone(),
934
23526
                false.into(),
935
23526
                &mut decisions,
936
23526
                &mut symbols,
937
23526
            );
938
        }
939
2745
    }
940
5697
    Ok(RuleEffect::sat(
941
5697
        Expr::SATInt(
942
5697
            Metadata::new(),
943
5697
            SATIntEncoding::Log,
944
5697
            Moo::new(into_matrix_expr!(result)),
945
5697
            bounds,
946
5697
        ),
947
5697
        decisions,
948
5697
        symbols,
949
5697
    ))
950
16911
}