martin-g commented on code in PR #18970:
URL: https://github.com/apache/datafusion/pull/18970#discussion_r2569983312


##########
datafusion/physical-expr/src/simplifier/not.rs:
##########
@@ -0,0 +1,379 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Simplify NOT expressions in physical expressions
+//!
+//! This module provides optimizations for NOT expressions such as:
+//! - Double negation elimination: NOT(NOT(expr)) -> expr
+//! - NOT with binary comparisons: NOT(a = b) -> a != b
+//! - NOT with IN expressions: NOT(a IN (list)) -> a NOT IN (list)
+//! - De Morgan's laws: NOT(A AND B) -> NOT A OR NOT B
+//! - Constant folding: NOT(TRUE) -> FALSE, NOT(FALSE) -> TRUE
+
+use std::sync::Arc;
+
+use arrow::datatypes::Schema;
+use datafusion_common::{tree_node::Transformed, Result, ScalarValue};
+use datafusion_expr::Operator;
+
+use crate::expressions::{lit, BinaryExpr, Literal, NotExpr};
+use crate::PhysicalExpr;
+
+/// Attempts to simplify NOT expressions
+pub(crate) fn simplify_not_expr(
+    expr: Arc<dyn PhysicalExpr>,
+    schema: &Schema,
+) -> Result<Transformed<Arc<dyn PhysicalExpr>>> {
+    // Check if this is a NOT expression
+    let not_expr = match expr.as_any().downcast_ref::<NotExpr>() {
+        Some(not_expr) => not_expr,
+        None => return Ok(Transformed::no(expr)),
+    };
+
+    let inner_expr = not_expr.arg();
+
+    // Handle NOT(NOT(expr)) -> expr (double negation elimination)
+    if let Some(inner_not) = inner_expr.as_any().downcast_ref::<NotExpr>() {
+        // Recursively simplify the inner expression
+        let simplified = simplify_not_expr_recursive(inner_not.arg(), schema)?;
+        // We eliminated double negation, so always return transformed=true
+        return Ok(Transformed::yes(simplified.data));
+    }
+
+    // Handle NOT(literal) -> !literal
+    if let Some(literal) = inner_expr.as_any().downcast_ref::<Literal>() {
+        if let ScalarValue::Boolean(Some(val)) = literal.value() {
+            return Ok(Transformed::yes(lit(ScalarValue::Boolean(Some(!val)))));
+        }
+        if let ScalarValue::Boolean(None) = literal.value() {
+            return Ok(Transformed::yes(lit(ScalarValue::Boolean(None))));
+        }
+    }
+
+    // Handle NOT(binary_expr) where we can flip the operator
+    if let Some(binary_expr) = 
inner_expr.as_any().downcast_ref::<BinaryExpr>() {
+        if let Some(negated_op) = negate_operator(binary_expr.op()) {
+            // Recursively simplify the left and right expressions first
+            let left_simplified =
+                simplify_not_expr_recursive(binary_expr.left(), schema)?;
+            let right_simplified =
+                simplify_not_expr_recursive(binary_expr.right(), schema)?;
+
+            let new_binary = Arc::new(BinaryExpr::new(
+                left_simplified.data,
+                negated_op,
+                right_simplified.data,
+            ));
+            // We flipped the operator, so always return transformed=true
+            return Ok(Transformed::yes(new_binary));
+        }
+
+        // Handle De Morgan's laws for AND/OR
+        match binary_expr.op() {
+            Operator::And => {
+                // NOT(A AND B) -> NOT A OR NOT B
+                let not_left: Arc<dyn PhysicalExpr> =
+                    Arc::new(NotExpr::new(Arc::clone(binary_expr.left())));
+                let not_right: Arc<dyn PhysicalExpr> =
+                    Arc::new(NotExpr::new(Arc::clone(binary_expr.right())));
+
+                // Recursively simplify the NOT expressions
+                let simplified_left = simplify_not_expr_recursive(&not_left, 
schema)?;
+                let simplified_right = simplify_not_expr_recursive(&not_right, 
schema)?;
+
+                let new_binary = Arc::new(BinaryExpr::new(
+                    simplified_left.data,
+                    Operator::Or,
+                    simplified_right.data,
+                ));
+                return Ok(Transformed::yes(new_binary));
+            }
+            Operator::Or => {
+                // NOT(A OR B) -> NOT A AND NOT B
+                let not_left: Arc<dyn PhysicalExpr> =
+                    Arc::new(NotExpr::new(Arc::clone(binary_expr.left())));
+                let not_right: Arc<dyn PhysicalExpr> =
+                    Arc::new(NotExpr::new(Arc::clone(binary_expr.right())));
+
+                // Recursively simplify the NOT expressions
+                let simplified_left = simplify_not_expr_recursive(&not_left, 
schema)?;
+                let simplified_right = simplify_not_expr_recursive(&not_right, 
schema)?;
+
+                let new_binary = Arc::new(BinaryExpr::new(
+                    simplified_left.data,
+                    Operator::And,
+                    simplified_right.data,
+                ));
+                return Ok(Transformed::yes(new_binary));
+            }
+            _ => {}
+        }
+    }
+
+    // If no simplification possible, return the original expression
+    Ok(Transformed::no(expr))
+}
+
+/// Helper function that recursively simplifies expressions, including NOT 
expressions
+pub fn simplify_not_expr_recursive(
+    expr: &Arc<dyn PhysicalExpr>,
+    schema: &Schema,
+) -> Result<Transformed<Arc<dyn PhysicalExpr>>> {
+    // First, try to simplify any NOT expressions in this expression
+    let not_simplified = simplify_not_expr(Arc::clone(expr), schema)?;
+
+    // If the expression was transformed, we might have created new 
opportunities for simplification
+    if not_simplified.transformed {
+        // Recursively simplify the result
+        let further_simplified =
+            simplify_not_expr_recursive(&not_simplified.data, schema)?;

Review Comment:
   I wonder whether this could be a vector of an attack.
   Someone may craft a query with many `not(not(not(not(...))))` to cause a 
stack overflow due to the usage of recursion here.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to