1
use conjure_cp::{
2
    ast::Metadata,
3
    ast::{
4
        Atom, DeclarationKind, Expression, Literal, Moo, Name, Reference, ReturnType, SymbolTable,
5
        Typeable, eval_constant,
6
    },
7
    into_matrix_expr, matrix_expr,
8
    rule_engine::{
9
        ApplicationError::{self, RuleNotApplicable},
10
        ApplicationResult, RuleEffect, register_rule, register_rule_set,
11
    },
12
};
13
use uniplate::Biplate;
14

            
15
use crate::shared::utils::rewrite_children;
16

            
17
register_rule_set!("Bubble", ("Base"));
18

            
19
// Bubble reduction rules
20

            
21
/*
22
    Reduce bubbles with a boolean expression to a conjunction with their condition.
23

            
24
    e.g. (a / b = c) @ (b != 0) => (a / b = c) & (b != 0)
25
*/
26
#[register_rule("Bubble", 8900, [Bubble])]
27
132719
fn expand_bubble(expr: &Expression, _: &SymbolTable) -> ApplicationResult {
28
132719
    match expr {
29
122202
        Expression::Bubble(_, a, b) if a.return_type() == ReturnType::Bool => {
30
55569
            let a = Moo::unwrap_or_clone(Moo::clone(a));
31
55569
            let b = Moo::unwrap_or_clone(Moo::clone(b));
32
55569
            Ok(RuleEffect::pure(Expression::And(
33
55569
                Metadata::new(),
34
55569
                Moo::new(matrix_expr![a, b]),
35
55569
            )))
36
        }
37
77150
        _ => Err(ApplicationError::RuleNotApplicable),
38
    }
39
132719
}
40

            
41
/*
42
    Bring bubbles with a non-boolean expression higher up the tree.
43

            
44
    E.g. ((a / b) @ (b != 0)) = c => (a / b = c) @ (b != 0)
45
*/
46
#[register_rule("Bubble", 8800, [* / Bubble, * / Atomic / Reference])]
47
14421477
fn bubble_up(expr: &Expression, syms: &SymbolTable) -> ApplicationResult {
48
    // catchUndef consumes definedness itself; lifting its bubble would bypass the fallback.
49
    // do not put root inside a bubble
50
    //
51
    // also do not bubble bubbles inside bubbles, as this does nothing productive it just shuffles
52
    // the conditions around, shuffles them back, then gets stuck in a loop doing this ad infinitum
53
14421477
    if matches!(
54
14421477
        expr,
55
        Expression::Root(_, _) | Expression::Bubble(_, _, _) | Expression::CatchUndef(_, _, _)
56
    ) {
57
17427
        return Err(RuleNotApplicable);
58
14404050
    }
59

            
60
14404050
    let mut bubbled_conditions = vec![];
61
14404050
    let mut followed_lettings = vec![];
62
37875767
    let (new_inner, num_changed) = rewrite_children(expr, |child| match child {
63
55103
        Expression::Bubble(_, a, b) if a.return_type() != ReturnType::Bool => {
64
55067
            let a = Moo::unwrap_or_clone(a);
65
55067
            let b = Moo::unwrap_or_clone(b);
66
55067
            bubbled_conditions.push(b);
67
55067
            (a, true)
68
        }
69
        // A bubble in a value letting's body has nothing above it to escape into, so follow the
70
        // reference and lift it from here instead. Without this, `letting a be 2 / 0` leaves every
71
        // use of `a` an opaque reference all the way down to the solver adaptor.
72
        Expression::Atomic(_, Atom::Reference(ref reference)) => {
73
26908582
            let Some((inner, condition, name)) = bubbled_value_letting(reference) else {
74
26908578
                return (child, false);
75
            };
76
4
            bubbled_conditions.push(condition);
77
4
            followed_lettings.push(name);
78
4
            (inner, true)
79
        }
80
10912118
        child => (child, false),
81
37875767
    });
82
14404050
    if num_changed == 0 {
83
14349523
        return Err(ApplicationError::RuleNotApplicable);
84
54527
    }
85

            
86
    // The value-letting guard walks every referenced name in the subtree, so keep it behind the
87
    // cheap direct-child check above. Most `bubble_up` attempts fail before this point. Lettings
88
    // this call has just followed are exempt: their bubble is the one being lifted. Defined
89
    // constant lettings cannot hide another bubble and must not prevent index guards escaping.
90
595901
    if expr.universe_bi().iter().any(|x: &Name| {
91
595901
        !followed_lettings.contains(x)
92
595897
            && syms.lookup(x).is_some_and(|x| {
93
595897
                matches!(
94
595897
                    &x.kind() as &DeclarationKind,
95
1098
                    DeclarationKind::ValueLetting(value, _) if eval_constant(value).is_none()
96
                )
97
595897
            })
98
595901
    }) {
99
        return Err(RuleNotApplicable);
100
54527
    };
101

            
102
54527
    if bubbled_conditions.len() == 1 {
103
53983
        let new_expr = Expression::Bubble(
104
53983
            Metadata::new(),
105
53983
            Moo::new(new_inner),
106
53983
            Moo::new(bubbled_conditions[0].clone()),
107
53983
        );
108

            
109
53983
        Ok(RuleEffect::pure(new_expr))
110
    } else {
111
544
        Ok(RuleEffect::pure(Expression::Bubble(
112
544
            Metadata::new(),
113
544
            Moo::new(new_inner),
114
544
            Moo::new(Expression::And(
115
544
                Metadata::new(),
116
544
                Moo::new(into_matrix_expr![bubbled_conditions]),
117
544
            )),
118
544
        )))
119
    }
120
14421477
}
121

            
122
/// The inner expression, bubble condition and name of a value letting whose body is a non-boolean
123
/// bubble, e.g. `letting a be 2 / 0`.
124
26908582
fn bubbled_value_letting(reference: &Reference) -> Option<(Expression, Expression, Name)> {
125
26908582
    let declaration = reference.ptr();
126
26908582
    let value = declaration.as_value_letting()?;
127
18759
    let Expression::Bubble(_, inner, condition) = &*value else {
128
18755
        return None;
129
    };
130
4
    if inner.return_type() == ReturnType::Bool {
131
        return None;
132
4
    }
133
4
    Some((
134
4
        Moo::unwrap_or_clone(Moo::clone(inner)),
135
4
        Moo::unwrap_or_clone(Moo::clone(condition)),
136
4
        reference.name().clone(),
137
4
    ))
138
26908582
}
139

            
140
// Bubble applications
141

            
142
/// Converts an unsafe division to a safe division with a bubble condition.
143
///
144
/// ```text
145
///     a / b => (a / b) @ (b != 0)
146
/// ```
147
///
148
/// Division by zero is undefined and therefore not allowed, so we add a condition to check for it.
149
/// This condition is brought up the tree and expanded into a conjunction with the first
150
/// boolean-type expression it is paired with.
151

            
152
#[register_rule("Bubble", 6000, [UnsafeDiv])]
153
249347
fn div_to_bubble(expr: &Expression, _: &SymbolTable) -> ApplicationResult {
154
249347
    if eval_constant(expr).is_some() {
155
519
        return Err(RuleNotApplicable);
156
248828
    }
157
248828
    if let Expression::UnsafeDiv(_, a, b) = expr {
158
        // bubble bottom up
159
242149
        if !a.is_safe() || !b.is_safe() {
160
1971
            return Err(RuleNotApplicable);
161
240178
        }
162

            
163
240178
        return Ok(RuleEffect::pure(Expression::Bubble(
164
240178
            Metadata::new(),
165
240178
            Moo::new(Expression::SafeDiv(Metadata::new(), a.clone(), b.clone())),
166
240178
            Moo::new(Expression::Neq(
167
240178
                Metadata::new(),
168
240178
                b.clone(),
169
240178
                Moo::new(Expression::from(0)),
170
240178
            )),
171
240178
        )));
172
6679
    }
173
6679
    Err(ApplicationError::RuleNotApplicable)
174
249347
}
175

            
176
/// Converts an unsafe mod to a safe mod with a bubble condition.
177
///
178
/// ```text
179
/// a % b => (a % b) @ (b != 0)
180
/// ```
181
///
182
/// Mod zero is undefined and therefore not allowed, so we add a condition to check for it.
183
/// This condition is brought up the tree and expanded into a conjunction with the first
184
/// boolean-type expression it is paired with.
185
///
186
#[register_rule("Bubble", 6000, [UnsafeMod])]
187
442834
fn mod_to_bubble(expr: &Expression, _: &SymbolTable) -> ApplicationResult {
188
442834
    if eval_constant(expr).is_some() {
189
519
        return Err(RuleNotApplicable);
190
442315
    }
191
442315
    if let Expression::UnsafeMod(_, a, b) = expr {
192
        // bubble bottom up
193
435636
        if !a.is_safe() || !b.is_safe() {
194
201267
            return Err(RuleNotApplicable);
195
234369
        }
196

            
197
234369
        return Ok(RuleEffect::pure(Expression::Bubble(
198
234369
            Metadata::new(),
199
234369
            Moo::new(Expression::SafeMod(Metadata::new(), a.clone(), b.clone())),
200
234369
            Moo::new(Expression::Neq(
201
234369
                Metadata::new(),
202
234369
                b.clone(),
203
234369
                Moo::new(Expression::from(0)),
204
234369
            )),
205
234369
        )));
206
6679
    }
207
6679
    Err(ApplicationError::RuleNotApplicable)
208
442834
}
209

            
210
/// Converts an unsafe pow to a safe pow with a bubble condition.
211
///
212
/// ```text
213
/// a**b => (a ** b) @ ((a!=0 \/ b!=0) /\ b>=0
214
/// ```
215
///
216
/// Pow is only defined when `(a!=0 \/ b!=0) /\ b>=0`, so we add a condition to check for it.
217
/// This condition is brought up the tree and expanded into a conjunction with the first
218
/// boolean-type expression it is paired with.
219
///
220
#[register_rule("Bubble", 6000, [UnsafePow])]
221
18925
fn pow_to_bubble(expr: &Expression, _: &SymbolTable) -> ApplicationResult {
222
18925
    if eval_constant(expr).is_some() {
223
519
        return Err(RuleNotApplicable);
224
18406
    }
225
18406
    if let Expression::UnsafePow(_, a, b) = expr.clone() {
226
        // bubble bottom up
227
11763
        if !a.is_safe() || !b.is_safe() {
228
639
            return Err(RuleNotApplicable);
229
11124
        }
230

            
231
11124
        return Ok(RuleEffect::pure(Expression::Bubble(
232
11124
            Metadata::new(),
233
11124
            Moo::new(Expression::SafePow(Metadata::new(), a.clone(), b.clone())),
234
11124
            Moo::new(Expression::And(
235
11124
                Metadata::new(),
236
11124
                Moo::new(matrix_expr![
237
11124
                    Expression::Or(
238
11124
                        Metadata::new(),
239
11124
                        Moo::new(matrix_expr![
240
11124
                            Expression::Neq(
241
11124
                                Metadata::new(),
242
11124
                                a,
243
11124
                                Moo::new(Atom::Literal(Literal::Int(0)).into()),
244
11124
                            ),
245
11124
                            Expression::Neq(
246
11124
                                Metadata::new(),
247
11124
                                b.clone(),
248
11124
                                Moo::new(Atom::Literal(Literal::Int(0)).into()),
249
11124
                            ),
250
11124
                        ]),
251
11124
                    ),
252
11124
                    Expression::Geq(
253
11124
                        Metadata::new(),
254
11124
                        b,
255
11124
                        Moo::new(Atom::Literal(Literal::Int(0)).into()),
256
11124
                    ),
257
11124
                ]),
258
11124
            )),
259
11124
        )));
260
6643
    }
261
6643
    Err(ApplicationError::RuleNotApplicable)
262
18925
}
263

            
264
/// An enum endpoint has no predecessor/successor. Preserve that undefinedness until the
265
/// surrounding boolean expression (or catchUndef) consumes it.
266
#[register_rule("Bubble", 6000, [Pred, Succ])]
267
7206
fn enum_neighbour_to_bubble(expr: &Expression, _: &SymbolTable) -> ApplicationResult {
268
7206
    let (Expression::Pred(_, operand) | Expression::Succ(_, operand)) = expr else {
269
7198
        return Err(RuleNotApplicable);
270
    };
271
8
    let Some(Literal::EnumVariant(value)) = eval_constant(operand) else {
272
        return Err(RuleNotApplicable);
273
    };
274
8
    let neighbour = if matches!(expr, Expression::Pred(_, _)) {
275
        value.pred()
276
    } else {
277
8
        value.succ()
278
    };
279
8
    if neighbour.is_some() {
280
        return Err(RuleNotApplicable);
281
8
    }
282
8
    Ok(RuleEffect::pure(Expression::Bubble(
283
8
        Metadata::new(),
284
8
        operand.clone(),
285
8
        Moo::new(false.into()),
286
8
    )))
287
7206
}