1
use conjure_cp::ast::Metadata;
2
use conjure_cp::ast::{Atom, Expression as Expr, Moo, SatEncodingDecision};
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::{Domain, SymbolTable};
9

            
10
// Atomic references can denote integers and compound values too. Those must reach their
11
// representation's comparison rules rather than becoming Boolean gate inputs.
12
52154471
fn is_literal(expr: &Expr) -> bool {
13
52154471
    crate::shared::utils::is_literal(expr)
14
39631634
        && expr.domain_of().is_some_and(|domain| domain.is_bool())
15
52154471
}
16

            
17
184438325
pub(super) fn create_bool_aux(symbols: &mut SymbolTable) -> Expr {
18
184438325
    let name = symbols.gen_find_auxiliary(&Domain::bool());
19

            
20
184438325
    symbols.insert(name.clone());
21

            
22
184438325
    Expr::Atomic(
23
184438325
        Metadata::new(),
24
184438325
        Atom::Reference(conjure_cp::ast::Reference::new(name)),
25
184438325
    )
26
184438325
}
27

            
28
/// Boolean order is false before true and shares the existing gate decisions.
29
#[register_rule("SAT", 18500, [Lt, Gt, Leq, Geq])]
30
8506082
fn boolean_order(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
31
8506082
    let (left, right, strict) = match expr {
32
2722019
        Expr::Lt(_, left, right) => (left, right, true),
33
296896
        Expr::Gt(_, left, right) => (right, left, true),
34
4318058
        Expr::Leq(_, left, right) => (left, right, false),
35
1169082
        Expr::Geq(_, left, right) => (right, left, false),
36
27
        _ => return Err(RuleNotApplicable),
37
    };
38
8506055
    if [left, right]
39
8506055
        .iter()
40
8519654
        .any(|operand| !operand.domain_of().is_some_and(|domain| domain.is_bool()))
41
    {
42
8492456
        return Err(RuleNotApplicable);
43
13599
    }
44
13599
    Ok(RuleEffect::pure(if strict {
45
13599
        Expr::And(
46
13599
            Metadata::new(),
47
13599
            Moo::new(conjure_cp::into_matrix_expr!(vec![
48
13599
                Expr::Not(Metadata::new(), left.clone()),
49
13599
                (**right).clone(),
50
13599
            ])),
51
13599
        )
52
    } else {
53
        Expr::Imply(Metadata::new(), left.clone(), right.clone())
54
    }))
55
8506082
}
56

            
57
/// Record an AND gate without generating clauses.
58
67302877
pub fn tseytin_and(
59
67302877
    exprs: &[Expr],
60
67302877
    decisions: &mut Vec<SatEncodingDecision>,
61
67302877
    symbols: &mut SymbolTable,
62
67302877
) -> Expr {
63
67302877
    gate(
64
67302877
        Expr::And(
65
67302877
            Metadata::new(),
66
67302877
            Moo::new(conjure_cp::into_matrix_expr!(exprs.to_vec())),
67
67302877
        ),
68
67302877
        decisions,
69
67302877
        symbols,
70
67302877
    )
71
67302877
}
72

            
73
/// Record a NOT gate without generating clauses.
74
11439182
pub fn tseytin_not(
75
11439182
    x: Expr,
76
11439182
    decisions: &mut Vec<SatEncodingDecision>,
77
11439182
    symbols: &mut SymbolTable,
78
11439182
) -> Expr {
79
11439182
    gate(Expr::Not(Metadata::new(), Moo::new(x)), decisions, symbols)
80
11439182
}
81

            
82
/// Record an OR gate without generating clauses.
83
29774539
pub fn tseytin_or(
84
29774539
    exprs: &[Expr],
85
29774539
    decisions: &mut Vec<SatEncodingDecision>,
86
29774539
    symbols: &mut SymbolTable,
87
29774539
) -> Expr {
88
29774539
    gate(
89
29774539
        Expr::Or(
90
29774539
            Metadata::new(),
91
29774539
            Moo::new(conjure_cp::into_matrix_expr!(exprs.to_vec())),
92
29774539
        ),
93
29774539
        decisions,
94
29774539
        symbols,
95
29774539
    )
96
29774539
}
97

            
98
/// Record a Boolean equivalence gate.
99
37149
pub fn tseytin_iff(
100
37149
    x: Expr,
101
37149
    y: Expr,
102
37149
    decisions: &mut Vec<SatEncodingDecision>,
103
37149
    symbols: &mut SymbolTable,
104
37149
) -> Expr {
105
37149
    gate(
106
37149
        Expr::Iff(Metadata::new(), Moo::new(x), Moo::new(y)),
107
37149
        decisions,
108
37149
        symbols,
109
37149
    )
110
37149
}
111

            
112
/// Record a Boolean implication gate.
113
2532
pub fn tseytin_imply(
114
2532
    x: Expr,
115
2532
    y: Expr,
116
2532
    decisions: &mut Vec<SatEncodingDecision>,
117
2532
    symbols: &mut SymbolTable,
118
2532
) -> Expr {
119
2532
    gate(
120
2532
        Expr::Imply(Metadata::new(), Moo::new(x), Moo::new(y)),
121
2532
        decisions,
122
2532
        symbols,
123
2532
    )
124
2532
}
125

            
126
/// Record a conditional Boolean choice.
127
#[allow(dead_code)]
128
21079715
pub fn tseytin_mux(
129
21079715
    cond: Expr,
130
21079715
    a: Expr,
131
21079715
    b: Expr,
132
21079715
    decisions: &mut Vec<SatEncodingDecision>,
133
21079715
    symbols: &mut SymbolTable,
134
21079715
) -> Expr {
135
21079715
    let when_true = Expr::And(
136
21079715
        Metadata::new(),
137
21079715
        Moo::new(conjure_cp::into_matrix_expr!(vec![cond.clone(), b])),
138
21079715
    );
139
21079715
    let when_false = Expr::And(
140
21079715
        Metadata::new(),
141
21079715
        Moo::new(conjure_cp::into_matrix_expr!(vec![
142
21079715
            Expr::Not(Metadata::new(), Moo::new(cond)),
143
21079715
            a
144
21079715
        ])),
145
21079715
    );
146
21079715
    gate(
147
21079715
        Expr::Or(
148
21079715
            Metadata::new(),
149
21079715
            Moo::new(conjure_cp::into_matrix_expr!(vec![when_true, when_false])),
150
21079715
        ),
151
21079715
        decisions,
152
21079715
        symbols,
153
21079715
    )
154
21079715
}
155

            
156
/// Record a Boolean exclusive-or gate.
157
#[allow(dead_code)]
158
51769905
pub fn tseytin_xor(
159
51769905
    x: Expr,
160
51769905
    y: Expr,
161
51769905
    decisions: &mut Vec<SatEncodingDecision>,
162
51769905
    symbols: &mut SymbolTable,
163
51769905
) -> Expr {
164
51769905
    gate(
165
51769905
        Expr::Not(
166
51769905
            Metadata::new(),
167
51769905
            Moo::new(Expr::Iff(Metadata::new(), Moo::new(x), Moo::new(y))),
168
51769905
        ),
169
51769905
        decisions,
170
51769905
        symbols,
171
51769905
    )
172
51769905
}
173

            
174
181405899
fn gate(
175
181405899
    expression: Expr,
176
181405899
    decisions: &mut Vec<SatEncodingDecision>,
177
181405899
    symbols: &mut SymbolTable,
178
181405899
) -> Expr {
179
181405899
    let output = create_bool_aux(symbols);
180
181405899
    decisions.push(SatEncodingDecision::Boolean {
181
181405899
        output: output.clone(),
182
181405899
        expression,
183
181405899
    });
184
181405899
    output
185
181405899
}
186

            
187
/// Preserve ready assertions before the ordinary equivalence-gate rules consume them.
188
#[register_rule("SAT", 18000, [Root])]
189
8020324
fn select_asserted_boolean(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
190
55154313
    super::asserted::select_asserted(expr, symbols, |child| {
191
55154313
        (child != &true.into() && ready_boolean(child))
192
3170959
            .then(|| SatEncodingDecision::Assert(child.clone()))
193
55154313
    })
194
8020324
}
195

            
196
81738600
fn ready_boolean(expr: &Expr) -> bool {
197
81738600
    match expr {
198
21444519
        Expr::Atomic(..) => is_literal(expr),
199
1824686
        Expr::Not(_, input) => ready_boolean(input),
200
        Expr::And(_, inputs) | Expr::Or(_, inputs) => {
201
18673534
            matches!(inputs.as_ref(), Expr::AbstractLiteral(_, Matrix(entries, _))
202
17352910
                if entries.iter().all(ready_boolean))
203
        }
204
        Expr::Imply(_, left, right)
205
        | Expr::Iff(_, left, right)
206
        | Expr::Eq(_, left, right)
207
16139456
        | Expr::Neq(_, left, right) => ready_boolean(left) && ready_boolean(right),
208
23656405
        _ => false,
209
    }
210
81738600
}
211

            
212
/// Lower the Boolean operation to a semantic SAT gate decision.
213
#[register_rule("SAT", 8500, [And, Or])]
214
4367001
fn apply_tseytin_and_or(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
215
4367001
    let exprs = match expr {
216
4366974
        Expr::And(_, exprs) | Expr::Or(_, exprs) => exprs,
217
27
        _ => return Err(RuleNotApplicable),
218
    };
219

            
220
4366974
    let Expr::AbstractLiteral(_, Matrix(exprs_list, _)) = exprs.as_ref() else {
221
187082
        return Err(RuleNotApplicable);
222
    };
223

            
224
4179892
    for x in exprs_list {
225
7130140
        if !is_literal(x) {
226
3961228
            return Err(RuleNotApplicable);
227
3168912
        };
228
    }
229

            
230
    let new_expr;
231
218664
    let mut new_sat_decisions = vec![];
232
218664
    let mut new_symbols = symbols.clone();
233

            
234
218664
    match expr {
235
        Expr::And(_, _) => {
236
159904
            new_expr = tseytin_and(exprs_list, &mut new_sat_decisions, &mut new_symbols);
237
        }
238
        Expr::Or(_, _) => {
239
58760
            new_expr = tseytin_or(exprs_list, &mut new_sat_decisions, &mut new_symbols);
240
        }
241
        _ => return Err(RuleNotApplicable),
242
    };
243

            
244
218664
    Ok(RuleEffect::sat(new_expr, new_sat_decisions, new_symbols))
245
4367001
}
246

            
247
/// Lower the Boolean operation to a semantic SAT gate decision.
248
#[register_rule("SAT", 9005, [Not])]
249
131438
fn apply_tseytin_not(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
250
131438
    let Expr::Not(_, x) = expr else {
251
27
        return Err(RuleNotApplicable);
252
    };
253

            
254
131411
    let Expr::Atomic(_, _) = x.as_ref() else {
255
110493
        return Err(RuleNotApplicable);
256
    };
257

            
258
20918
    if !is_literal(x.as_ref()) {
259
        return Err(RuleNotApplicable);
260
20918
    };
261

            
262
20918
    let mut new_sat_decisions = vec![];
263
20918
    let mut new_symbols = symbols.clone();
264

            
265
20918
    let new_expr = tseytin_not(x.as_ref().clone(), &mut new_sat_decisions, &mut new_symbols);
266

            
267
20918
    Ok(RuleEffect::sat(new_expr, new_sat_decisions, new_symbols))
268
131438
}
269

            
270
/// Lower the Boolean operation to a semantic SAT gate decision.
271
#[register_rule("SAT", 8500, [Iff, Eq])]
272
3631253
fn apply_tseytin_iff_eq(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
273
    // Check for iff or eq
274
3631253
    let (x, y) = match expr {
275
3631226
        Expr::Iff(_, x, y) | Expr::Eq(_, x, y) => (x, y),
276
27
        _ => return Err(RuleNotApplicable),
277
    };
278

            
279
3631226
    if !is_literal(x.as_ref()) || !is_literal(y.as_ref()) {
280
3630617
        return Err(RuleNotApplicable);
281
609
    };
282

            
283
609
    let mut new_sat_decisions = vec![];
284
609
    let mut new_symbols = symbols.clone();
285

            
286
609
    let new_expr = tseytin_iff(
287
609
        x.as_ref().clone(),
288
609
        y.as_ref().clone(),
289
609
        &mut new_sat_decisions,
290
609
        &mut new_symbols,
291
609
    );
292

            
293
609
    Ok(RuleEffect::sat(new_expr, new_sat_decisions, new_symbols))
294
3631253
}
295

            
296
/// Lower the Boolean operation to a semantic SAT gate decision.
297
#[register_rule("SAT", 8500, [Imply])]
298
80814
fn apply_tseytin_imply(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
299
80814
    let Expr::Imply(_, x, y) = expr else {
300
27
        return Err(RuleNotApplicable);
301
    };
302

            
303
80787
    if !is_literal(x.as_ref()) || !is_literal(y.as_ref()) {
304
78255
        return Err(RuleNotApplicable);
305
2532
    };
306

            
307
    let new_expr;
308
2532
    let mut new_sat_decisions = vec![];
309
2532
    let mut new_symbols = symbols.clone();
310

            
311
2532
    new_expr = tseytin_imply(
312
2532
        x.as_ref().clone(),
313
2532
        y.as_ref().clone(),
314
2532
        &mut new_sat_decisions,
315
2532
        &mut new_symbols,
316
2532
    );
317

            
318
2532
    Ok(RuleEffect::sat(new_expr, new_sat_decisions, new_symbols))
319
80814
}
320

            
321
/// Lower the Boolean operation to a semantic SAT gate decision.
322
#[register_rule("SAT", 8500, [Neq])]
323
126630
fn apply_tseytin_xor_neq(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
324
126630
    let Expr::Neq(_, x, y) = expr else {
325
27
        return Err(RuleNotApplicable);
326
    };
327

            
328
126603
    if !is_literal(x.as_ref()) || !is_literal(y.as_ref()) {
329
119673
        return Err(RuleNotApplicable);
330
6930
    };
331

            
332
6930
    let mut new_sat_decisions = vec![];
333
6930
    let mut new_symbols = symbols.clone();
334

            
335
6930
    let new_expr = tseytin_xor(
336
6930
        x.as_ref().clone(),
337
6930
        y.as_ref().clone(),
338
6930
        &mut new_sat_decisions,
339
6930
        &mut new_symbols,
340
6930
    );
341

            
342
6930
    Ok(RuleEffect::sat(new_expr, new_sat_decisions, new_symbols))
343
126630
}
344

            
345
/// Shared recognition keeps asserted Boolean counts in their own encoding family.
346
15779677
pub(super) fn count_inputs(sum: &Expr) -> Option<Vec<Expr>> {
347
15779677
    let Expr::AbstractLiteral(_, Matrix(terms, _)) = sum else {
348
622071
        return None;
349
    };
350
15157606
    terms
351
15157606
        .iter()
352
28114204
        .map(|term| match term {
353
            Expr::ToInt(_, input)
354
19486386
                if is_literal(input)
355
14731308
                    && input.domain_of().is_some_and(|domain| domain.is_bool()) =>
356
            {
357
14731308
                Some(input.as_ref().clone())
358
            }
359
            Expr::Atomic(_, Atom::Literal(conjure_cp::ast::Literal::Int(value)))
360
904743
                if *value == 0 || *value == 1 =>
361
            {
362
361719
                Some((*value == 1).into())
363
            }
364
13021177
            _ => None,
365
28114204
        })
366
        .collect::<Option<Vec<_>>>()
367
15779677
}
368

            
369
/// Preserve asserted Boolean counts until a library encoder is selected.
370
#[register_rule("SAT", 20000, [Root])]
371
10017084
fn select_cardinality(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
372
    use conjure_cp::ast::sat_decision::CardinalityRelation;
373
98721215
    super::asserted::select_asserted(expr, symbols, |child| {
374
98721215
        let (left, right, mut relation) = match child {
375
3972085
            Expr::Leq(_, left, right) => (left, right, CardinalityRelation::AtMost),
376
1151563
            Expr::Geq(_, left, right) => (left, right, CardinalityRelation::AtLeast),
377
8081663
            Expr::Eq(_, left, right) => (left, right, CardinalityRelation::Exactly),
378
85515904
            _ => return None,
379
        };
380
13205311
        let (sum, bound) = match (left.as_ref(), right.as_ref()) {
381
            (
382
                Expr::Sum(_, terms),
383
                Expr::Atomic(_, Atom::Literal(conjure_cp::ast::Literal::Int(bound))),
384
5666908
            ) => (terms, *bound),
385
            (
386
                Expr::Atomic(_, Atom::Literal(conjure_cp::ast::Literal::Int(bound))),
387
                Expr::Sum(_, terms),
388
            ) => {
389
34065
                relation = match relation {
390
                    CardinalityRelation::AtMost => CardinalityRelation::AtLeast,
391
                    CardinalityRelation::AtLeast => CardinalityRelation::AtMost,
392
34065
                    other => other,
393
                };
394
34065
                (terms, *bound)
395
            }
396
7504338
            _ => return None,
397
        };
398
5700973
        let inputs = count_inputs(sum)?;
399
830790
        Some(if relation == CardinalityRelation::AtMost && bound == 1 {
400
747729
            SatEncodingDecision::AtMostOne {
401
747729
                inputs,
402
747729
                encoding: None,
403
747729
            }
404
        } else {
405
83061
            SatEncodingDecision::Cardinality {
406
83061
                inputs,
407
83061
                relation,
408
83061
                bound: i64::from(bound),
409
83061
                encoding: None,
410
83061
            }
411
        })
412
98721215
    })
413
10017084
}