You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by lu...@apache.org on 2026/09/25 07:34:58 UTC

(datafusion-sqlparser-rs) 01/01: Check prefix operator spacing by rendered first char

This is an automated email from the ASF dual-hosted git repository.

LucaCappelletti94 pushed a commit to branch upstream/unary-minus-display-linear
in repository https://gitbox.apache.org/repos/asf/datafusion-sqlparser-rs.git

commit 65b6ecf86c0060ede93e764ce31fb2482abe2fb3
Author: LucaCappelletti94 <ca...@gmail.com>
AuthorDate: Fri Sep 25 09:34:49 2026 +0200

    Check prefix operator spacing by rendered first char
---
 src/ast/mod.rs            | 21 +++++++++------------
 src/display_utils.rs      | 41 ++++++++++++++++++++++++++++++++++++++++
 tests/sqlparser_common.rs | 48 +++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 98 insertions(+), 12 deletions(-)

diff --git a/src/ast/mod.rs b/src/ast/mod.rs
index 491c82e95..e5e37d678 100644
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -49,7 +49,7 @@ use crate::{
     tokenizer::{Span, Token},
 };
 use crate::{
-    display_utils::{Indent, NewLine},
+    display_utils::{first_char, Indent, NewLine},
     keywords::Keyword,
 };
 
@@ -1987,11 +1987,13 @@ impl fmt::Display for Expr {
                 | UnaryOperator::PGSquareRoot
                 | UnaryOperator::PGCubeRoot => write!(f, "{op} {expr}"),
                 UnaryOperator::Minus | UnaryOperator::BangNot => {
+                    // Written before the check, so an enclosing
+                    // `starts_with_operator_char` stops at this operator.
+                    write!(f, "{op}")?;
                     if starts_with_operator_char(expr) {
-                        write!(f, "{op} {expr}")
-                    } else {
-                        write!(f, "{op}{expr}")
+                        f.write_str(" ")?;
                     }
+                    write!(f, "{expr}")
                 }
                 UnaryOperator::Plus | UnaryOperator::PGPrefixFactorial => write!(f, "{op}{expr}"),
             },
@@ -8109,14 +8111,9 @@ impl fmt::Display for FunctionArg {
 /// Whether `expr` renders with an operator character first. A prefix `-` or `!`
 /// must not abut one, since `--` starts a line comment and compound tokens
 /// like `!!` or `!~` alter the parsed AST or fail to parse.
-fn starts_with_operator_char(mut expr: &Expr) -> bool {
-    loop {
-        match expr {
-            Expr::UnaryOp { op, .. } => return !matches!(op, UnaryOperator::Not),
-            Expr::BinaryOp { left, .. } => expr = left,
-            _ => return false,
-        }
-    }
+fn starts_with_operator_char(expr: &Expr) -> bool {
+    const OPERATOR_CHARS: &str = "+-*/<>=~!@%#^&|";
+    first_char(expr).is_some_and(|c| OPERATOR_CHARS.contains(c))
 }
 
 /// `FunctionArgOperator::Space` has no token of its own, so the name and the
diff --git a/src/display_utils.rs b/src/display_utils.rs
index ba36fccdd..280b00296 100644
--- a/src/display_utils.rs
+++ b/src/display_utils.rs
@@ -108,6 +108,28 @@ pub(crate) fn indented_list<T: fmt::Display>(f: &mut fmt::Formatter, items: &[T]
     Indent(DisplayCommaSeparated(items)).fmt(f)
 }
 
+/// The first char `value` displays, rendering only up to it.
+///
+/// The sink fails once it holds a char. Stopping there relies on every
+/// `Display` impl propagating the formatter's errors.
+pub(crate) fn first_char(value: &impl Display) -> Option<char> {
+    struct FirstChar(Option<char>);
+
+    impl Write for FirstChar {
+        fn write_str(&mut self, s: &str) -> fmt::Result {
+            self.0 = self.0.or_else(|| s.chars().next());
+            match self.0 {
+                Some(_) => Err(fmt::Error),
+                None => Ok(()),
+            }
+        }
+    }
+
+    let mut first = FirstChar(None);
+    let _ = write!(first, "{value}");
+    first.0
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -132,4 +154,23 @@ mod tests {
         );
         assert_eq!(format!("{:#}", indent), "  line 1\n  line 2");
     }
+
+    #[test]
+    fn test_first_char_stops_at_first_char() {
+        struct EmptyThenChars(core::cell::Cell<bool>);
+
+        impl Display for EmptyThenChars {
+            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+                f.write_str("")?;
+                f.write_str("ab")?;
+                self.0.set(true);
+                Ok(())
+            }
+        }
+
+        let value = EmptyThenChars(Default::default());
+        assert_eq!(first_char(&value), Some('a'));
+        assert!(!value.0.get(), "rendered past the first char");
+        assert_eq!(first_char(&""), None);
+    }
 }
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
index 6ff0fe030..7fffa4380 100644
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -20200,3 +20200,51 @@ fn parse_bang_not_renders_apart_from_operand() {
     dialects.verified_stmt("SET eaac_cion = ! !o");
     dialects.one_statement_parses_to("SET eaac_cion = ! ! o", "SET eaac_cion = ! !o");
 }
+
+#[test]
+fn unary_prefix_operator_renders_apart_from_cast_operand() {
+    for (op, expected) in [
+        (UnaryOperator::Minus, "- -x::INT"),
+        (UnaryOperator::BangNot, "! !x::INT"),
+    ] {
+        let cast = Expr::Cast {
+            kind: CastKind::DoubleColon,
+            expr: Box::new(UnaryOp {
+                op,
+                expr: Box::new(Identifier(Ident::new("x"))),
+            }),
+            data_type: DataType::Int(None),
+            format: None,
+        };
+        let expr = UnaryOp {
+            op,
+            expr: Box::new(cast),
+        };
+        assert_eq!(expr.to_string(), expected);
+    }
+}
+
+#[test]
+fn display_nested_unary_minus_in_linear_time() {
+    use core::time::Duration;
+    use std::sync::mpsc;
+    use std::thread;
+
+    let depth = 200;
+    let sql = format!("SELECT {}-x", "- ".repeat(depth - 1));
+    let statement = Parser::new(&GenericDialect {})
+        .with_recursion_limit(depth * 10)
+        .try_with_sql(&sql)
+        .and_then(|mut p| p.parse_statement())
+        .unwrap();
+
+    let (tx, rx) = mpsc::channel();
+    thread::spawn(move || {
+        let _ = tx.send(statement.to_string());
+    });
+
+    let printed = rx
+        .recv_timeout(Duration::from_secs(5))
+        .expect("display should not take exponential time");
+    assert_eq!(printed, sql);
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org