Skip to main content

vibesql_parser/parser/expressions/
operators.rs

1use super::*;
2
3impl Parser {
4    /// Parse OR expression (lowest precedence)
5    pub(super) fn parse_or_expression(&mut self) -> Result<vibesql_ast::Expression, ParseError> {
6        let mut left = self.parse_and_expression()?;
7
8        while self.peek_keyword(Keyword::Or) {
9            self.consume_keyword(Keyword::Or)?;
10            let right = self.parse_and_expression()?;
11            left = vibesql_ast::Expression::BinaryOp {
12                op: vibesql_ast::BinaryOperator::Or,
13                left: Box::new(left),
14                right: Box::new(right),
15            };
16        }
17
18        Ok(left)
19    }
20
21    /// Parse AND expression
22    pub(super) fn parse_and_expression(&mut self) -> Result<vibesql_ast::Expression, ParseError> {
23        let mut left = self.parse_not_expression()?;
24
25        while self.peek_keyword(Keyword::And) {
26            self.consume_keyword(Keyword::And)?;
27            let right = self.parse_not_expression()?;
28            left = vibesql_ast::Expression::BinaryOp {
29                op: vibesql_ast::BinaryOperator::And,
30                left: Box::new(left),
31                right: Box::new(right),
32            };
33        }
34
35        Ok(left)
36    }
37
38    /// Parse NOT expression
39    /// NOT has precedence between AND and comparison operators
40    /// This ensures "NOT col IS NULL" parses as "NOT (col IS NULL)" not "(NOT col) IS NULL"
41    pub(super) fn parse_not_expression(&mut self) -> Result<vibesql_ast::Expression, ParseError> {
42        // Check for NOT keyword (but not NOT IN, NOT BETWEEN, NOT LIKE, NOT EXISTS)
43        // Those are handled in parse_comparison_expression and parse_primary_expression
44        if self.peek_keyword(Keyword::Not) {
45            // Peek ahead to see if it's a special case
46            let saved_pos = self.position;
47            self.advance(); // consume NOT
48
49            // Check for special cases that are NOT unary NOT
50            if self.peek_keyword(Keyword::In)
51                || self.peek_keyword(Keyword::Between)
52                || self.peek_keyword(Keyword::Like)
53                || self.peek_keyword(Keyword::Glob)
54                || self.peek_keyword(Keyword::Exists)
55            {
56                // Restore position and let the other parsers handle it
57                self.position = saved_pos;
58                return self.parse_bitwise_or_expression();
59            }
60
61            // It's a unary NOT - parse the expression it applies to
62            // Recursively call parse_not_expression to handle multiple NOTs
63            let expr = self.parse_not_expression()?;
64
65            Ok(vibesql_ast::Expression::UnaryOp {
66                op: vibesql_ast::UnaryOperator::Not,
67                expr: Box::new(expr),
68            })
69        } else {
70            self.parse_bitwise_or_expression()
71        }
72    }
73
74    /// Parse bitwise OR expression (handles |)
75    /// Precedence: between NOT and bitwise AND
76    pub(super) fn parse_bitwise_or_expression(
77        &mut self,
78    ) -> Result<vibesql_ast::Expression, ParseError> {
79        let mut left = self.parse_bitwise_and_expression()?;
80
81        while self.peek() == &Token::Symbol('|') {
82            self.advance();
83            let right = self.parse_bitwise_and_expression()?;
84            left = vibesql_ast::Expression::BinaryOp {
85                op: vibesql_ast::BinaryOperator::BitwiseOr,
86                left: Box::new(left),
87                right: Box::new(right),
88            };
89        }
90
91        Ok(left)
92    }
93
94    /// Parse bitwise AND expression (handles &)
95    /// Precedence: between bitwise OR and comparison
96    pub(super) fn parse_bitwise_and_expression(
97        &mut self,
98    ) -> Result<vibesql_ast::Expression, ParseError> {
99        let mut left = self.parse_comparison_expression()?;
100
101        while self.peek() == &Token::Symbol('&') {
102            self.advance();
103            let right = self.parse_comparison_expression()?;
104            left = vibesql_ast::Expression::BinaryOp {
105                op: vibesql_ast::BinaryOperator::BitwiseAnd,
106                left: Box::new(left),
107                right: Box::new(right),
108            };
109        }
110
111        Ok(left)
112    }
113
114    /// Parse shift expression (handles <<, >>)
115    /// Precedence: between comparison and additive
116    pub(super) fn parse_shift_expression(&mut self) -> Result<vibesql_ast::Expression, ParseError> {
117        let mut left = self.parse_additive_expression()?;
118
119        loop {
120            let op = match self.peek() {
121                Token::Operator(crate::token::MultiCharOperator::LeftShift) => {
122                    vibesql_ast::BinaryOperator::LeftShift
123                }
124                Token::Operator(crate::token::MultiCharOperator::RightShift) => {
125                    vibesql_ast::BinaryOperator::RightShift
126                }
127                _ => break,
128            };
129            self.advance();
130
131            let right = self.parse_additive_expression()?;
132            left = vibesql_ast::Expression::BinaryOp {
133                op,
134                left: Box::new(left),
135                right: Box::new(right),
136            };
137        }
138
139        Ok(left)
140    }
141
142    /// Parse additive expression (handles +, -)
143    /// Per SQLite, || has higher precedence than + and -, so it's handled in parse_concat_expression
144    pub(super) fn parse_additive_expression(
145        &mut self,
146    ) -> Result<vibesql_ast::Expression, ParseError> {
147        let mut left = self.parse_concat_expression()?;
148
149        loop {
150            let op = match self.peek() {
151                Token::Symbol('+') => vibesql_ast::BinaryOperator::Plus,
152                Token::Symbol('-') => vibesql_ast::BinaryOperator::Minus,
153                _ => break,
154            };
155            self.advance();
156
157            let right = self.parse_concat_expression()?;
158            left = vibesql_ast::Expression::BinaryOp {
159                op,
160                left: Box::new(left),
161                right: Box::new(right),
162            };
163        }
164
165        Ok(left)
166    }
167
168    /// Parse string concatenation expression (handles ||)
169    /// Per SQLite, || has higher precedence than + and -, but lower than * / %
170    pub(super) fn parse_concat_expression(
171        &mut self,
172    ) -> Result<vibesql_ast::Expression, ParseError> {
173        let mut left = self.parse_multiplicative_expression()?;
174
175        while self.peek() == &Token::Operator(crate::token::MultiCharOperator::Concat) {
176            self.advance();
177            let right = self.parse_multiplicative_expression()?;
178            left = vibesql_ast::Expression::BinaryOp {
179                op: vibesql_ast::BinaryOperator::Concat,
180                left: Box::new(left),
181                right: Box::new(right),
182            };
183        }
184
185        Ok(left)
186    }
187
188    /// Parse multiplicative expression (handles *, /, DIV, %)
189    pub(super) fn parse_multiplicative_expression(
190        &mut self,
191    ) -> Result<vibesql_ast::Expression, ParseError> {
192        let mut left = self.parse_unary_expression()?;
193
194        loop {
195            let op = match self.peek() {
196                Token::Symbol('*') => vibesql_ast::BinaryOperator::Multiply,
197                Token::Symbol('/') => vibesql_ast::BinaryOperator::Divide,
198                Token::Symbol('%') => vibesql_ast::BinaryOperator::Modulo,
199                Token::Keyword { keyword: Keyword::Div, .. } => {
200                    vibesql_ast::BinaryOperator::IntegerDivide
201                }
202                _ => break,
203            };
204            self.advance();
205
206            let right = self.parse_unary_expression()?;
207            left = vibesql_ast::Expression::BinaryOp {
208                op,
209                left: Box::new(left),
210                right: Box::new(right),
211            };
212        }
213
214        Ok(left)
215    }
216
217    /// Parse comparison expression (handles =, <, >, <=, >=, !=, <>, IN, BETWEEN, LIKE, IS NULL)
218    /// These operators have lower precedence than arithmetic operators
219    pub(super) fn parse_comparison_expression(
220        &mut self,
221    ) -> Result<vibesql_ast::Expression, ParseError> {
222        let mut left = self.parse_shift_expression()?;
223
224        // Check for IN operator (including NOT IN) and BETWEEN (including NOT BETWEEN)
225        if self.peek_keyword(Keyword::Not) {
226            // Peek ahead to see if it's "NOT IN" or "NOT BETWEEN"
227            let saved_pos = self.position;
228            self.advance(); // consume NOT
229
230            if self.peek_keyword(Keyword::In) {
231                // It's NOT IN
232                self.consume_keyword(Keyword::In)?;
233
234                // Check if it's NOT IN table_name (SQLite syntax) or NOT IN (...)
235                if self.peek() != &Token::LParen {
236                    // SQLite compatibility: NOT IN table_name is equivalent to NOT IN (SELECT *
237                    // FROM table_name) Parse the table name and expand to a
238                    // subquery
239                    let table_ref = self.parse_table_ref()?;
240                    let table_name = table_ref.full_name();
241                    let quoted = table_ref.is_any_quoted();
242
243                    // Create a SELECT * FROM table_name subquery
244                    let subquery = vibesql_ast::SelectStmt {
245                        with_clause: None,
246                        distinct: false,
247                        select_list: vec![vibesql_ast::SelectItem::Wildcard { alias: None }],
248                        into_table: None,
249                        into_variables: None,
250                        from: Some(vibesql_ast::FromClause::Table {
251                            index_hint: None,
252                            name: table_name,
253                            alias: None,
254                            column_aliases: None,
255                            quoted,
256                        }),
257                        where_clause: None,
258                        group_by: None,
259                        having: None,
260                        window_definitions: None,
261                        order_by: None,
262                        limit: None,
263                        offset: None,
264                        set_operation: None,
265                        values: None,
266                    };
267
268                    left = vibesql_ast::Expression::In {
269                        expr: Box::new(left),
270                        subquery: Box::new(subquery),
271                        negated: true,
272                    };
273                } else {
274                    // Standard syntax: NOT IN (...)
275                    self.expect_token(Token::LParen)?;
276
277                    // Check if it's a subquery (SELECT ...) or a value list
278                    // Also check for parenthesized subqueries like NOT IN ((SELECT ...))
279                    let (is_subquery_through_parens, extra_paren_depth) =
280                        self.peek_select_through_parens();
281
282                    if self.peek_keyword(Keyword::Select)
283                        || self.peek_keyword(Keyword::Values)
284                        || self.peek_keyword(Keyword::With)
285                        || is_subquery_through_parens
286                    {
287                        // It's a subquery: NOT IN (SELECT ...) or NOT IN ((SELECT ...))
288                        // Consume any extra opening parentheses
289                        for _ in 0..extra_paren_depth {
290                            self.expect_token(Token::LParen)?;
291                        }
292
293                        let subquery = self.parse_select_statement()?;
294
295                        // Consume matching closing parentheses
296                        for _ in 0..extra_paren_depth {
297                            self.expect_token(Token::RParen)?;
298                        }
299                        self.expect_token(Token::RParen)?;
300
301                        // Don't return - assign to left and continue to check for IS NULL
302                        left = vibesql_ast::Expression::In {
303                            expr: Box::new(left),
304                            subquery: Box::new(subquery),
305                            negated: true,
306                        };
307                    } else {
308                        // It's a value list: NOT IN (val1, val2, ...)
309                        let values = self.parse_expression_list()?;
310                        self.expect_token(Token::RParen)?;
311
312                        // Empty IN lists are allowed per SQL:1999 (evaluates to TRUE for NOT IN)
313                        // Don't return - assign to left and continue to check for IS NULL
314                        left = vibesql_ast::Expression::InList {
315                            expr: Box::new(left),
316                            values,
317                            negated: true,
318                        };
319                    }
320                }
321            } else if self.peek_keyword(Keyword::Between) {
322                // It's NOT BETWEEN
323                self.consume_keyword(Keyword::Between)?;
324
325                // Check for optional ASYMMETRIC or SYMMETRIC
326                let symmetric = if self.peek_keyword(Keyword::Symmetric) {
327                    self.consume_keyword(Keyword::Symmetric)?;
328                    true
329                } else {
330                    // ASYMMETRIC is default, but can be explicitly specified
331                    if self.peek_keyword(Keyword::Asymmetric) {
332                        self.consume_keyword(Keyword::Asymmetric)?;
333                    }
334                    false
335                };
336
337                // Parse low AND high
338                let low = self.parse_shift_expression()?;
339                self.consume_keyword(Keyword::And)?;
340                let high = self.parse_shift_expression()?;
341
342                // Don't return - assign to left and continue to check for IS NULL
343                left = vibesql_ast::Expression::Between {
344                    expr: Box::new(left),
345                    low: Box::new(low),
346                    high: Box::new(high),
347                    negated: true,
348                    symmetric,
349                };
350            } else if self.peek_keyword(Keyword::Like) {
351                // It's NOT LIKE
352                self.consume_keyword(Keyword::Like)?;
353
354                // Parse pattern expression
355                let pattern = self.parse_shift_expression()?;
356
357                // Check for optional ESCAPE clause
358                let escape = if self.peek_keyword(Keyword::Escape) {
359                    self.consume_keyword(Keyword::Escape)?;
360                    Some(Box::new(self.parse_shift_expression()?))
361                } else {
362                    None
363                };
364
365                // Don't return - assign to left and continue to check for IS NULL
366                left = vibesql_ast::Expression::Like {
367                    expr: Box::new(left),
368                    pattern: Box::new(pattern),
369                    negated: true,
370                    escape,
371                };
372            } else if self.peek_keyword(Keyword::Glob) {
373                // It's NOT GLOB (SQLite)
374                self.consume_keyword(Keyword::Glob)?;
375
376                // Parse pattern expression
377                let pattern = self.parse_shift_expression()?;
378
379                // Check for optional ESCAPE clause
380                let escape = if self.peek_keyword(Keyword::Escape) {
381                    self.consume_keyword(Keyword::Escape)?;
382                    Some(Box::new(self.parse_shift_expression()?))
383                } else {
384                    None
385                };
386
387                // Don't return - assign to left and continue to check for IS NULL
388                left = vibesql_ast::Expression::Glob {
389                    expr: Box::new(left),
390                    pattern: Box::new(pattern),
391                    negated: true,
392                    escape,
393                };
394            } else if self.peek_keyword(Keyword::Null) {
395                // SQLite compatibility: "expr NOT NULL" (without IS) is equivalent to "expr IS NOT
396                // NULL" BUT: In column definition context, "DEFAULT expr NOT NULL"
397                // should parse NOT NULL as a column constraint, not as part of the
398                // expression.
399                //
400                // Heuristic: If the left expression is a simple literal and what follows NULL
401                // could be a column constraint context (`,` `)` or constraint keyword), then
402                // treat NOT NULL as a column constraint, not an operator.
403                // This handles: DEFAULT 'table' NOT NULL
404                // But allows: WHERE col NOT NULL (col is not a literal)
405                self.consume_keyword(Keyword::Null)?;
406
407                // Check if left is a literal (in which case NOT NULL as an operator is semantically
408                // odd)
409                let left_is_literal = matches!(&left, vibesql_ast::Expression::Literal(_));
410
411                // Check what comes after NULL
412                let next_could_be_column_constraint = match self.peek() {
413                    Token::Comma | Token::RParen => true,
414                    Token::Keyword { keyword: kw, .. } => matches!(
415                        kw,
416                        // Column constraint keywords that can follow NOT NULL
417                        Keyword::Check
418                            | Keyword::Unique
419                            | Keyword::Primary
420                            | Keyword::References
421                            | Keyword::Collate
422                            | Keyword::Default
423                            | Keyword::On
424                            | Keyword::Generated
425                            | Keyword::AutoIncrement
426                            | Keyword::Constraint
427                    ),
428                    Token::Semicolon | Token::Eof => false, // At end of query, treat as operator
429                    _ => false,
430                };
431
432                if left_is_literal && next_could_be_column_constraint {
433                    // Likely in column definition: DEFAULT 'value' NOT NULL
434                    // Restore position - NOT NULL should be parsed as column constraint
435                    self.position = saved_pos;
436                } else {
437                    // General case: expr NOT NULL is an operator
438                    return Ok(vibesql_ast::Expression::IsNull {
439                        expr: Box::new(left),
440                        negated: true,
441                    });
442                }
443            } else {
444                // Not "NOT IN", "NOT BETWEEN", "NOT LIKE", "NOT GLOB", or "NOT NULL", restore
445                // position and continue Note: NOT EXISTS is handled in
446                // parse_primary_expression()
447                self.position = saved_pos;
448            }
449        } else if self.peek_keyword(Keyword::In) {
450            // It's IN (not negated)
451            self.consume_keyword(Keyword::In)?;
452
453            // Check if it's IN table_name (SQLite syntax) or IN (...)
454            if self.peek() != &Token::LParen {
455                // SQLite compatibility: IN table_name is equivalent to IN (SELECT * FROM
456                // table_name) Parse the table name and expand to a subquery
457                let table_ref = self.parse_table_ref()?;
458                let table_name = table_ref.full_name();
459                let quoted = table_ref.is_any_quoted();
460
461                // Create a SELECT * FROM table_name subquery
462                let subquery = vibesql_ast::SelectStmt {
463                    with_clause: None,
464                    distinct: false,
465                    select_list: vec![vibesql_ast::SelectItem::Wildcard { alias: None }],
466                    into_table: None,
467                    into_variables: None,
468                    from: Some(vibesql_ast::FromClause::Table {
469                        index_hint: None,
470                        name: table_name,
471                        alias: None,
472                        column_aliases: None,
473                        quoted,
474                    }),
475                    where_clause: None,
476                    group_by: None,
477                    having: None,
478                    window_definitions: None,
479                    order_by: None,
480                    limit: None,
481                    offset: None,
482                    set_operation: None,
483                    values: None,
484                };
485
486                left = vibesql_ast::Expression::In {
487                    expr: Box::new(left),
488                    subquery: Box::new(subquery),
489                    negated: false,
490                };
491            } else {
492                // Standard syntax: IN (...)
493                self.expect_token(Token::LParen)?;
494
495                // Check if it's a subquery (SELECT ...) or a value list
496                // Also check for parenthesized subqueries like IN ((SELECT ...))
497                let (is_subquery_through_parens, extra_paren_depth) =
498                    self.peek_select_through_parens();
499
500                if self.peek_keyword(Keyword::Select)
501                    || self.peek_keyword(Keyword::Values)
502                    || self.peek_keyword(Keyword::With)
503                    || is_subquery_through_parens
504                {
505                    // It's a subquery: IN (SELECT ...) or IN ((SELECT ...))
506                    // Consume any extra opening parentheses
507                    for _ in 0..extra_paren_depth {
508                        self.expect_token(Token::LParen)?;
509                    }
510
511                    let subquery = self.parse_select_statement()?;
512
513                    // Consume matching closing parentheses
514                    for _ in 0..extra_paren_depth {
515                        self.expect_token(Token::RParen)?;
516                    }
517                    self.expect_token(Token::RParen)?;
518
519                    // Don't return - assign to left and continue to check for IS NULL
520                    left = vibesql_ast::Expression::In {
521                        expr: Box::new(left),
522                        subquery: Box::new(subquery),
523                        negated: false,
524                    };
525                } else {
526                    // It's a value list: IN (val1, val2, ...)
527                    let values = self.parse_expression_list()?;
528                    self.expect_token(Token::RParen)?;
529
530                    // Empty IN lists are allowed per SQL:1999 (evaluates to FALSE)
531                    // Don't return - assign to left and continue to check for IS NULL
532                    left = vibesql_ast::Expression::InList {
533                        expr: Box::new(left),
534                        values,
535                        negated: false,
536                    };
537                }
538            }
539        } else if self.peek_keyword(Keyword::Between) {
540            // It's BETWEEN (not negated)
541            self.consume_keyword(Keyword::Between)?;
542
543            // Check for optional ASYMMETRIC or SYMMETRIC
544            let symmetric = if self.peek_keyword(Keyword::Symmetric) {
545                self.consume_keyword(Keyword::Symmetric)?;
546                true
547            } else {
548                // ASYMMETRIC is default, but can be explicitly specified
549                if self.peek_keyword(Keyword::Asymmetric) {
550                    self.consume_keyword(Keyword::Asymmetric)?;
551                }
552                false
553            };
554
555            // Parse low AND high
556            let low = self.parse_additive_expression()?;
557            self.consume_keyword(Keyword::And)?;
558            let high = self.parse_additive_expression()?;
559
560            // Don't return - assign to left and continue to check for IS NULL
561            left = vibesql_ast::Expression::Between {
562                expr: Box::new(left),
563                low: Box::new(low),
564                high: Box::new(high),
565                negated: false,
566                symmetric,
567            };
568        } else if self.peek_keyword(Keyword::Like) {
569            // It's LIKE (not negated)
570            self.consume_keyword(Keyword::Like)?;
571
572            // Parse pattern expression
573            let pattern = self.parse_additive_expression()?;
574
575            // Check for optional ESCAPE clause
576            let escape = if self.peek_keyword(Keyword::Escape) {
577                self.consume_keyword(Keyword::Escape)?;
578                Some(Box::new(self.parse_additive_expression()?))
579            } else {
580                None
581            };
582
583            // Don't return - assign to left and continue to check for IS NULL
584            left = vibesql_ast::Expression::Like {
585                expr: Box::new(left),
586                pattern: Box::new(pattern),
587                negated: false,
588                escape,
589            };
590        } else if self.peek_keyword(Keyword::Glob) {
591            // It's GLOB (SQLite) (not negated)
592            self.consume_keyword(Keyword::Glob)?;
593
594            // Parse pattern expression
595            let pattern = self.parse_additive_expression()?;
596
597            // Check for optional ESCAPE clause
598            let escape = if self.peek_keyword(Keyword::Escape) {
599                self.consume_keyword(Keyword::Escape)?;
600                Some(Box::new(self.parse_additive_expression()?))
601            } else {
602                None
603            };
604
605            // Don't return - assign to left and continue to check for IS NULL
606            left = vibesql_ast::Expression::Glob {
607                expr: Box::new(left),
608                pattern: Box::new(pattern),
609                negated: false,
610                escape,
611            };
612        }
613
614        // Check for comparison operators (both single-char and multi-char)
615        // Note: Exclude || (concat) operator which should be handled in additive expression
616        let is_comparison = match self.peek() {
617            Token::Symbol('=') | Token::Symbol('<') | Token::Symbol('>') => true,
618            Token::Operator(op) => !matches!(op, crate::token::MultiCharOperator::Concat),
619            _ => false,
620        };
621
622        if is_comparison {
623            let op = match self.peek() {
624                Token::Symbol('=') => vibesql_ast::BinaryOperator::Equal,
625                Token::Symbol('<') => vibesql_ast::BinaryOperator::LessThan,
626                Token::Symbol('>') => vibesql_ast::BinaryOperator::GreaterThan,
627                Token::Operator(op) => {
628                    use crate::token::MultiCharOperator;
629                    match op {
630                        MultiCharOperator::LessEqual => {
631                            vibesql_ast::BinaryOperator::LessThanOrEqual
632                        }
633                        MultiCharOperator::GreaterEqual => {
634                            vibesql_ast::BinaryOperator::GreaterThanOrEqual
635                        }
636                        MultiCharOperator::NotEqual | MultiCharOperator::NotEqualAlt => {
637                            vibesql_ast::BinaryOperator::NotEqual
638                        }
639                        // SQLite compatibility: == is a synonym for =
640                        MultiCharOperator::DoubleEqual => vibesql_ast::BinaryOperator::Equal,
641                        // Vector distance operators (pgvector compatible)
642                        MultiCharOperator::CosineDistance => {
643                            vibesql_ast::BinaryOperator::CosineDistance
644                        }
645                        MultiCharOperator::NegativeInnerProduct => {
646                            vibesql_ast::BinaryOperator::NegativeInnerProduct
647                        }
648                        MultiCharOperator::L2Distance => vibesql_ast::BinaryOperator::L2Distance,
649                        MultiCharOperator::Concat
650                        | MultiCharOperator::LeftShift
651                        | MultiCharOperator::RightShift
652                        | MultiCharOperator::JsonExtract
653                        | MultiCharOperator::JsonExtractText => {
654                            return Err(ParseError {
655                                message: format!("Unexpected operator: {}", op),
656                            })
657                        }
658                    }
659                }
660                _ => unreachable!(),
661            };
662            self.advance();
663
664            // Check for quantified comparison (ALL, ANY, SOME)
665            if self.peek_keyword(Keyword::All)
666                || self.peek_keyword(Keyword::Any)
667                || self.peek_keyword(Keyword::Some)
668            {
669                let quantifier = if self.peek_keyword(Keyword::All) {
670                    self.consume_keyword(Keyword::All)?;
671                    vibesql_ast::Quantifier::All
672                } else if self.peek_keyword(Keyword::Any) {
673                    self.consume_keyword(Keyword::Any)?;
674                    vibesql_ast::Quantifier::Any
675                } else {
676                    self.consume_keyword(Keyword::Some)?;
677                    vibesql_ast::Quantifier::Some
678                };
679
680                // Expect opening paren
681                self.expect_token(Token::LParen)?;
682
683                // Parse subquery
684                let subquery = self.parse_select_statement()?;
685
686                // Expect closing paren
687                self.expect_token(Token::RParen)?;
688
689                return Ok(vibesql_ast::Expression::QuantifiedComparison {
690                    expr: Box::new(left),
691                    op,
692                    quantifier,
693                    subquery: Box::new(subquery),
694                });
695            }
696
697            let right = self.parse_shift_expression()?;
698            left = vibesql_ast::Expression::BinaryOp {
699                op,
700                left: Box::new(left),
701                right: Box::new(right),
702            };
703        }
704
705        // Check for IS NULL / IS NOT NULL / IS [NOT] DISTINCT FROM / IS [NOT] TRUE/FALSE/UNKNOWN
706        if self.peek_keyword(Keyword::Is) {
707            self.consume_keyword(Keyword::Is)?;
708
709            // Check for NOT
710            let negated = if self.peek_keyword(Keyword::Not) {
711                self.consume_keyword(Keyword::Not)?;
712                true
713            } else {
714                false
715            };
716
717            // Check for DISTINCT FROM (SQL:1999), NULL, TRUE, FALSE, or UNKNOWN
718            if self.peek_keyword(Keyword::Distinct) {
719                self.consume_keyword(Keyword::Distinct)?;
720                self.expect_keyword(Keyword::From)?;
721                let right = self.parse_shift_expression()?;
722                left = vibesql_ast::Expression::IsDistinctFrom {
723                    left: Box::new(left),
724                    right: Box::new(right),
725                    negated,
726                };
727            } else if self.peek_keyword(Keyword::True) {
728                self.consume_keyword(Keyword::True)?;
729                left = vibesql_ast::Expression::IsTruthValue {
730                    expr: Box::new(left),
731                    truth_value: vibesql_ast::TruthValue::True,
732                    negated,
733                };
734            } else if self.peek_keyword(Keyword::False) {
735                self.consume_keyword(Keyword::False)?;
736                left = vibesql_ast::Expression::IsTruthValue {
737                    expr: Box::new(left),
738                    truth_value: vibesql_ast::TruthValue::False,
739                    negated,
740                };
741            } else if self.peek_keyword(Keyword::Unknown) {
742                self.consume_keyword(Keyword::Unknown)?;
743                left = vibesql_ast::Expression::IsTruthValue {
744                    expr: Box::new(left),
745                    truth_value: vibesql_ast::TruthValue::Unknown,
746                    negated,
747                };
748            } else if self.peek_keyword(Keyword::Null) {
749                // IS NULL / IS NOT NULL
750                self.consume_keyword(Keyword::Null)?;
751                left = vibesql_ast::Expression::IsNull { expr: Box::new(left), negated };
752            } else {
753                // SQLite compatibility: IS <expr> - compare using IS semantics (NULL-safe equals)
754                // This handles cases like `expr IS 0` or `expr IS 1`
755                let right = self.parse_shift_expression()?;
756                left = vibesql_ast::Expression::IsDistinctFrom {
757                    left: Box::new(left),
758                    right: Box::new(right),
759                    // IS is equivalent to IS NOT DISTINCT FROM (NULL-safe equals)
760                    // IS NOT is equivalent to IS DISTINCT FROM (NULL-safe not equals)
761                    negated: !negated,
762                };
763            }
764        }
765
766        // SQLite compatibility: ISNULL and NOTNULL as postfix operators
767        // These are equivalent to IS NULL and IS NOT NULL respectively
768        // Loop to support chaining: `x NOTNULL NOTNULL` → `(x IS NOT NULL) IS NOT NULL`
769        loop {
770            if self.peek_keyword(Keyword::Isnull) {
771                self.consume_keyword(Keyword::Isnull)?;
772                left = vibesql_ast::Expression::IsNull { expr: Box::new(left), negated: false };
773            } else if self.peek_keyword(Keyword::Notnull) {
774                self.consume_keyword(Keyword::Notnull)?;
775                left = vibesql_ast::Expression::IsNull { expr: Box::new(left), negated: true };
776            } else {
777                break;
778            }
779        }
780
781        Ok(left)
782    }
783
784    /// Parse unary expression (handles unary +, -, ~ operators)
785    pub(super) fn parse_unary_expression(&mut self) -> Result<vibesql_ast::Expression, ParseError> {
786        // Check for unary +, -, or ~
787        match self.peek() {
788            Token::Symbol('+') => {
789                self.advance();
790                let expr = self.parse_unary_expression()?;
791                Ok(vibesql_ast::Expression::UnaryOp {
792                    op: vibesql_ast::UnaryOperator::Plus,
793                    expr: Box::new(expr),
794                })
795            }
796            Token::Symbol('-') => {
797                self.advance();
798                // Special case: handle i64::MIN (-9223372036854775808)
799                // The positive value 9223372036854775808 overflows i64, but when
800                // negated it becomes i64::MIN which is valid. We need to detect
801                // this case and parse the combined negative number as i64.
802                if let Token::Number(n) = self.peek() {
803                    if n == "9223372036854775808" {
804                        // This is the only number that overflows i64 but is valid when negated
805                        self.advance();
806                        return Ok(vibesql_ast::Expression::Literal(
807                            vibesql_types::SqlValue::Integer(i64::MIN),
808                        ));
809                    }
810                }
811                let expr = self.parse_unary_expression()?;
812                Ok(vibesql_ast::Expression::UnaryOp {
813                    op: vibesql_ast::UnaryOperator::Minus,
814                    expr: Box::new(expr),
815                })
816            }
817            Token::Symbol('~') => {
818                self.advance();
819                let expr = self.parse_unary_expression()?;
820                Ok(vibesql_ast::Expression::UnaryOp {
821                    op: vibesql_ast::UnaryOperator::BitwiseNot,
822                    expr: Box::new(expr),
823                })
824            }
825            _ => self.parse_postfix_expression(),
826        }
827    }
828
829    /// Parse postfix expressions (JSON operators ->, ->>, and COLLATE)
830    /// These have high precedence, binding tighter than most operators
831    pub(super) fn parse_postfix_expression(
832        &mut self,
833    ) -> Result<vibesql_ast::Expression, ParseError> {
834        let mut expr = self.parse_primary_expression()?;
835
836        // Handle JSON operators -> and ->> (high precedence, left-associative)
837        loop {
838            let op = match self.peek() {
839                Token::Operator(crate::token::MultiCharOperator::JsonExtract) => {
840                    vibesql_ast::BinaryOperator::JsonExtract
841                }
842                Token::Operator(crate::token::MultiCharOperator::JsonExtractText) => {
843                    vibesql_ast::BinaryOperator::JsonExtractText
844                }
845                _ => break,
846            };
847            self.advance();
848
849            // Parse the key/index expression (usually a string or integer)
850            let right = self.parse_primary_expression()?;
851            expr = vibesql_ast::Expression::BinaryOp {
852                op,
853                left: Box::new(expr),
854                right: Box::new(right),
855            };
856        }
857
858        // Handle COLLATE postfix operator
859        while self.peek_keyword(Keyword::Collate) {
860            self.consume_keyword(Keyword::Collate)?;
861            // Parse collation name (identifier)
862            let collation = match self.peek() {
863                Token::Identifier(name) | Token::DelimitedIdentifier(name) => {
864                    let name = name.clone();
865                    self.advance();
866                    name
867                }
868                Token::Keyword { keyword: kw, .. } => {
869                    // Allow keywords like BINARY, NOCASE, RTRIM as collation names
870                    let name = kw.to_string();
871                    self.advance();
872                    name
873                }
874                _ => {
875                    return Err(ParseError {
876                        message: "Expected collation name after COLLATE".to_string(),
877                    })
878                }
879            };
880            expr = vibesql_ast::Expression::Collate { expr: Box::new(expr), collation };
881        }
882
883        Ok(expr)
884    }
885
886    /// Parse a comma-separated list of expressions
887    /// Used for IN (val1, val2, ...) and function arguments
888    /// Does NOT consume the opening or closing parentheses
889    pub fn parse_expression_list(&mut self) -> Result<Vec<vibesql_ast::Expression>, ParseError> {
890        let mut expressions = Vec::new();
891
892        // Check for empty list (SQLite compatibility)
893        if matches!(self.peek(), Token::RParen) {
894            return Ok(expressions);
895        }
896
897        // Parse first expression
898        expressions.push(self.parse_expression()?);
899
900        // Parse remaining expressions
901        while matches!(self.peek(), Token::Comma) {
902            self.advance(); // consume comma
903            expressions.push(self.parse_expression()?);
904        }
905
906        Ok(expressions)
907    }
908}