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

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

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

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

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

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

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

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

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

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

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