1
//! Retain allDifferent as a semantic decision until library clause generation.
2
use conjure_cp::ast::{
3
    Expression as Expr, Metadata, Moo, ReturnType, SatEncodingDecision, SymbolTable, Typeable,
4
};
5
use conjure_cp::rule_engine::{
6
    ApplicationError::RuleNotApplicable, ApplicationResult, RuleEffect, register_rule,
7
};
8

            
9
/// Preserve ready numeric operands, including nested Boolean uses.
10
#[register_rule("SAT", 18500, [AllDiff, AllDifferentExcept])]
11
434826
fn select_alldifferent(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
12
434826
    let (matrix, except) = match expr {
13
241119
        Expr::AllDiff(_, matrix) => (matrix, None),
14
        Expr::AllDifferentExcept(_, matrix, except) => {
15
193680
            let value = super::pseudo_boolean::integer_view(except).ok_or(RuleNotApplicable)?;
16
124965
            (matrix, Some(value))
17
        }
18
27
        _ => return Err(RuleNotApplicable),
19
    };
20
366084
    let elements = super::counting::matrix_entries(matrix).ok_or(RuleNotApplicable)?;
21
208674
    let inputs = elements
22
208674
        .iter()
23
208674
        .map(super::pseudo_boolean::integer_view)
24
208674
        .collect::<Option<Vec<_>>>()
25
208674
        .ok_or(RuleNotApplicable)?;
26
29745
    let mut symbols = symbols.clone();
27
29745
    let output = super::boolean::create_bool_aux(&mut symbols);
28
29745
    Ok(RuleEffect::sat(
29
29745
        output.clone(),
30
29745
        vec![SatEncodingDecision::AllDifferent {
31
29745
            output,
32
29745
            inputs,
33
29745
            comparisons: None,
34
29745
            except,
35
29745
            encoding: None,
36
29745
            amo_encoding: None,
37
29745
            pb_encoding: None,
38
29745
        }],
39
29745
        symbols,
40
29745
    ))
41
434826
}
42

            
43
/// Construct whole-value comparisons before their representation-specific lowering.
44
#[register_rule("SAT", 18400, [AllDiff, AllDifferentExcept])]
45
387729
fn introduce_compound_alldifferent(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
46
387729
    let (matrix, except) = match expr {
47
215937
        Expr::AllDiff(_, matrix) => (matrix, None),
48
171765
        Expr::AllDifferentExcept(_, matrix, except) => (matrix, Some(except)),
49
27
        _ => return Err(RuleNotApplicable),
50
    };
51
387702
    let inputs = super::counting::matrix_entries(matrix).ok_or(RuleNotApplicable)?;
52
232065
    if inputs.is_empty()
53
252225
        || inputs.iter().any(|input| {
54
252225
            matches!(
55
252225
                input.return_type(),
56
                ReturnType::Int | ReturnType::Bool | ReturnType::Unknown
57
            )
58
252225
        })
59
    {
60
215685
        return Err(RuleNotApplicable);
61
16380
    }
62
16380
    let mut symbols = symbols.clone();
63
16380
    let mut definitions = Vec::new();
64
16380
    let mut conditions = Vec::new();
65
16380
    for (index, left) in inputs.iter().enumerate() {
66
36540
        let exempt = except.filter(|_| index + 1 < inputs.len()).map(|except| {
67
14490
            let output = super::boolean::create_bool_aux(&mut symbols);
68
14490
            definitions.push(Expr::Iff(
69
14490
                Metadata::new(),
70
14490
                Moo::new(output.clone()),
71
14490
                Moo::new(Expr::Eq(
72
14490
                    Metadata::new(),
73
14490
                    Moo::new(left.clone()),
74
14490
                    except.clone(),
75
14490
                )),
76
14490
            ));
77
14490
            output
78
14490
        });
79
36540
        for right in &inputs[index + 1..] {
80
23940
            let unequal = Expr::Neq(
81
23940
                Metadata::new(),
82
23940
                Moo::new(left.clone()),
83
23940
                Moo::new(right.clone()),
84
23940
            );
85
23940
            conditions.push(if let Some(exempt) = &exempt {
86
18270
                Expr::Or(
87
18270
                    Metadata::new(),
88
18270
                    Moo::new(conjure_cp::into_matrix_expr!(vec![unequal, exempt.clone()])),
89
18270
                )
90
            } else {
91
5670
                unequal
92
            });
93
        }
94
    }
95
16380
    Ok(RuleEffect::new(
96
16380
        Expr::SatAllDifferentComparisons(
97
16380
            Metadata::new(),
98
16380
            Moo::new(conjure_cp::into_matrix_expr!(conditions)),
99
16380
        ),
100
16380
        definitions,
101
16380
        symbols,
102
16380
    ))
103
387729
}
104

            
105
/// Keep the allDifferent family choice after whole-value comparisons become Boolean literals.
106
#[register_rule("SAT", 18500, [SatAllDifferentComparisons])]
107
429012
fn select_compound_alldifferent(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
108
429012
    let Expr::SatAllDifferentComparisons(_, comparisons) = expr else {
109
27
        return Err(RuleNotApplicable);
110
    };
111
428985
    let comparisons = comparisons.unwrap_list_cow().ok_or(RuleNotApplicable)?;
112
453330
    if !comparisons.iter().all(|condition| {
113
453330
        condition.return_type() == ReturnType::Bool && crate::shared::utils::is_literal(condition)
114
453330
    }) {
115
412605
        return Err(RuleNotApplicable);
116
16380
    }
117
16380
    let mut symbols = symbols.clone();
118
16380
    let output = super::boolean::create_bool_aux(&mut symbols);
119
16380
    Ok(RuleEffect::sat(
120
16380
        output.clone(),
121
16380
        vec![SatEncodingDecision::AllDifferent {
122
16380
            output,
123
16380
            inputs: vec![],
124
16380
            comparisons: Some(comparisons.into_owned()),
125
16380
            except: None,
126
16380
            encoding: None,
127
16380
            amo_encoding: None,
128
16380
            pb_encoding: None,
129
16380
        }],
130
16380
        symbols,
131
16380
    ))
132
429012
}