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

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

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

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

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

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

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

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

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

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

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