vibesql-parser 0.2.0

SQL parser for vibesql database engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
use super::*;

impl Parser {
    /// Parse OR expression (lowest precedence)
    pub(super) fn parse_or_expression(&mut self) -> Result<vibesql_ast::Expression, ParseError> {
        let mut left = self.parse_and_expression()?;

        while self.peek_keyword(Keyword::Or) {
            self.consume_keyword(Keyword::Or)?;
            let right = self.parse_and_expression()?;
            left = vibesql_ast::Expression::BinaryOp {
                op: vibesql_ast::BinaryOperator::Or,
                left: Box::new(left),
                right: Box::new(right),
            };
        }

        Ok(left)
    }

    /// Parse AND expression
    pub(super) fn parse_and_expression(&mut self) -> Result<vibesql_ast::Expression, ParseError> {
        let mut left = self.parse_not_expression()?;

        while self.peek_keyword(Keyword::And) {
            self.consume_keyword(Keyword::And)?;
            let right = self.parse_not_expression()?;
            left = vibesql_ast::Expression::BinaryOp {
                op: vibesql_ast::BinaryOperator::And,
                left: Box::new(left),
                right: Box::new(right),
            };
        }

        Ok(left)
    }

    /// Parse NOT expression
    /// NOT has precedence between AND and comparison operators
    /// This ensures "NOT col IS NULL" parses as "NOT (col IS NULL)" not "(NOT col) IS NULL"
    pub(super) fn parse_not_expression(&mut self) -> Result<vibesql_ast::Expression, ParseError> {
        // Check for NOT keyword (but not NOT IN, NOT BETWEEN, NOT LIKE, NOT EXISTS)
        // Those are handled in parse_comparison_expression and parse_primary_expression
        if self.peek_keyword(Keyword::Not) {
            // Peek ahead to see if it's a special case
            let saved_pos = self.position;
            self.advance(); // consume NOT

            // Check for special cases that are NOT unary NOT
            if self.peek_keyword(Keyword::In)
                || self.peek_keyword(Keyword::Between)
                || self.peek_keyword(Keyword::Like)
                || self.peek_keyword(Keyword::Glob)
                || self.peek_keyword(Keyword::Exists)
            {
                // Restore position and let the other parsers handle it
                self.position = saved_pos;
                return self.parse_bitwise_or_expression();
            }

            // It's a unary NOT - parse the expression it applies to
            // Recursively call parse_not_expression to handle multiple NOTs
            let expr = self.parse_not_expression()?;

            Ok(vibesql_ast::Expression::UnaryOp {
                op: vibesql_ast::UnaryOperator::Not,
                expr: Box::new(expr),
            })
        } else {
            self.parse_bitwise_or_expression()
        }
    }

    /// Parse bitwise OR expression (handles |)
    /// Precedence: between NOT and bitwise AND
    pub(super) fn parse_bitwise_or_expression(
        &mut self,
    ) -> Result<vibesql_ast::Expression, ParseError> {
        let mut left = self.parse_bitwise_and_expression()?;

        while self.peek() == &Token::Symbol('|') {
            self.advance();
            let right = self.parse_bitwise_and_expression()?;
            left = vibesql_ast::Expression::BinaryOp {
                op: vibesql_ast::BinaryOperator::BitwiseOr,
                left: Box::new(left),
                right: Box::new(right),
            };
        }

        Ok(left)
    }

    /// Parse bitwise AND expression (handles &)
    /// Precedence: between bitwise OR and comparison
    pub(super) fn parse_bitwise_and_expression(
        &mut self,
    ) -> Result<vibesql_ast::Expression, ParseError> {
        let mut left = self.parse_comparison_expression()?;

        while self.peek() == &Token::Symbol('&') {
            self.advance();
            let right = self.parse_comparison_expression()?;
            left = vibesql_ast::Expression::BinaryOp {
                op: vibesql_ast::BinaryOperator::BitwiseAnd,
                left: Box::new(left),
                right: Box::new(right),
            };
        }

        Ok(left)
    }

