Skip to main content

datafusion_physical_expr/simplifier/
not.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Simplify NOT expressions in physical expressions
6//!
7//! This module provides optimizations for NOT expressions such as:
8//! - Double negation elimination: NOT(NOT(expr)) -> expr
9//! - NOT with binary comparisons: NOT(a = b) -> a != b
10//! - NOT with IN expressions: NOT(a IN (list)) -> a NOT IN (list)
11//! - De Morgan's laws: NOT(A AND B) -> NOT A OR NOT B
12//! - Constant folding: NOT(TRUE) -> FALSE, NOT(FALSE) -> TRUE
13//!
14//! This function is designed to work with TreeNodeRewriter's f_up traversal,
15//! which means children are already simplified when this function is called.
16//! The TreeNodeRewriter will automatically call this function repeatedly until
17//! no more transformations are possible.
18
19use std::sync::Arc;
20
21use arrow::datatypes::Schema;
22use datafusion_common::{Result, ScalarValue, tree_node::Transformed};
23use datafusion_expr::Operator;
24
25use crate::PhysicalExpr;
26use crate::expressions::{BinaryExpr, InListExpr, Literal, NotExpr, in_list, lit};
27
28/// Attempts to simplify NOT expressions by applying one level of transformation
29///
30/// This function applies a single simplification rule and returns. When used with
31/// TreeNodeRewriter, multiple passes will automatically be applied until no more
32/// transformations are possible.
33#[deprecated(
34    since = "53.0.0",
35    note = "This function will be made private in a future release, please file an issue if you have a reason for keeping it public."
36)]
37pub fn simplify_not_expr(
38    expr: Arc<dyn PhysicalExpr>,
39    schema: &Schema,
40) -> Result<Transformed<Arc<dyn PhysicalExpr>>> {
41    // Check if this is a NOT expression
42    let Some(not_expr) = expr.downcast_ref::<NotExpr>() else {
43        return Ok(Transformed::no(expr));
44    };
45
46    let inner_expr = not_expr.arg();
47
48    // Handle NOT(NOT(expr)) -> expr (double negation elimination)
49    if let Some(inner_not) = inner_expr.downcast_ref::<NotExpr>() {
50        return Ok(Transformed::yes(Arc::clone(inner_not.arg())));
51    }
52
53    // Handle NOT(literal) -> !literal
54    if let Some(literal) = inner_expr.downcast_ref::<Literal>() {
55        if let ScalarValue::Boolean(Some(val)) = literal.value() {
56            return Ok(Transformed::yes(lit(ScalarValue::Boolean(Some(!val)))));
57        }
58        if matches!(literal.value(), ScalarValue::Boolean(None)) {
59            return Ok(Transformed::yes(lit(ScalarValue::Boolean(None))));
60        }
61    }
62
63    // Handle NOT(IN list) -> NOT IN list
64    if let Some(in_list_expr) = inner_expr.downcast_ref::<InListExpr>() {
65        let negated = !in_list_expr.negated();
66        let new_in_list = in_list(
67            Arc::clone(in_list_expr.expr()),
68            in_list_expr.list().to_vec(),
69            &negated,
70            schema,
71        )?;
72        return Ok(Transformed::yes(new_in_list));
73    }
74
75    // Handle NOT(binary_expr)
76    if let Some(binary_expr) = inner_expr.downcast_ref::<BinaryExpr>() {
77        if let Some(negated_op) = binary_expr.op().negate() {
78            let new_binary = Arc::new(BinaryExpr::new(
79                Arc::clone(binary_expr.left()),
80                negated_op,
81                Arc::clone(binary_expr.right()),
82            ));
83            return Ok(Transformed::yes(new_binary));
84        }
85
86        // Handle De Morgan's laws for AND/OR
87        match binary_expr.op() {
88            Operator::And => {
89                // NOT(A AND B) -> NOT A OR NOT B
90                let not_left: Arc<dyn PhysicalExpr> =
91                    Arc::new(NotExpr::new(Arc::clone(binary_expr.left())));
92                let not_right: Arc<dyn PhysicalExpr> =
93                    Arc::new(NotExpr::new(Arc::clone(binary_expr.right())));
94                let new_binary =
95                    Arc::new(BinaryExpr::new(not_left, Operator::Or, not_right));
96                return Ok(Transformed::yes(new_binary));
97            }
98            Operator::Or => {
99                // NOT(A OR B) -> NOT A AND NOT B
100                let not_left: Arc<dyn PhysicalExpr> =
101                    Arc::new(NotExpr::new(Arc::clone(binary_expr.left())));
102                let not_right: Arc<dyn PhysicalExpr> =
103                    Arc::new(NotExpr::new(Arc::clone(binary_expr.right())));
104                let new_binary =
105                    Arc::new(BinaryExpr::new(not_left, Operator::And, not_right));
106                return Ok(Transformed::yes(new_binary));
107            }
108            _ => {}
109        }
110    }
111
112    // If no simplification possible, return the original expression
113    Ok(Transformed::no(expr))
114}