diff --git a/src/ast/mod.rs b/src/ast/mod.rs index 4817a3f09..dcfd1a96e 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs @@ -1965,8 +1965,14 @@ impl fmt::Display for Expr { | UnaryOperator::PGAbs | UnaryOperator::QuestionDash | UnaryOperator::QuestionPipe => write!(f, "{op} {expr}"), + UnaryOperator::Minus => { + if starts_with_operator_char(expr) { + write!(f, "{op} {expr}") + } else { + write!(f, "{op}{expr}") + } + } UnaryOperator::Plus - | UnaryOperator::Minus | UnaryOperator::BangNot | UnaryOperator::PGPrefixFactorial | UnaryOperator::PGSquareRoot @@ -8083,6 +8089,26 @@ impl fmt::Display for FunctionArg { } } +/// Whether `expr` renders with an operator character first. A prefix `-` +/// must not abut one, since `--` starts a line comment and operator-run +/// dialects fuse `-@`, `-~`, `-#`, `-!!` and `-||/` into single tokens. +fn starts_with_operator_char(expr: &Expr) -> bool { + use fmt::Write; + struct FirstChar(Option); + impl fmt::Write for FirstChar { + fn write_str(&mut self, s: &str) -> fmt::Result { + if self.0.is_none() { + self.0 = s.chars().next(); + } + Ok(()) + } + } + let mut first = FirstChar(None); + let _ = write!(first, "{expr}"); + const OPERATOR_CHARS: &str = "+-*/<>=~!@%#^&|"; + first.0.is_some_and(|c| OPERATOR_CHARS.contains(c)) +} + /// `FunctionArgOperator::Space` has no token of its own, so the name and the /// value are separated by a single space instead. fn fmt_named_function_arg( diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs index 4069ff105..c4aa607d8 100644 --- a/tests/sqlparser_common.rs +++ b/tests/sqlparser_common.rs @@ -20072,3 +20072,11 @@ fn parse_bitwise_not_renders_apart_from_operand() { all_dialects().verified_stmt("SELECT ~ -1"); all_dialects().verified_stmt("SELECT ~ ~ 1"); } + +#[test] +fn parse_unary_minus_never_renders_line_comment() { + all_dialects().verified_stmt("SELECT - -1"); + all_dialects().verified_stmt("SELECT - - -1"); + all_dialects().verified_stmt("SELECT -1"); + all_dialects().verified_stmt("SELECT -x"); +} diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs index bf5353836..ab2d4b8ee 100644 --- a/tests/sqlparser_postgres.rs +++ b/tests/sqlparser_postgres.rs @@ -9975,3 +9975,12 @@ fn parse_bitwise_not_before_pg_prefix_operators() { pg().verified_stmt("SELECT ~ @ 2"); pg().one_statement_parses_to("SELECT ~ #x", "SELECT ~ # x"); } + +#[test] +fn parse_unary_minus_before_pg_prefix_operators() { + pg().one_statement_parses_to("SELECT - ~1", "SELECT - ~ 1"); + pg().verified_stmt("SELECT - ~ 1"); + pg().one_statement_parses_to("SELECT - @2", "SELECT - @ 2"); + pg().verified_stmt("SELECT - @ 2"); + pg().one_statement_parses_to("SELECT - #x", "SELECT - # x"); +}