Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<char>);
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(
Expand Down
8 changes: 8 additions & 0 deletions tests/sqlparser_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
9 changes: 9 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
Loading