Skip to main content

vlorql_core/optimizer/
fold.rs

1//! Constant folding: statically evaluate constant sub-expressions.
2//!
3//! [`ConstantFolding`] walks every expression in a plan using the
4//! [`ExpressionFold`] visitor and replaces any
5//! [`Expression::BinaryOp`] whose operands are both literals with
6//! the computed [`Expression::Literal`]. Because predicates embed
7//! expressions (`age > 20 + 5`), folding the operands also simplifies
8//! the comparisons the planner and cost model see (`age > 25`).
9//!
10//! In addition to full constant folding, the rule also applies
11//! boolean identity simplifications:
12//!
13//! * `true AND x` / `x AND true` → `x`
14//! * `false AND x` / `x AND false` → `false`
15//! * `true OR x` / `x OR true` → `true`
16//! * `false OR x` / `x OR false` → `x`
17//! * `NOT true` → `false`, `NOT false` → `true`
18//! * `x IS NULL` where `x` is a non-null literal → `false`
19//! * `NOT NOT x` → `x`
20//!
21//! The rewrite is intentionally conservative: it folds only when it can
22//! compute an exact, type-preserving result. Anything it is unsure
23//! about (mixed types, division by zero, string operands, `NULL`) is
24//! left untouched so the rewrite never changes query semantics.
25
26use serde_json::{Value, json};
27
28use crate::errors::VlorQLError;
29use crate::schema::{
30    BinaryOperator, ComparisonOperator, DataType, Expression, Predicate, QueryPlan,
31};
32
33use super::rules::PlanRewriter;
34use super::visitor::{ExpressionFold, default_fold_expression, default_fold_predicate};
35
36/// Folds constant expressions such as `1 + 2` into a single literal.
37///
38/// # Examples
39///
40/// ```
41/// use vlorql_core::optimizer::{ConstantFolding, PlanRewriter};
42/// use vlorql_core::schema::{
43///     BinaryOperator, DataType, Expression, FromClause, Projection, QueryPlan,
44/// };
45///
46/// let plan = QueryPlan {
47///     select: vec![Projection::Expr {
48///         expression: Expression::BinaryOp {
49///             left: Box::new(Expression::Literal { value: 1.into(), data_type: DataType::Int }),
50///             op: BinaryOperator::Add,
51///             right: Box::new(Expression::Literal { value: 2.into(), data_type: DataType::Int }),
52///         },
53///         alias: Some("three".to_owned()),
54///     }],
55///     from: FromClause { table: "t".to_owned(), alias: None },
56///     r#where: None, group_by: None, having: None,
57///     order_by: None, limit: None, offset: None, joins: None, ctes: None, distinct: false, distinct_on: None, set_operation: None,
58/// };
59///
60/// let folded = ConstantFolding.rewrite(&plan).unwrap();
61/// assert_eq!(
62///     folded.select[0],
63///     Projection::Expr {
64///         expression: Expression::Literal { value: 3.into(), data_type: DataType::Int },
65///         alias: Some("three".to_owned()),
66///     },
67/// );
68/// ```
69#[derive(Debug, Clone, Copy, Default)]
70pub struct ConstantFolding;
71
72impl PlanRewriter for ConstantFolding {
73    fn rewrite(&self, plan: &QueryPlan) -> Result<QueryPlan, VlorQLError> {
74        let mut folder = *self;
75        Ok(folder.fold_plan(plan))
76    }
77}
78
79impl ExpressionFold for ConstantFolding {
80    fn fold_expression(&mut self, expr: &Expression) -> Expression {
81        match expr {
82            Expression::BinaryOp { left, op, right } => {
83                let left = self.fold_expression(left);
84                let right = self.fold_expression(right);
85
86                // Boolean short-circuit and identity simplifications.
87                match op {
88                    BinaryOperator::And | BinaryOperator::Or => {
89                        if let Some(simplified) = fold_boolean_identity(&left, *op, &right) {
90                            return simplified;
91                        }
92                    }
93                    _ => {}
94                }
95
96                // Algebraic identity simplifications (x + 0 → x, x * 1 → x, etc.).
97                if let Some(simplified) = fold_algebraic_identity(&left, *op, &right) {
98                    return simplified;
99                }
100
101                // Both literals: compute the result.
102                if let (
103                    Expression::Literal {
104                        value: left_value, ..
105                    },
106                    Expression::Literal {
107                        value: right_value, ..
108                    },
109                ) = (&left, &right)
110                    && let Some(folded) = fold_binary(left_value, *op, right_value)
111                {
112                    return folded;
113                }
114
115                Expression::BinaryOp {
116                    left: Box::new(left),
117                    op: *op,
118                    right: Box::new(right),
119                }
120            }
121            Expression::FunctionCall {
122                name,
123                args,
124                distinct,
125            } => Expression::FunctionCall {
126                name: name.clone(),
127                args: args.iter().map(|a| self.fold_expression(a)).collect(),
128                distinct: *distinct,
129            },
130            other => default_fold_expression(self, other),
131        }
132    }
133
134    fn fold_predicate(&mut self, pred: &Predicate) -> Predicate {
135        match pred {
136            Predicate::Not { child } => {
137                let child = self.fold_predicate(child);
138                // Double negation: NOT NOT x = x
139                if let Predicate::Not { child: inner } = &child {
140                    return *inner.clone();
141                }
142                // NOT on a comparison with all-literal operands.
143                if let Predicate::Comparison { left, op, right } = &child
144                    && let Some(result) = fold_not_comparison(left, *op, right)
145                {
146                    return result;
147                }
148                Predicate::Not {
149                    child: Box::new(child),
150                }
151            }
152            Predicate::IsNull { expr } => {
153                let expr = self.fold_expression(expr);
154                // IS NULL on a known non-null literal → false.
155                if let Expression::Literal { value, .. } = &expr {
156                    if !value.is_null() {
157                        return bool_predicate(false);
158                    }
159                    // value.is_null() → keep as IS NULL (null is still unknown at runtime? No,
160                    // SQL NULL IS NULL → true)
161                    if value.is_null() {
162                        return bool_predicate(true);
163                    }
164                }
165                Predicate::IsNull { expr }
166            }
167            Predicate::And { left, right } => {
168                let left = self.fold_predicate(left);
169                let right = self.fold_predicate(right);
170                fold_and_or_short_circuit(&left, true, &right).unwrap_or_else(|| Predicate::And {
171                    left: Box::new(left),
172                    right: Box::new(right),
173                })
174            }
175            Predicate::Or { left, right } => {
176                let left = self.fold_predicate(left);
177                let right = self.fold_predicate(right);
178                fold_and_or_short_circuit(&left, false, &right).unwrap_or_else(|| Predicate::Or {
179                    left: Box::new(left),
180                    right: Box::new(right),
181                })
182            }
183            other => default_fold_predicate(self, other),
184        }
185    }
186}
187
188// -- boolean identity helpers ----------------------------------------------
189
190/// Applies `AND`/`OR` short-circuit and identity rules at the
191/// `Expression` level (`true AND col` → `col`).
192fn fold_boolean_identity(
193    left: &Expression,
194    op: BinaryOperator,
195    right: &Expression,
196) -> Option<Expression> {
197    let left_bool = lit_as_bool(left);
198    let right_bool = lit_as_bool(right);
199
200    match (op, left_bool, right_bool) {
201        // true AND x → x,  x AND true → x
202        (BinaryOperator::And, Some(true), _) => Some(right.clone()),
203        (BinaryOperator::And, _, Some(true)) => Some(left.clone()),
204        // false AND x → false,  x AND false → false
205        (BinaryOperator::And, Some(false), _) => Some(left.clone()),
206        (BinaryOperator::And, _, Some(false)) => Some(right.clone()),
207        // true OR x → true,  x OR true → true
208        (BinaryOperator::Or, Some(true), _) => Some(left.clone()),
209        (BinaryOperator::Or, _, Some(true)) => Some(right.clone()),
210        // false OR x → x,  x OR false → x
211        (BinaryOperator::Or, Some(false), _) => Some(right.clone()),
212        (BinaryOperator::Or, _, Some(false)) => Some(left.clone()),
213        _ => None,
214    }
215}
216
217/// Applies algebraic identity simplifications (`x + 0 → x`, `x * 1 → x`, etc.)
218///
219/// These are safe for all values including NULL because the identity
220/// element does not change the operand (NULL + 0 = NULL, NULL * 1 = NULL).
221fn fold_algebraic_identity(
222    left: &Expression,
223    op: BinaryOperator,
224    right: &Expression,
225) -> Option<Expression> {
226    let right_is_zero =
227        matches!(right, Expression::Literal { value, .. } if value.as_f64() == Some(0.0));
228    let right_is_one =
229        matches!(right, Expression::Literal { value, .. } if value.as_f64() == Some(1.0));
230    let left_is_zero =
231        matches!(left, Expression::Literal { value, .. } if value.as_f64() == Some(0.0));
232    let left_is_one =
233        matches!(left, Expression::Literal { value, .. } if value.as_f64() == Some(1.0));
234
235    match op {
236        BinaryOperator::Add => {
237            // x + 0 → x,  0 + x → x
238            if right_is_zero {
239                Some(left.clone())
240            } else if left_is_zero {
241                Some(right.clone())
242            } else {
243                None
244            }
245        }
246        BinaryOperator::Sub if right_is_zero => {
247            // x - 0 → x
248            Some(left.clone())
249        }
250        BinaryOperator::Mul => {
251            // x * 1 → x,  1 * x → x
252            if right_is_one {
253                Some(left.clone())
254            } else if left_is_one {
255                Some(right.clone())
256            } else {
257                None
258            }
259        }
260        BinaryOperator::Div if right_is_one => {
261            // x / 1 → x
262            Some(left.clone())
263        }
264        _ => None,
265    }
266}
267
268/// Applies `AND`/`OR` short-circuit at the `Predicate` level.
269fn fold_and_or_short_circuit(
270    left: &Predicate,
271    is_and: bool,
272    right: &Predicate,
273) -> Option<Predicate> {
274    let left_val = predicate_is_bool_literal(left);
275    let right_val = predicate_is_bool_literal(right);
276
277    match (is_and, left_val, right_val) {
278        // AND: false AND _ → false,  _ AND false → false
279        (true, Some(false), _) => Some(bool_predicate(false)),
280        (true, _, Some(false)) => Some(bool_predicate(false)),
281        // AND: true AND x → x,  x AND true → x
282        (true, Some(true), _) => Some(right.clone()),
283        (true, _, Some(true)) => Some(left.clone()),
284        // OR: true OR _ → true,  _ OR true → true
285        (false, Some(true), _) => Some(bool_predicate(true)),
286        (false, _, Some(true)) => Some(bool_predicate(true)),
287        // OR: false OR x → x,  x OR false → x
288        (false, Some(false), _) => Some(right.clone()),
289        (false, _, Some(false)) => Some(left.clone()),
290        _ => None,
291    }
292}
293
294/// Evaluates `NOT (left op right)` where all are literals.
295fn fold_not_comparison(
296    left: &Expression,
297    op: ComparisonOperator,
298    right: &Expression,
299) -> Option<Predicate> {
300    let (Expression::Literal { value: lv, .. }, Expression::Literal { value: rv, .. }) =
301        (left, right)
302    else {
303        return None;
304    };
305    let ordering = compare_values(lv, rv)?;
306    let result = match op {
307        ComparisonOperator::Eq => !ordering.is_eq(),
308        ComparisonOperator::Neq => !ordering.is_ne(),
309        ComparisonOperator::Gt => !ordering.is_gt(),
310        ComparisonOperator::Lt => !ordering.is_lt(),
311        ComparisonOperator::Gte => !ordering.is_ge(),
312        ComparisonOperator::Lte => !ordering.is_le(),
313        // Non-evaluable comparison operators: keep NOT intact.
314        ComparisonOperator::Like
315        | ComparisonOperator::ILike
316        | ComparisonOperator::In
317        | ComparisonOperator::Between => return None,
318    };
319    Some(bool_predicate(result))
320}
321
322/// Returns `Some(true)` or `Some(false)` when `expr` is a boolean
323/// literal, `None` otherwise.
324fn lit_as_bool(expr: &Expression) -> Option<bool> {
325    match expr {
326        Expression::Literal { value, data_type } if *data_type == DataType::Boolean => {
327            value.as_bool()
328        }
329        _ => None,
330    }
331}
332
333/// Checks whether a predicate reduces to a boolean constant
334/// (e.g. `true = true` or `1 = 1` for true, `1 = 0` for false).
335fn predicate_is_bool_literal(pred: &Predicate) -> Option<bool> {
336    if let Predicate::Comparison { left, op, right } = pred
337        && matches!(op, ComparisonOperator::Eq)
338        && let (Expression::Literal { value: lv, .. }, Expression::Literal { value: rv, .. }) =
339            (left, right)
340    {
341        // true = true, false = false
342        if lv == rv {
343            return lv.as_bool();
344        }
345        // 1 = 1 is also true, 1 = 0 is false
346        if let (Some(l), Some(r)) = (lv.as_f64(), rv.as_f64()) {
347            return Some((l - r).abs() < f64::EPSILON);
348        }
349    }
350    None
351}
352
353// -- original constant-folding helpers -------------------------------------
354
355/// Evaluates a binary operation over two literal JSON values, returning
356/// the folded literal or `None` when the result cannot be computed
357/// exactly (and the original expression should be kept).
358fn fold_binary(left: &Value, op: BinaryOperator, right: &Value) -> Option<Expression> {
359    use BinaryOperator::*;
360
361    match op {
362        Add | Sub | Mul | Div | Mod => fold_arithmetic(left, op, right),
363        And | Or => fold_boolean(left, op, right),
364        Eq | Neq | Gt | Lt | Gte | Lte => fold_comparison(left, op, right),
365        Like | ILike => None,
366    }
367}
368
369fn fold_arithmetic(left: &Value, op: BinaryOperator, right: &Value) -> Option<Expression> {
370    let (left, right) = (left.as_f64()?, right.as_f64()?);
371    let both_ints = is_integral(left) && is_integral(right);
372
373    let result = match op {
374        BinaryOperator::Add => left + right,
375        BinaryOperator::Sub => left - right,
376        BinaryOperator::Mul => left * right,
377        BinaryOperator::Div if right != 0.0 => left / right,
378        BinaryOperator::Mod if right != 0.0 => left % right,
379        _ => return None,
380    };
381
382    if !result.is_finite() {
383        return None;
384    }
385
386    if both_ints && is_integral(result) {
387        Some(int_literal(result as i64))
388    } else {
389        Some(float_literal(result))
390    }
391}
392
393fn fold_boolean(left: &Value, op: BinaryOperator, right: &Value) -> Option<Expression> {
394    let (left, right) = (left.as_bool()?, right.as_bool()?);
395    let result = match op {
396        BinaryOperator::And => left && right,
397        BinaryOperator::Or => left || right,
398        _ => return None,
399    };
400    Some(bool_literal(result))
401}
402
403fn fold_comparison(left: &Value, op: BinaryOperator, right: &Value) -> Option<Expression> {
404    let ordering = compare_values(left, right)?;
405    let result = match op {
406        BinaryOperator::Eq => ordering.is_eq(),
407        BinaryOperator::Neq => ordering.is_ne(),
408        BinaryOperator::Gt => ordering.is_gt(),
409        BinaryOperator::Lt => ordering.is_lt(),
410        BinaryOperator::Gte => ordering.is_ge(),
411        BinaryOperator::Lte => ordering.is_le(),
412        _ => return None,
413    };
414    Some(bool_literal(result))
415}
416
417fn compare_values(left: &Value, right: &Value) -> Option<std::cmp::Ordering> {
418    match (left, right) {
419        (Value::Number(_), Value::Number(_)) => left.as_f64()?.partial_cmp(&right.as_f64()?),
420        (Value::String(left), Value::String(right)) => Some(left.cmp(right)),
421        (Value::Bool(left), Value::Bool(right)) => Some(left.cmp(right)),
422        _ => None,
423    }
424}
425
426fn is_integral(value: f64) -> bool {
427    value.fract() == 0.0 && value.is_finite()
428}
429
430fn int_literal(value: i64) -> Expression {
431    Expression::Literal {
432        value: json!(value),
433        data_type: DataType::Int,
434    }
435}
436
437fn float_literal(value: f64) -> Expression {
438    Expression::Literal {
439        value: json!(value),
440        data_type: DataType::Float,
441    }
442}
443
444fn bool_literal(value: bool) -> Expression {
445    Expression::Literal {
446        value: json!(value),
447        data_type: DataType::Boolean,
448    }
449}
450
451fn bool_predicate(value: bool) -> Predicate {
452    let lit = Expression::Literal {
453        value: json!(value),
454        data_type: DataType::Boolean,
455    };
456    Predicate::Comparison {
457        left: lit.clone(),
458        op: ComparisonOperator::Eq,
459        right: lit,
460    }
461}
462
463#[cfg(test)]
464mod tests {
465    use super::*;
466    use crate::schema::{ComparisonOperator, DataType, FromClause, Projection};
467
468    fn lit_int(value: i64) -> Expression {
469        Expression::Literal {
470            value: json!(value),
471            data_type: DataType::Int,
472        }
473    }
474
475    fn lit_bool(value: bool) -> Expression {
476        Expression::Literal {
477            value: json!(value),
478            data_type: DataType::Boolean,
479        }
480    }
481
482    fn column(column: &str) -> Expression {
483        Expression::ColumnRef {
484            table: None,
485            column: column.to_owned(),
486        }
487    }
488
489    fn binop(left: Expression, op: BinaryOperator, right: Expression) -> Expression {
490        Expression::BinaryOp {
491            left: Box::new(left),
492            op,
493            right: Box::new(right),
494        }
495    }
496
497    #[test]
498    fn folds_integer_addition() {
499        let folded =
500            ConstantFolding.fold_expression(&binop(lit_int(1), BinaryOperator::Add, lit_int(2)));
501        assert_eq!(folded, lit_int(3));
502    }
503
504    #[test]
505    fn folds_nested_arithmetic() {
506        let inner = binop(lit_int(3), BinaryOperator::Add, lit_int(4));
507        let folded =
508            ConstantFolding.fold_expression(&binop(lit_int(2), BinaryOperator::Mul, inner));
509        assert_eq!(folded, lit_int(14));
510    }
511
512    #[test]
513    fn folds_constant_side_of_predicate() {
514        let pred = Predicate::Comparison {
515            left: column("age"),
516            op: ComparisonOperator::Gt,
517            right: binop(lit_int(20), BinaryOperator::Add, lit_int(5)),
518        };
519        let folded = ConstantFolding.fold_predicate(&pred);
520        assert_eq!(
521            folded,
522            Predicate::Comparison {
523                left: column("age"),
524                op: ComparisonOperator::Gt,
525                right: lit_int(25),
526            }
527        );
528    }
529
530    #[test]
531    fn does_not_fold_column_operands() {
532        let expr = binop(column("a"), BinaryOperator::Add, lit_int(1));
533        assert_eq!(ConstantFolding.fold_expression(&expr), expr);
534    }
535
536    #[test]
537    fn does_not_fold_division_by_zero() {
538        let expr = binop(lit_int(1), BinaryOperator::Div, lit_int(0));
539        assert_eq!(ConstantFolding.fold_expression(&expr), expr);
540    }
541
542    #[test]
543    fn division_stays_float_when_inexact() {
544        let folded =
545            ConstantFolding.fold_expression(&binop(lit_int(1), BinaryOperator::Div, lit_int(2)));
546        assert_eq!(
547            folded,
548            Expression::Literal {
549                value: json!(0.5),
550                data_type: DataType::Float,
551            }
552        );
553    }
554
555    #[test]
556    fn folds_constant_boolean_comparison() {
557        let expr = binop(
558            binop(lit_int(20), BinaryOperator::Add, lit_int(5)),
559            BinaryOperator::Eq,
560            lit_int(25),
561        );
562        assert_eq!(ConstantFolding.fold_expression(&expr), bool_literal(true));
563    }
564
565    // --- boolean identity tests -------------------------------------------
566
567    #[test]
568    fn true_and_column_is_column() {
569        let expr = binop(lit_bool(true), BinaryOperator::And, column("x"));
570        assert_eq!(ConstantFolding.fold_expression(&expr), column("x"));
571    }
572
573    #[test]
574    fn column_and_true_is_column() {
575        let expr = binop(column("x"), BinaryOperator::And, lit_bool(true));
576        assert_eq!(ConstantFolding.fold_expression(&expr), column("x"));
577    }
578
579    #[test]
580    fn false_and_column_is_false() {
581        let expr = binop(lit_bool(false), BinaryOperator::And, column("x"));
582        assert_eq!(ConstantFolding.fold_expression(&expr), lit_bool(false));
583    }
584
585    #[test]
586    fn column_and_false_is_false() {
587        let expr = binop(column("x"), BinaryOperator::And, lit_bool(false));
588        assert_eq!(ConstantFolding.fold_expression(&expr), lit_bool(false));
589    }
590
591    #[test]
592    fn true_or_column_is_true() {
593        let expr = binop(lit_bool(true), BinaryOperator::Or, column("x"));
594        assert_eq!(ConstantFolding.fold_expression(&expr), lit_bool(true));
595    }
596
597    #[test]
598    fn false_or_column_is_column() {
599        let expr = binop(lit_bool(false), BinaryOperator::Or, column("x"));
600        assert_eq!(ConstantFolding.fold_expression(&expr), column("x"));
601    }
602
603    #[test]
604    fn not_not_x_is_x() {
605        let inner = Predicate::Comparison {
606            left: column("age"),
607            op: ComparisonOperator::Gt,
608            right: lit_int(18),
609        };
610        let pred = Predicate::Not {
611            child: Box::new(Predicate::Not {
612                child: Box::new(inner.clone()),
613            }),
614        };
615        assert_eq!(ConstantFolding.fold_predicate(&pred), inner);
616    }
617
618    #[test]
619    fn not_literal_comparison_is_folded() {
620        let pred = Predicate::Not {
621            child: Box::new(Predicate::Comparison {
622                left: lit_int(1),
623                op: ComparisonOperator::Eq,
624                right: lit_int(2),
625            }),
626        };
627        let folded = ConstantFolding.fold_predicate(&pred);
628        assert_eq!(folded, bool_predicate(true)); // NOT (1 = 2) → true
629    }
630
631    #[test]
632    fn is_null_on_non_null_literal_is_false() {
633        let pred = Predicate::IsNull { expr: lit_int(42) };
634        assert_eq!(ConstantFolding.fold_predicate(&pred), bool_predicate(false));
635    }
636
637    #[test]
638    fn rewrite_folds_projection_and_leaves_plan_shape() {
639        let plan = QueryPlan {
640            select: vec![Projection::Expr {
641                expression: binop(lit_int(6), BinaryOperator::Mul, lit_int(7)),
642                alias: Some("answer".to_owned()),
643            }],
644            from: FromClause {
645                table: "t".to_owned(),
646                alias: None,
647            },
648            r#where: None,
649            group_by: None,
650            having: None,
651            order_by: None,
652            limit: None,
653            offset: None,
654            joins: None,
655            ctes: None,
656            distinct: false,
657            distinct_on: None,
658            set_operation: None,
659        };
660        let folded = ConstantFolding.rewrite(&plan).unwrap();
661        assert_eq!(
662            folded.select[0],
663            Projection::Expr {
664                expression: lit_int(42),
665                alias: Some("answer".to_owned()),
666            }
667        );
668    }
669
670    #[test]
671    fn true_and_predicate_simplifies() {
672        let pred = Predicate::And {
673            left: Box::new(bool_predicate(true)),
674            right: Box::new(Predicate::Comparison {
675                left: column("x"),
676                op: ComparisonOperator::Eq,
677                right: lit_int(1),
678            }),
679        };
680        let folded = ConstantFolding.fold_predicate(&pred);
681        assert_eq!(
682            folded,
683            Predicate::Comparison {
684                left: column("x"),
685                op: ComparisonOperator::Eq,
686                right: lit_int(1),
687            }
688        );
689    }
690
691    #[test]
692    fn false_or_predicate_simplifies() {
693        let pred = Predicate::Or {
694            left: Box::new(bool_predicate(false)),
695            right: Box::new(Predicate::Comparison {
696                left: column("x"),
697                op: ComparisonOperator::Eq,
698                right: lit_int(1),
699            }),
700        };
701        let folded = ConstantFolding.fold_predicate(&pred);
702        assert_eq!(
703            folded,
704            Predicate::Comparison {
705                left: column("x"),
706                op: ComparisonOperator::Eq,
707                right: lit_int(1),
708            }
709        );
710    }
711
712    // --- algebraic identity tests -----------------------------------------
713
714    #[test]
715    fn column_plus_zero_is_column() {
716        assert_eq!(
717            ConstantFolding.fold_expression(&binop(column("x"), BinaryOperator::Add, lit_int(0))),
718            column("x"),
719        );
720    }
721
722    #[test]
723    fn zero_plus_column_is_column() {
724        assert_eq!(
725            ConstantFolding.fold_expression(&binop(lit_int(0), BinaryOperator::Add, column("x"))),
726            column("x"),
727        );
728    }
729
730    #[test]
731    fn column_minus_zero_is_column() {
732        assert_eq!(
733            ConstantFolding.fold_expression(&binop(column("x"), BinaryOperator::Sub, lit_int(0))),
734            column("x"),
735        );
736    }
737
738    #[test]
739    fn column_times_one_is_column() {
740        assert_eq!(
741            ConstantFolding.fold_expression(&binop(column("x"), BinaryOperator::Mul, lit_int(1))),
742            column("x"),
743        );
744    }
745
746    #[test]
747    fn one_times_column_is_column() {
748        assert_eq!(
749            ConstantFolding.fold_expression(&binop(lit_int(1), BinaryOperator::Mul, column("x"))),
750            column("x"),
751        );
752    }
753
754    #[test]
755    fn column_divided_by_one_is_column() {
756        assert_eq!(
757            ConstantFolding.fold_expression(&binop(column("x"), BinaryOperator::Div, lit_int(1))),
758            column("x"),
759        );
760    }
761
762    #[test]
763    fn no_simplification_for_non_identity() {
764        // x + 2 should stay as-is
765        let expr = binop(column("x"), BinaryOperator::Add, lit_int(2));
766        assert_eq!(ConstantFolding.fold_expression(&expr), expr);
767    }
768
769    #[test]
770    fn identity_works_with_nested_expressions() {
771        // (x + 0) * 1 → x
772        let inner = binop(column("x"), BinaryOperator::Add, lit_int(0));
773        let expr = binop(inner, BinaryOperator::Mul, lit_int(1));
774        assert_eq!(ConstantFolding.fold_expression(&expr), column("x"));
775    }
776}