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

            
7
use crate::types::int::{
8
    IntBinaryOffset, IntBinaryRank, IntBinarySignMagnitude, IntBinaryTwosComplement,
9
};
10

            
11
/// Normalise logarithmic SAT integer operands to a common bit width.
12
781830
pub(super) fn validate_log_int_operands(
13
781830
    exprs: Vec<Expr>,
14
781830
    bit_count: Option<u32>,
15
781830
) -> Result<Vec<Vec<Expr>>, ApplicationError> {
16
781830
    let mut out: Vec<Vec<Expr>> = exprs
17
781830
        .into_iter()
18
1093410
        .map(|expr| match expr {
19
            Expr::SATInt(_, SATIntEncoding::Log, inner, _) => {
20
629478
                inner.as_ref().clone().into_list().ok_or(RuleNotApplicable)
21
            }
22
463932
            _ => Err(RuleNotApplicable),
23
1093410
        })
24
463932
        .collect::<Result<_, _>>()?;
25

            
26
317898
    let max_len = bit_count
27
5697
        .map(|bits| bits as usize)
28
312201
        .unwrap_or_else(|| out.iter().map(Vec::len).max().unwrap_or(0));
29
317898
    for bits in &mut out {
30
629478
        if bits.len() < max_len {
31
200025
            if let Some(last) = bits.last().cloned() {
32
200025
                bits.resize(max_len, last);
33
            }
34
        } else {
35
429453
            bits.truncate(max_len);
36
        }
37
    }
38
317898
    Ok(out)
39
781830
}
40

            
41
/// Replace a log-represented reference with its bit vector.
42
#[register_rule("SAT", 9500, [Atomic])]
43
49438685
fn integer_decision_representation_log(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
44
49438685
    let Expr::Atomic(_, Atom::Reference(reference)) = expr else {
45
16991985
        return Err(RuleNotApplicable);
46
    };
47
32446700
    let state = reference
48
32446700
        .get_repr_as::<IntBinaryTwosComplement>()
49
32446700
        .ok_or(RuleNotApplicable)?;
50
62505
    Ok(RuleEffect::pure(state.sat_int_expr()))
51
49438685
}
52

            
53
/// Number of bits required to encode an `i32` in two's complement.
54
1269779
pub(in crate::backends::sat) fn bit_magnitude(value: i32) -> usize {
55
1269779
    if value >= 0 {
56
1187735
        (1 + (32 - value.leading_zeros())).try_into().unwrap()
57
    } else {
58
82044
        (33 - (!value).leading_zeros()).try_into().unwrap()
59
    }
60
1269779
}
61

            
62
/// Sign-extend the shorter of two bit vectors to the length of the longer one.
63
31410
pub(super) fn match_bits_length(mut lhs: Vec<Expr>, mut rhs: Vec<Expr>) -> (Vec<Expr>, Vec<Expr>) {
64
31410
    if lhs.len() < rhs.len() {
65
315
        lhs.resize(rhs.len(), lhs.last().cloned().unwrap());
66
31095
    } else if rhs.len() < lhs.len() {
67
855
        rhs.resize(lhs.len(), rhs.last().cloned().unwrap());
68
30240
    }
69
31410
    (lhs, rhs)
70
31410
}
71

            
72
/// Materialise unsigned codes without treating rank as the semantic numeric value.
73
#[register_rule("SAT", 9500, [Atomic])]
74
49438685
fn integer_decision_representation_unsigned(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
75
49438685
    let Expr::Atomic(_, Atom::Reference(reference)) = expr else {
76
16991985
        return Err(RuleNotApplicable);
77
    };
78
32446700
    let represented = if let Some(state) = reference.get_repr_as::<IntBinaryOffset>() {
79
77580
        state.sat_int_expr()
80
32369120
    } else if let Some(state) = reference.get_repr_as::<IntBinaryRank>() {
81
86912
        state.sat_int_expr()
82
32282208
    } else if let Some(state) = reference.get_repr_as::<IntBinarySignMagnitude>() {
83
62505
        state.sat_int_expr()
84
    } else {
85
32219703
        return Err(RuleNotApplicable);
86
    };
87
226997
    Ok(RuleEffect::pure(represented))
88
49438685
}