    /// Parse shift expression (handles <<, >>)
    /// Precedence: between comparison and additive
    pub(super) fn parse_shift_expression(&mut self) -> Result<vibesql_ast::Expression, ParseError> {
        let mut left = self.parse_additive_expression()?;

        loop {
            let op = match self.peek() {
                Token::Operator(crate::token::MultiCharOperator::LeftShift) => {
                    vibesql_ast::BinaryOperator::LeftShift
                }
                Token::Operator(crate::token::MultiCharOperator::RightShift) => {
                    vibesql_ast::BinaryOperator::RightShift
                }
                _ => break,
            };
            self.advance();

            let right = self.parse_additive_expression()?;
            left = vibesql_ast::Expression::BinaryOp {
                op,
                left: Box::new(left),
                right: Box::new(right),
            };
        }

        Ok(left)
    }

    /// Parse additive expression (handles +, -)
    /// Per SQLite, || has higher precedence than + and -, so it's handled in parse_concat_expression
    pub(super) fn parse_additive_expression(
        &mut self,
    ) -> Result<vibesql_ast::Expression, ParseError> {
        let mut left = self.parse_concat_expression()?;

        loop {
            let op = match self.peek() {
                Token::Symbol('+') => vibesql_ast::BinaryOperator::Plus,
                Token::Symbol('-') => vibesql_ast::BinaryOperator::Minus,
                _ => break,
            };
            self.advance();

            let right = self.parse_concat_expression()?;
            left = vibesql_ast::Expression::BinaryOp {
                op,
                left: Box::new(left),
                right: Box::new(right),
            };
        }

        Ok(left)
    }

    /// Parse string concatenation expression (handles ||)
    /// Per SQLite, || has higher precedence than + and -, but lower than * / %
    pub(super) fn parse_concat_expression(
        &mut self,
    ) -> Result<vibesql_ast::Expression, ParseError> {
        let mut left = self.parse_multiplicative_expression()?;

        while self.peek() == &Token::Operator(crate::token::MultiCharOperator::Concat) {
            self.advance();
            let right = self.parse_multiplicative_expression()?;
            left = vibesql_ast::Expression::BinaryOp {
                op: vibesql_ast::BinaryOperator::Concat,
                left: Box::new(left),
                right: Box::new(right),
            };
        }

        Ok(left)
    }

    /// Parse multiplicative expression (handles *, /, DIV, %)
    pub(super) fn parse_multiplicative_expression(
        &mut self,
    ) -> Result<vibesql_ast::Expression, ParseError> {
        let mut left = self.parse_unary_expression()?;

        loop {
            let op = match self.peek() {
                Token::Symbol('*') => vibesql_ast::BinaryOperator::Multiply,
                Token::Symbol('/') => vibesql_ast::BinaryOperator::Divide,
                Token::Symbol('%') => vibesql_ast::BinaryOperator::Modulo,
                Token::Keyword { keyword: Keyword::Div, .. } => {
                    vibesql_ast::BinaryOperator::IntegerDivide
                }
                _ => break,
            };
            self.advance();

            let right = self.parse_unary_expression()?;
            left = vibesql_ast::Expression::BinaryOp {
                op,
                left: Box::new(left),
                right: Box::new(right),
            };
        }

        Ok(left)
    }

