1
use conjure_cp::ast::{DomainPtr, GroundDomain, Metadata};
2
use conjure_cp::ast::{Expression, Moo, SymbolTable};
3
use conjure_cp::rule_engine::{
4
    ApplicationError, ApplicationError::RuleNotApplicable, ApplicationResult, Reduction,
5
    register_rule,
6
};
7
use conjure_cp::{bug, into_matrix_expr};
8
use itertools::{Itertools as _, izip};
9

            
10
/// Converts an unsafe index to a safe index using a bubble expression.
11
#[register_rule(("Bubble", 6000))]
12
259742
fn index_to_bubble(expr: &Expression, _: &SymbolTable) -> ApplicationResult {
13
259742
    let Expression::UnsafeIndex(_, subject, indices) = expr else {
14
258473
        return Err(RuleNotApplicable);
15
    };
16

            
17
1269
    let domain = subject
18
1269
        .domain_of()
19
1269
        .ok_or(ApplicationError::DomainError)?
20
1269
        .resolve()
21
1269
        .ok_or(RuleNotApplicable)?;
22

            
23
    // TODO: tuple, this is a hack right now just to avoid the rule being applied to tuples, but could we safely modify the rule to
24
    // handle tuples as well?
25
1269
    if matches!(domain.as_ref(), GroundDomain::Tuple(_))
26
1269
        || matches!(domain.as_ref(), GroundDomain::Record(_))
27
    {
28
        return Err(RuleNotApplicable);
29
1269
    }
30

            
31
1269
    let GroundDomain::Matrix(_, index_domains) = domain.as_ref() else {
32
        bug!(
33
            "subject of an index expression should have a matrix domain. subject: {:?}, with domain: {:?}",
34
            subject,
35
            domain.as_ref()
36
        );
37
    };
38

            
39
1269
    assert_eq!(
40
1269
        index_domains.len(),
41
1269
        indices.len(),
42
        "in an index expression, there should be the same number of indices as the subject has index domains"
43
    );
44

            
45
1269
    let bubble_constraints = Moo::new(into_matrix_expr![
46
1269
        izip!(index_domains, indices)
47
1746
            .map(|(domain, index)| {
48
1746
                Expression::InDomain(
49
1746
                    Metadata::new(),
50
1746
                    Moo::new(index.clone()),
51
1746
                    DomainPtr::from(domain.clone()),
52
1746
                )
53
1746
            })
54
1269
            .collect_vec()
55
    ]);
56

            
57
1269
    let new_expr = Moo::new(Expression::SafeIndex(
58
1269
        Metadata::new(),
59
1269
        subject.clone(),
60
1269
        indices.clone(),
61
1269
    ));
62

            
63
1269
    Ok(Reduction::pure(Expression::Bubble(
64
1269
        Metadata::new(),
65
1269
        new_expr,
66
1269
        Moo::new(Expression::And(Metadata::new(), bubble_constraints)),
67
1269
    )))
68
259742
}
69

            
70
/// Converts an unsafe slice to a safe slice using a bubble expression.
71
#[register_rule(("Bubble", 6000))]
72
259742
fn slice_to_bubble(expr: &Expression, _: &SymbolTable) -> ApplicationResult {
73
259742
    let Expression::UnsafeSlice(_, subject, indices) = expr else {
74
259496
        return Err(RuleNotApplicable);
75
    };
76

            
77
246
    let domain = subject
78
246
        .domain_of()
79
246
        .ok_or(ApplicationError::DomainError)?
80
246
        .resolve()
81
246
        .ok_or(RuleNotApplicable)?;
82

            
83
246
    let GroundDomain::Matrix(_, index_domains) = domain.as_ref() else {
84
        bug!(
85
            "subject of a slice expression should have a matrix domain. subject: {:?}, with domain: {:?}",
86
            subject,
87
            domain
88
        );
89
    };
90

            
91
246
    assert_eq!(
92
246
        index_domains.len(),
93
246
        indices.len(),
94
        "in a slice expression, there should be the same number of indices as the subject has index domains"
95
    );
96

            
97
    // the wildcard dimension doesn't need a constraint.
98
246
    let bubble_constraints = Moo::new(into_matrix_expr![
99
246
        izip!(index_domains, indices)
100
486
            .filter_map(|(domain, index)| {
101
486
                index
102
486
                    .clone()
103
                    // TODO(perf): This pattern of "take something with a ground domain G and re-wrap it in Moo(Domain::Ground(G))" is fairly common...
104
486
                    .map(|index| {
105
240
                        Expression::InDomain(
106
240
                            Metadata::new(),
107
240
                            Moo::new(index),
108
240
                            DomainPtr::from(domain.clone()),
109
240
                        )
110
240
                    })
111
486
            })
112
246
            .collect_vec()
113
    ]);
114

            
115
246
    let new_expr = Moo::new(Expression::SafeSlice(
116
246
        Metadata::new(),
117
246
        subject.clone(),
118
246
        indices.clone(),
119
246
    ));
120

            
121
246
    Ok(Reduction::pure(Expression::Bubble(
122
246
        Metadata::new(),
123
246
        new_expr,
124
246
        Moo::new(Expression::And(Metadata::new(), bubble_constraints)),
125
246
    )))
126
259742
}