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

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

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

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

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

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

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

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

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

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

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