    /// Parse comparison expression (handles =, <, >, <=, >=, !=, <>, IN, BETWEEN, LIKE, IS NULL)
    /// These operators have lower precedence than arithmetic operators
    pub(super) fn parse_comparison_expression(
        &mut self,
    ) -> Result<vibesql_ast::Expression, ParseError> {
        let mut left = self.parse_shift_expression()?;

        // Check for IN operator (including NOT IN) and BETWEEN (including NOT BETWEEN)
        if self.peek_keyword(Keyword::Not) {
            // Peek ahead to see if it's "NOT IN" or "NOT BETWEEN"
            let saved_pos = self.position;
            self.advance(); // consume NOT

            if self.peek_keyword(Keyword::In) {
                // It's NOT IN
                self.consume_keyword(Keyword::In)?;

                // Check if it's NOT IN table_name (SQLite syntax) or NOT IN (...)
                if self.peek() != &Token::LParen {
                    // SQLite compatibility: NOT IN table_name is equivalent to NOT IN (SELECT *
                    // FROM table_name) Parse the table name and expand to a
                    // subquery
                    let table_ref = self.parse_table_ref()?;
                    let table_name = table_ref.full_name();
                    let quoted = table_ref.is_any_quoted();

                    // Create a SELECT * FROM table_name subquery
                    let subquery = vibesql_ast::SelectStmt {
                        with_clause: None,
                        distinct: false,
                        select_list: vec![vibesql_ast::SelectItem::Wildcard { alias: None }],
                        into_table: None,
                        into_variables: None,
                        from: Some(vibesql_ast::FromClause::Table {
                            index_hint: None,
                            name: table_name,
                            alias: None,
                            column_aliases: None,
                            quoted,
                        }),
                        where_clause: None,
                        group_by: None,
                        having: None,
                        window_definitions: None,
                        order_by: None,
                        limit: None,
                        offset: None,
                        set_operation: None,
                        values: None,
                    };

                    left = vibesql_ast::Expression::In {
                        expr: Box::new(left),
                        subquery: Box::new(subquery),
                        negated: true,
                    };
                } else {
                    // Standard syntax: NOT IN (...)
                    self.expect_token(Token::LParen)?;

                    // Check if it's a subquery (SELECT ...) or a value list
                    // Also check for parenthesized subqueries like NOT IN ((SELECT ...))
                    let (is_subquery_through_parens, extra_paren_depth) =
                        self.peek_select_through_parens();

                    if self.peek_keyword(Keyword::Select)
                        || self.peek_keyword(Keyword::Values)
                        || self.peek_keyword(Keyword::With)
                        || is_subquery_through_parens
                    {
                        // It's a subquery: NOT IN (SELECT ...) or NOT IN ((SELECT ...))
                        // Consume any extra opening parentheses
                        for _ in 0..extra_paren_depth {
                            self.expect_token(Token::LParen)?;
                        }

                        let subquery = self.parse_select_statement()?;

                        // Consume matching closing parentheses
                        for _ in 0..extra_paren_depth {
                            self.expect_token(Token::RParen)?;
                        }
                        self.expect_token(Token::RParen)?;

                        // Don't return - assign to left and continue to check for IS NULL
                        left = vibesql_ast::Expression::In {
                            expr: Box::new(left),
                            subquery: Box::new(subquery),
                            negated: true,
                        };
                    } else {
                        // It's a value list: NOT IN (val1, val2, ...)
                        let values = self.parse_expression_list()?;
                        self.expect_token(Token::RParen)?;

                        // Empty IN lists are allowed per SQL:1999 (evaluates to TRUE for NOT IN)
                        // Don't return - assign to left and continue to check for IS NULL
                        left = vibesql_ast::Expression::InList {
                            expr: Box::new(left),
                            values,
                            negated: true,
                        };
                    }
                }
            } else if self.peek_keyword(Keyword::Between) {
                // It's NOT BETWEEN
                self.consume_keyword(Keyword::Between)?;

                // Check for optional ASYMMETRIC or SYMMETRIC
                let symmetric = if self.peek_keyword(Keyword::Symmetric) {
                    self.consume_keyword(Keyword::Symmetric)?;
                    true
                } else {
                    // ASYMMETRIC is default, but can be explicitly specified
                    if self.peek_keyword(Keyword::Asymmetric) {
                        self.consume_keyword(Keyword::Asymmetric)?;
                    }
                    false
                };

                // Parse low AND high
                let low = self.parse_shift_expression()?;
                self.consume_keyword(Keyword::And)?;
                let high = self.parse_shift_expression()?;

                // Don't return - assign to left and continue to check for IS NULL
                left = vibesql_ast::Expression::Between {
                    expr: Box::new(left),
                    low: Box::new(low),
                    high: Box::new(high),
                    negated: true,
                    symmetric,
                };
            } else if self.peek_keyword(Keyword::Like) {
                // It's NOT LIKE
                self.consume_keyword(Keyword::Like)?;

                // Parse pattern expression
                let pattern = self.parse_shift_expression()?;

                // Check for optional ESCAPE clause
                let escape = if self.peek_keyword(Keyword::Escape) {
                    self.consume_keyword(Keyword::Escape)?;
                    Some(Box::new(self.parse_shift_expression()?))
                } else {
                    None
                };

                // Don't return - assign to left and continue to check for IS NULL
                left = vibesql_ast::Expression::Like {
                    expr: Box::new(left),
                    pattern: Box::new(pattern),
                    negated: true,
                    escape,
                };
            } else if self.peek_keyword(Keyword::Glob) {
                // It's NOT GLOB (SQLite)
                self.consume_keyword(Keyword::Glob)?;

                // Parse pattern expression
                let pattern = self.parse_shift_expression()?;

                // Check for optional ESCAPE clause
                let escape = if self.peek_keyword(Keyword::Escape) {
                    self.consume_keyword(Keyword::Escape)?;
                    Some(Box::new(self.parse_shift_expression()?))
                } else {
                    None
                };

                // Don't return - assign to left and continue to check for IS NULL
                left = vibesql_ast::Expression::Glob {
                    expr: Box::new(left),
                    pattern: Box::new(pattern),
                    negated: true,
                    escape,
                };
            } else if self.peek_keyword(Keyword::Null) {
                // SQLite compatibility: "expr NOT NULL" (without IS) is equivalent to "expr IS NOT
                // NULL" BUT: In column definition context, "DEFAULT expr NOT NULL"
                // should parse NOT NULL as a column constraint, not as part of the
                // expression.
                //
                // Heuristic: If the left expression is a simple literal and what follows NULL
                // could be a column constraint context (`,` `)` or constraint keyword), then
                // treat NOT NULL as a column constraint, not an operator.
                // This handles: DEFAULT 'table' NOT NULL
                // But allows: WHERE col NOT NULL (col is not a literal)
                self.consume_keyword(Keyword::Null)?;

                // Check if left is a literal (in which case NOT NULL as an operator is semantically
                // odd)
                let left_is_literal = matches!(&left, vibesql_ast::Expression::Literal(_));

                // Check what comes after NULL
                let next_could_be_column_constraint = match self.peek() {
                    Token::Comma | Token::RParen => true,
                    Token::Keyword { keyword: kw, .. } => matches!(
                        kw,
                        // Column constraint keywords that can follow NOT NULL
                        Keyword::Check
                            | Keyword::Unique
                            | Keyword::Primary
                            | Keyword::References
                            | Keyword::Collate
                            | Keyword::Default
                            | Keyword::On
                            | Keyword::Generated
                            | Keyword::AutoIncrement
                            | Keyword::Constraint
                    ),
                    Token::Semicolon | Token::Eof => false, // At end of query, treat as operator
                    _ => false,
                };

                if left_is_literal && next_could_be_column_constraint {
                    // Likely in column definition: DEFAULT 'value' NOT NULL
                    // Restore position - NOT NULL should be parsed as column constraint
                    self.position = saved_pos;
                } else {
                    // General case: expr NOT NULL is an operator
                    return Ok(vibesql_ast::Expression::IsNull {
                        expr: Box::new(left),
                        negated: true,
                    });
                }
            } else {
                // Not "NOT IN", "NOT BETWEEN", "NOT LIKE", "NOT GLOB", or "NOT NULL", restore
                // position and continue Note: NOT EXISTS is handled in
                // parse_primary_expression()
                self.position = saved_pos;
            }
        } else if self.peek_keyword(Keyword::In) {
            // It's IN (not negated)
            self.consume_keyword(Keyword::In)?;

            // Check if it's IN table_name (SQLite syntax) or IN (...)
            if self.peek() != &Token::LParen {
                // SQLite compatibility: IN table_name is equivalent to IN (SELECT * FROM
                // table_name) Parse the table name and expand to a subquery
                let table_ref = self.parse_table_ref()?;
                let table_name = table_ref.full_name();
                let quoted = table_ref.is_any_quoted();

                // Create a SELECT * FROM table_name subquery
                let subquery = vibesql_ast::SelectStmt {
                    with_clause: None,
                    distinct: false,
                    select_list: vec![vibesql_ast::SelectItem::Wildcard { alias: None }],
                    into_table: None,
                    into_variables: None,
                    from: Some(vibesql_ast::FromClause::Table {
                        index_hint: None,
                        name: table_name,
                        alias: None,
                        column_aliases: None,
                        quoted,
                    }),
                    where_clause: None,
                    group_by: None,
                    having: None,
                    window_definitions: None,
                    order_by: None,
                    limit: None,
                    offset: None,
                    set_operation: None,
                    values: None,
                };

                left = vibesql_ast::Expression::In {
                    expr: Box::new(left),
                    subquery: Box::new(subquery),
                    negated: false,
                };
            } else {
                // Standard syntax: IN (...)
                self.expect_token(Token::LParen)?;

                // Check if it's a subquery (SELECT ...) or a value list
                // Also check for parenthesized subqueries like IN ((SELECT ...))
                let (is_subquery_through_parens, extra_paren_depth) =
                    self.peek_select_through_parens();

                if self.peek_keyword(Keyword::Select)
                    || self.peek_keyword(Keyword::Values)
                    || self.peek_keyword(Keyword::With)
                    || is_subquery_through_parens
                {
                    // It's a subquery: IN (SELECT ...) or IN ((SELECT ...))
                    // Consume any extra opening parentheses
                    for _ in 0..extra_paren_depth {
                        self.expect_token(Token::LParen)?;
                    }

                    let subquery = self.parse_select_statement()?;

                    // Consume matching closing parentheses
                    for _ in 0..extra_paren_depth {
                        self.expect_token(Token::RParen)?;
                    }
                    self.expect_token(Token::RParen)?;

                    // Don't return - assign to left and continue to check for IS NULL
                    left = vibesql_ast::Expression::In {
                        expr: Box::new(left),
                        subquery: Box::new(subquery),
                        negated: false,
                    };
                } else {
                    // It's a value list: IN (val1, val2, ...)
                    let values = self.parse_expression_list()?;
                    self.expect_token(Token::RParen)?;

                    // Empty IN lists are allowed per SQL:1999 (evaluates to FALSE)
                    // Don't return - assign to left and continue to check for IS NULL
                    left = vibesql_ast::Expression::InList {
                        expr: Box::new(left),
                        values,
                        negated: false,
                    };
                }
            }
        } else if self.peek_keyword(Keyword::Between) {
            // It's BETWEEN (not negated)
            self.consume_keyword(Keyword::Between)?;

            // Check for optional ASYMMETRIC or SYMMETRIC
            let symmetric = if self.peek_keyword(Keyword::Symmetric) {
                self.consume_keyword(Keyword::Symmetric)?;
                true
            } else {
                // ASYMMETRIC is default, but can be explicitly specified
                if self.peek_keyword(Keyword::Asymmetric) {
                    self.consume_keyword(Keyword::Asymmetric)?;
                }
                false
            };

            // Parse low AND high
            let low = self.parse_additive_expression()?;
            self.consume_keyword(Keyword::And)?;
            let high = self.parse_additive_expression()?;

            // Don't return - assign to left and continue to check for IS NULL
            left = vibesql_ast::Expression::Between {
                expr: Box::new(left),
                low: Box::new(low),
                high: Box::new(high),
                negated: false,
                symmetric,
            };
        } else if self.peek_keyword(Keyword::Like) {
            // It's LIKE (not negated)
            self.consume_keyword(Keyword::Like)?;

            // Parse pattern expression
            let pattern = self.parse_additive_expression()?;

            // Check for optional ESCAPE clause
            let escape = if self.peek_keyword(Keyword::Escape) {
                self.consume_keyword(Keyword::Escape)?;
                Some(Box::new(self.parse_additive_expression()?))
            } else {
                None
            };

            // Don't return - assign to left and continue to check for IS NULL
            left = vibesql_ast::Expression::Like {
                expr: Box::new(left),
                pattern: Box::new(pattern),
                negated: false,
                escape,
            };
        } else if self.peek_keyword(Keyword::Glob) {
            // It's GLOB (SQLite) (not negated)
            self.consume_keyword(Keyword::Glob)?;

            // Parse pattern expression
            let pattern = self.parse_additive_expression()?;

            // Check for optional ESCAPE clause
            let escape = if self.peek_keyword(Keyword::Escape) {
                self.consume_keyword(Keyword::Escape)?;
                Some(Box::new(self.parse_additive_expression()?))
            } else {
                None
            };

            // Don't return - assign to left and continue to check for IS NULL
            left = vibesql_ast::Expression::Glob {
                expr: Box::new(left),
                pattern: Box::new(pattern),
                negated: false,
                escape,
            };
        }

        // Check for comparison operators (both single-char and multi-char)
        // Note: Exclude || (concat) operator which should be handled in additive expression
        let is_comparison = match self.peek() {
            Token::Symbol('=') | Token::Symbol('<') | Token::Symbol('>') => true,
            Token::Operator(op) => !matches!(op, crate::token::MultiCharOperator::Concat),
            _ => false,
        };

        if is_comparison {
            let op = match self.peek() {
                Token::Symbol('=') => vibesql_ast::BinaryOperator::Equal,
                Token::Symbol('<') => vibesql_ast::BinaryOperator::LessThan,
                Token::Symbol('>') => vibesql_ast::BinaryOperator::GreaterThan,
                Token::Operator(op) => {
                    use crate::token::MultiCharOperator;
                    match op {
                        MultiCharOperator::LessEqual => {
                            vibesql_ast::BinaryOperator::LessThanOrEqual
                        }
                        MultiCharOperator::GreaterEqual => {
                            vibesql_ast::BinaryOperator::GreaterThanOrEqual
                        }
                        MultiCharOperator::NotEqual | MultiCharOperator::NotEqualAlt => {
                            vibesql_ast::BinaryOperator::NotEqual
                        }
                        // SQLite compatibility: == is a synonym for =
                        MultiCharOperator::DoubleEqual => vibesql_ast::BinaryOperator::Equal,
                        // Vector distance operators (pgvector compatible)
                        MultiCharOperator::CosineDistance => {
                            vibesql_ast::BinaryOperator::CosineDistance
                        }
                        MultiCharOperator::NegativeInnerProduct => {
                            vibesql_ast::BinaryOperator::NegativeInnerProduct
                        }
                        MultiCharOperator::L2Distance => vibesql_ast::BinaryOperator::L2Distance,
                        MultiCharOperator::Concat
                        | MultiCharOperator::LeftShift
                        | MultiCharOperator::RightShift
                        | MultiCharOperator::JsonExtract
                        | MultiCharOperator::JsonExtractText => {
                            return Err(ParseError {
                                message: format!("Unexpected operator: {}", op),
                            })
                        }
                    }
                }
                _ => unreachable!(),
            };
            self.advance();

            // Check for quantified comparison (ALL, ANY, SOME)
            if self.peek_keyword(Keyword::All)
                || self.peek_keyword(Keyword::Any)
                || self.peek_keyword(Keyword::Some)
            {
                let quantifier = if self.peek_keyword(Keyword::All) {
                    self.consume_keyword(Keyword::All)?;
                    vibesql_ast::Quantifier::All
                } else if self.peek_keyword(Keyword::Any) {
                    self.consume_keyword(Keyword::Any)?;
                    vibesql_ast::Quantifier::Any
                } else {
                    self.consume_keyword(Keyword::Some)?;
                    vibesql_ast::Quantifier::Some
                };

                // Expect opening paren
                self.expect_token(Token::LParen)?;

                // Parse subquery
                let subquery = self.parse_select_statement()?;

                // Expect closing paren
                self.expect_token(Token::RParen)?;

                return Ok(vibesql_ast::Expression::QuantifiedComparison {
                    expr: Box::new(left),
                    op,
                    quantifier,
                    subquery: Box::new(subquery),
                });
            }

            let right = self.parse_shift_expression()?;
            left = vibesql_ast::Expression::BinaryOp {
                op,
                left: Box::new(left),
                right: Box::new(right),
            };
        }

        // Check for IS NULL / IS NOT NULL / IS [NOT] DISTINCT FROM / IS [NOT] TRUE/FALSE/UNKNOWN
        if self.peek_keyword(Keyword::Is) {
            self.consume_keyword(Keyword::Is)?;

            // Check for NOT
            let negated = if self.peek_keyword(Keyword::Not) {
                self.consume_keyword(Keyword::Not)?;
                true
            } else {
                false
            };

            // Check for DISTINCT FROM (SQL:1999), NULL, TRUE, FALSE, or UNKNOWN
            if self.peek_keyword(Keyword::Distinct) {
                self.consume_keyword(Keyword::Distinct)?;
                self.expect_keyword(Keyword::From)?;
                let right = self.parse_shift_expression()?;
                left = vibesql_ast::Expression::IsDistinctFrom {
                    left: Box::new(left),
                    right: Box::new(right),
                    negated,
                };
            } else if self.peek_keyword(Keyword::True) {
                self.consume_keyword(Keyword::True)?;
                left = vibesql_ast::Expression::IsTruthValue {
                    expr: Box::new(left),
                    truth_value: vibesql_ast::TruthValue::True,
                    negated,
                };
            } else if self.peek_keyword(Keyword::False) {
                self.consume_keyword(Keyword::False)?;
                left = vibesql_ast::Expression::IsTruthValue {
                    expr: Box::new(left),
                    truth_value: vibesql_ast::TruthValue::False,
                    negated,
                };
            } else if self.peek_keyword(Keyword::Unknown) {
                self.consume_keyword(Keyword::Unknown)?;
                left = vibesql_ast::Expression::IsTruthValue {
                    expr: Box::new(left),
                    truth_value: vibesql_ast::TruthValue::Unknown,
                    negated,
                };
            } else if self.peek_keyword(Keyword::Null) {
                // IS NULL / IS NOT NULL
                self.consume_keyword(Keyword::Null)?;
                left = vibesql_ast::Expression::IsNull { expr: Box::new(left), negated };
            } else {
                // SQLite compatibility: IS <expr> - compare using IS semantics (NULL-safe equals)
                // This handles cases like `expr IS 0` or `expr IS 1`
                let right = self.parse_shift_expression()?;
                left = vibesql_ast::Expression::IsDistinctFrom {
                    left: Box::new(left),
                    right: Box::new(right),
                    // IS is equivalent to IS NOT DISTINCT FROM (NULL-safe equals)
                    // IS NOT is equivalent to IS DISTINCT FROM (NULL-safe not equals)
                    negated: !negated,
                };
            }
        }

        // SQLite compatibility: ISNULL and NOTNULL as postfix operators
        // These are equivalent to IS NULL and IS NOT NULL respectively
        // Loop to support chaining: `x NOTNULL NOTNULL` → `(x IS NOT NULL) IS NOT NULL`
        loop {
            if self.peek_keyword(Keyword::Isnull) {
                self.consume_keyword(Keyword::Isnull)?;
                left = vibesql_ast::Expression::IsNull { expr: Box::new(left), negated: false };
            } else if self.peek_keyword(Keyword::Notnull) {
                self.consume_keyword(Keyword::Notnull)?;
                left = vibesql_ast::Expression::IsNull { expr: Box::new(left), negated: true };
            } else {
                break;
            }
        }

        Ok(left)
    }

