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
86468
fn index_to_bubble(expr: &Expression, _: &SymbolTable) -> ApplicationResult {
13
86468
    let Expression::UnsafeIndex(_, subject, indices) = expr else {
14
86042
        return Err(RuleNotApplicable);
15
    };
16

            
17
426
    let domain = subject
18
426
        .domain_of()
19
426
        .ok_or(ApplicationError::DomainError)?
20
426
        .resolve()
21
426
        .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
426
    if matches!(domain.as_ref(), GroundDomain::Tuple(_))
26
426
        || matches!(domain.as_ref(), GroundDomain::Record(_))
27
    {
28
        return Err(RuleNotApplicable);
29
426
    }
30

            
31
426
    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
426
    assert_eq!(
40
426
        index_domains.len(),
41
426
        indices.len(),
42
        "in an index expression, there should be the same number of indices as the subject has index domains"
43
    );
44

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

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

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

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

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

            
83
84
    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
84
    assert_eq!(
92
84
        index_domains.len(),
93
84
        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
84
    let bubble_constraints = Moo::new(into_matrix_expr![
99
84
        izip!(index_domains, indices)
100
162
            .filter_map(|(domain, index)| {
101
162
                index
102
162
                    .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
162
                    .map(|index| {
105
78
                        Expression::InDomain(
106
78
                            Metadata::new(),
107
78
                            Moo::new(index),
108
78
                            DomainPtr::from(domain.clone()),
109
78
                        )
110
78
                    })
111
162
            })
112
84
            .collect_vec()
113
    ]);
114

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

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