    /// Parse unary expression (handles unary +, -, ~ operators)
    pub(super) fn parse_unary_expression(&mut self) -> Result<vibesql_ast::Expression, ParseError> {
        // Check for unary +, -, or ~
        match self.peek() {
            Token::Symbol('+') => {
                self.advance();
                let expr = self.parse_unary_expression()?;
                Ok(vibesql_ast::Expression::UnaryOp {
                    op: vibesql_ast::UnaryOperator::Plus,
                    expr: Box::new(expr),
                })
            }
            Token::Symbol('-') => {
                self.advance();
                // Special case: handle i64::MIN (-9223372036854775808)
                // The positive value 9223372036854775808 overflows i64, but when
                // negated it becomes i64::MIN which is valid. We need to detect
                // this case and parse the combined negative number as i64.
                if let Token::Number(n) = self.peek() {
                    if n == "9223372036854775808" {
                        // This is the only number that overflows i64 but is valid when negated
                        self.advance();
                        return Ok(vibesql_ast::Expression::Literal(
                            vibesql_types::SqlValue::Integer(i64::MIN),
                        ));
                    }
                }
                let expr = self.parse_unary_expression()?;
                Ok(vibesql_ast::Expression::UnaryOp {
                    op: vibesql_ast::UnaryOperator::Minus,
                    expr: Box::new(expr),
                })
            }
            Token::Symbol('~') => {
                self.advance();
                let expr = self.parse_unary_expression()?;
                Ok(vibesql_ast::Expression::UnaryOp {
                    op: vibesql_ast::UnaryOperator::BitwiseNot,
                    expr: Box::new(expr),
                })
            }
            _ => self.parse_postfix_expression(),
        }
    }

    /// Parse postfix expressions (JSON operators ->, ->>, and COLLATE)
    /// These have high precedence, binding tighter than most operators
    pub(super) fn parse_postfix_expression(
        &mut self,
    ) -> Result<vibesql_ast::Expression, ParseError> {
        let mut expr = self.parse_primary_expression()?;

        // Handle JSON operators -> and ->> (high precedence, left-associative)
        loop {
            let op = match self.peek() {
                Token::Operator(crate::token::MultiCharOperator::JsonExtract) => {
                    vibesql_ast::BinaryOperator::JsonExtract
                }
                Token::Operator(crate::token::MultiCharOperator::JsonExtractText) => {
                    vibesql_ast::BinaryOperator::JsonExtractText
                }
                _ => break,
            };
            self.advance();

            // Parse the key/index expression (usually a string or integer)
            let right = self.parse_primary_expression()?;
            expr = vibesql_ast::Expression::BinaryOp {
                op,
                left: Box::new(expr),
                right: Box::new(right),
            };
        }

        // Handle COLLATE postfix operator
        while self.peek_keyword(Keyword::Collate) {
            self.consume_keyword(Keyword::Collate)?;
            // Parse collation name (identifier)
            let collation = match self.peek() {
                Token::Identifier(name) | Token::DelimitedIdentifier(name) => {
                    let name = name.clone();
                    self.advance();
                    name
                }
                Token::Keyword { keyword: kw, .. } => {
                    // Allow keywords like BINARY, NOCASE, RTRIM as collation names
                    let name = kw.to_string();
                    self.advance();
                    name
                }
                _ => {
                    return Err(ParseError {
                        message: "Expected collation name after COLLATE".to_string(),
                    })
                }
            };
            expr = vibesql_ast::Expression::Collate { expr: Box::new(expr), collation };
        }

        Ok(expr)
    }

    /// Parse a comma-separated list of expressions
    /// Used for IN (val1, val2, ...) and function arguments
    /// Does NOT consume the opening or closing parentheses
    pub fn parse_expression_list(&mut self) -> Result<Vec<vibesql_ast::Expression>, ParseError> {
        let mut expressions = Vec::new();

        // Check for empty list (SQLite compatibility)
        if matches!(self.peek(), Token::RParen) {
            return Ok(expressions);
        }

        // Parse first expression
        expressions.push(self.parse_expression()?);

        // Parse remaining expressions
        while matches!(self.peek(), Token::Comma) {
            self.advance(); // consume comma
            expressions.push(self.parse_expression()?);
        }

        Ok(expressions)
    }
}