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
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
//! Arena-allocated expression parsing.

use bumpalo::collections::Vec as BumpVec;
use vibesql_ast::{
    arena::{
        CaseWhen, Expression, ExtendedExpr, NullsOrder, OrderByItem, OrderDirection, Quantifier,
        Symbol, TruthValue, WindowFunctionSpec, WindowSpec,
    },
    BinaryOperator, UnaryOperator,
};
use vibesql_types::SqlValue;

use super::ArenaParser;
use crate::{
    keywords::Keyword,
    token::{MultiCharOperator, Token},
    ParseError,
};

impl<'arena> ArenaParser<'arena> {
    /// Parse an expression (entry point).
    pub(crate) fn parse_expression(&mut self) -> Result<Expression<'arena>, ParseError> {
        self.parse_or_expression()
    }

    /// Parse OR expression (lowest precedence).
    /// Produces a flat Disjunction for chains of 2+ OR operands.
    fn parse_or_expression(&mut self) -> Result<Expression<'arena>, ParseError> {
        let first = self.parse_and_expression()?;

        // Check if there's at least one OR
        if !self.peek_keyword(Keyword::Or) {
            return Ok(first);
        }

        // Collect all OR operands into a flat vector
        let mut terms = BumpVec::new_in(self.arena);
        terms.push(first);

        while self.peek_keyword(Keyword::Or) {
            self.consume_keyword(Keyword::Or)?;
            terms.push(self.parse_and_expression()?);
        }

        Ok(Expression::Disjunction(terms))
    }

    /// Parse AND expression.
    /// Produces a flat Conjunction for chains of 2+ AND operands.
    fn parse_and_expression(&mut self) -> Result<Expression<'arena>, ParseError> {
        let first = self.parse_not_expression()?;

        // Check if there's at least one AND
        if !self.peek_keyword(Keyword::And) {
            return Ok(first);
        }

        // Collect all AND operands into a flat vector
        let mut terms = BumpVec::new_in(self.arena);
        terms.push(first);

        while self.peek_keyword(Keyword::And) {
            self.consume_keyword(Keyword::And)?;
            terms.push(self.parse_not_expression()?);
        }

        Ok(Expression::Conjunction(terms))
    }

    /// Parse NOT expression.
    fn parse_not_expression(&mut self) -> Result<Expression<'arena>, ParseError> {
        if self.peek_keyword(Keyword::Not) {
            let saved_pos = self.position;
            self.advance();

            if self.peek_keyword(Keyword::In)
                || self.peek_keyword(Keyword::Between)
                || self.peek_keyword(Keyword::Like)
                || self.peek_keyword(Keyword::Exists)
            {
                self.position = saved_pos;
                return self.parse_comparison_expression();
            }

            let expr = self.parse_not_expression()?;
            let expr_ref = self.arena.alloc(expr);

            Ok(Expression::UnaryOp { op: UnaryOperator::Not, expr: expr_ref })
        } else {
            self.parse_comparison_expression()
        }
    }

    /// Parse comparison expression.
    fn parse_comparison_expression(&mut self) -> Result<Expression<'arena>, ParseError> {
        let mut left = self.parse_additive_expression()?;

        // Check for IN, BETWEEN, LIKE operators
        if self.peek_keyword(Keyword::Not) {
            let saved_pos = self.position;
            self.advance();

            if self.peek_keyword(Keyword::In) {
                self.consume_keyword(Keyword::In)?;
                self.expect_token(Token::LParen)?;

                // 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)
                    || is_subquery_through_parens
                {
                    // 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)?;
                    let left_ref = self.arena.alloc(left);
                    return Ok(Expression::Extended(self.arena.alloc(ExtendedExpr::In {
                        expr: left_ref,
                        subquery,
                        negated: true,
                    })));
                } else {
                    let values = self.parse_expression_list()?;
                    self.expect_token(Token::RParen)?;
                    let left_ref = self.arena.alloc(left);
                    return Ok(Expression::Extended(self.arena.alloc(ExtendedExpr::InList {
                        expr: left_ref,
                        values,
                        negated: true,
                    })));
                }
            } else if self.peek_keyword(Keyword::Between) {
                self.consume_keyword(Keyword::Between)?;
                let symmetric = self.try_consume_keyword(Keyword::Symmetric);
                if !symmetric {
                    self.try_consume_keyword(Keyword::Asymmetric);
                }

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

                let left_ref = self.arena.alloc(left);
                let low_ref = self.arena.alloc(low);
                let high_ref = self.arena.alloc(high);

                return Ok(Expression::Extended(self.arena.alloc(ExtendedExpr::Between {
                    expr: left_ref,
                    low: low_ref,
                    high: high_ref,
                    negated: true,
                    symmetric,
                })));
            } else if self.peek_keyword(Keyword::Like) {
                self.consume_keyword(Keyword::Like)?;
                let pattern = self.parse_additive_expression()?;
                let escape: Option<&Expression<'arena>> = if self.peek_keyword(Keyword::Escape) {
                    self.consume_keyword(Keyword::Escape)?;
                    Some(self.arena.alloc(self.parse_additive_expression()?))
                } else {
                    None
                };
                let left_ref = self.arena.alloc(left);
                let pattern_ref = self.arena.alloc(pattern);
                return Ok(Expression::Extended(self.arena.alloc(ExtendedExpr::Like {
                    expr: left_ref,
                    pattern: pattern_ref,
                    negated: true,
                    escape,
                })));
            } else if self.peek_keyword(Keyword::Null) {
                // SQLite compatibility: "expr NOT NULL" (without IS) is equivalent to "expr IS NOT NULL"
                self.consume_keyword(Keyword::Null)?;
                let left_ref = self.arena.alloc(left);
                return Ok(Expression::IsNull { expr: left_ref, negated: true });
            } else {
                self.position = saved_pos;
            }
        } else if self.peek_keyword(Keyword::In) {
            self.consume_keyword(Keyword::In)?;
            self.expect_token(Token::LParen)?;

            // 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)
                || is_subquery_through_parens
            {
                // 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)?;
                let left_ref = self.arena.alloc(left);
                return Ok(Expression::Extended(self.arena.alloc(ExtendedExpr::In {
                    expr: left_ref,
                    subquery,
                    negated: false,
                })));
            } else {
                let values = self.parse_expression_list()?;
                self.expect_token(Token::RParen)?;
                let left_ref = self.arena.alloc(left);
                return Ok(Expression::Extended(self.arena.alloc(ExtendedExpr::InList {
                    expr: left_ref,
                    values,
                    negated: false,
                })));
            }
        } else if self.peek_keyword(Keyword::Between) {
            self.consume_keyword(Keyword::Between)?;
            let symmetric = self.try_consume_keyword(Keyword::Symmetric);
            if !symmetric {
                self.try_consume_keyword(Keyword::Asymmetric);
            }

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

            let left_ref = self.arena.alloc(left);
            let low_ref = self.arena.alloc(low);
            let high_ref = self.arena.alloc(high);

            return Ok(Expression::Extended(self.arena.alloc(ExtendedExpr::Between {
                expr: left_ref,
                low: low_ref,
                high: high_ref,
                negated: false,
                symmetric,
            })));
        } else if self.peek_keyword(Keyword::Like) {
            self.consume_keyword(Keyword::Like)?;
            let pattern = self.parse_additive_expression()?;
            let escape: Option<&Expression<'arena>> = if self.peek_keyword(Keyword::Escape) {
                self.consume_keyword(Keyword::Escape)?;
                Some(self.arena.alloc(self.parse_additive_expression()?))
            } else {
                None
            };
            let left_ref = self.arena.alloc(left);
            let pattern_ref = self.arena.alloc(pattern);
            return Ok(Expression::Extended(self.arena.alloc(ExtendedExpr::Like {
                expr: left_ref,
                pattern: pattern_ref,
                negated: false,
                escape,
            })));
        }

        // Check for comparison operators
        let is_comparison = match self.peek() {
            Token::Symbol('=') | Token::Symbol('<') | Token::Symbol('>') => true,
            Token::Operator(s) => matches!(
                s,
                MultiCharOperator::LessEqual
                    | MultiCharOperator::GreaterEqual
                    | MultiCharOperator::NotEqual
                    | MultiCharOperator::NotEqualAlt
                    | MultiCharOperator::DoubleEqual
                    | MultiCharOperator::CosineDistance
                    | MultiCharOperator::NegativeInnerProduct
                    | MultiCharOperator::L2Distance
            ),
            _ => false,
        };

        if is_comparison {
            let op = match self.peek() {
                Token::Symbol('=') => BinaryOperator::Equal,
                Token::Symbol('<') => BinaryOperator::LessThan,
                Token::Symbol('>') => BinaryOperator::GreaterThan,
                Token::Operator(s) => match s {
                    MultiCharOperator::LessEqual => BinaryOperator::LessThanOrEqual,
                    MultiCharOperator::GreaterEqual => BinaryOperator::GreaterThanOrEqual,
                    MultiCharOperator::NotEqual | MultiCharOperator::NotEqualAlt => {
                        BinaryOperator::NotEqual
                    }
                    // SQLite compatibility: == is a synonym for =
                    MultiCharOperator::DoubleEqual => BinaryOperator::Equal,
                    // Vector distance operators (pgvector compatible)
                    MultiCharOperator::CosineDistance => BinaryOperator::CosineDistance,
                    MultiCharOperator::NegativeInnerProduct => BinaryOperator::NegativeInnerProduct,
                    MultiCharOperator::L2Distance => BinaryOperator::L2Distance,
                    _ => {
                        return Err(ParseError {
                            message: "Unexpected || operator in comparison".to_string(),
                        })
                    }
                },
                _ => 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.try_consume_keyword(Keyword::All) {
                    Quantifier::All
                } else if self.try_consume_keyword(Keyword::Any) {
                    Quantifier::Any
                } else {
                    self.consume_keyword(Keyword::Some)?;
                    Quantifier::Some
                };

                self.expect_token(Token::LParen)?;
                let subquery = self.parse_select_statement()?;
                self.expect_token(Token::RParen)?;

                let left_ref = self.arena.alloc(left);
                return Ok(Expression::Extended(self.arena.alloc(
                    ExtendedExpr::QuantifiedComparison { expr: left_ref, op, quantifier, subquery },
                )));
            }

            let right = self.parse_additive_expression()?;
            let left_ref = self.arena.alloc(left);
            let right_ref = self.arena.alloc(right);
            left = Expression::BinaryOp { op, left: left_ref, right: right_ref };
        }

        // 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)?;
            let negated = self.try_consume_keyword(Keyword::Not);

            // 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_additive_expression()?;
                let left_ref = self.arena.alloc(left);
                let right_ref = self.arena.alloc(right);
                left = Expression::IsDistinctFrom { left: left_ref, right: right_ref, negated };
            } else if self.peek_keyword(Keyword::True) {
                self.consume_keyword(Keyword::True)?;
                let left_ref = self.arena.alloc(left);
                left = Expression::IsTruthValue {
                    expr: left_ref,
                    truth_value: TruthValue::True,
                    negated,
                };
            } else if self.peek_keyword(Keyword::False) {
                self.consume_keyword(Keyword::False)?;
                let left_ref = self.arena.alloc(left);
                left = Expression::IsTruthValue {
                    expr: left_ref,
                    truth_value: TruthValue::False,
                    negated,
                };
            } else if self.peek_keyword(Keyword::Unknown) {
                self.consume_keyword(Keyword::Unknown)?;
                let left_ref = self.arena.alloc(left);
                left = Expression::IsTruthValue {
                    expr: left_ref,
                    truth_value: TruthValue::Unknown,
                    negated,
                };
            } else if self.peek_keyword(Keyword::Null) {
                // IS NULL / IS NOT NULL
                self.consume_keyword(Keyword::Null)?;
                let left_ref = self.arena.alloc(left);
                left = Expression::IsNull { expr: left_ref, 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_additive_expression()?;
                let left_ref = self.arena.alloc(left);
                let right_ref = self.arena.alloc(right);
                // IS is equivalent to IS NOT DISTINCT FROM (NULL-safe equals)
                // IS NOT is equivalent to IS DISTINCT FROM (NULL-safe not equals)
                left = Expression::IsDistinctFrom {
                    left: left_ref,
                    right: right_ref,
                    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)?;
                let left_ref = self.arena.alloc(left);
                left = Expression::IsNull { expr: left_ref, negated: false };
            } else if self.peek_keyword(Keyword::Notnull) {
                self.consume_keyword(Keyword::Notnull)?;
                let left_ref = self.arena.alloc(left);
                left = Expression::IsNull { expr: left_ref, negated: true };
            } else {
                break;
            }
        }

        Ok(left)
    }

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

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

            let right = self.parse_concat_expression()?;
            let left_ref = self.arena.alloc(left);
            let right_ref = self.arena.alloc(right);
            left = Expression::BinaryOp { op, left: left_ref, right: right_ref };
        }

        Ok(left)
    }

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

        while self.peek() == &Token::Operator(MultiCharOperator::Concat) {
            self.advance();
            let right = self.parse_multiplicative_expression()?;
            let left_ref = self.arena.alloc(left);
            let right_ref = self.arena.alloc(right);
            left = Expression::BinaryOp {
                op: BinaryOperator::Concat,
                left: left_ref,
                right: right_ref,
            };
        }

        Ok(left)
    }

    /// Parse multiplicative expression.
    fn parse_multiplicative_expression(&mut self) -> Result<Expression<'arena>, ParseError> {
        let mut left = self.parse_unary_expression()?;

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

            let right = self.parse_unary_expression()?;
            let left_ref = self.arena.alloc(left);
            let right_ref = self.arena.alloc(right);
            left = Expression::BinaryOp { op, left: left_ref, right: right_ref };
        }

        Ok(left)
    }

    /// Parse unary expression.
    fn parse_unary_expression(&mut self) -> Result<Expression<'arena>, ParseError> {
        match self.peek() {
            Token::Symbol('+') => {
                self.advance();
                let expr = self.parse_unary_expression()?;
                let expr_ref = self.arena.alloc(expr);
                Ok(Expression::UnaryOp { op: UnaryOperator::Plus, expr: expr_ref })
            }
            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.
                if let Token::Number(n) = self.peek() {
                    if n == "9223372036854775808" {
                        self.advance();
                        return Ok(Expression::Literal(SqlValue::Integer(i64::MIN)));
                    }
                }
                let expr = self.parse_unary_expression()?;
                let expr_ref = self.arena.alloc(expr);
                Ok(Expression::UnaryOp { op: UnaryOperator::Minus, expr: expr_ref })
            }
            _ => self.parse_primary_expression(),
        }
    }

    /// Parse primary expression.
    fn parse_primary_expression(&mut self) -> Result<Expression<'arena>, ParseError> {
        // Placeholder (?)
        if matches!(self.peek(), Token::Placeholder) {
            self.advance();
            let index = self.next_placeholder();
            return Ok(Expression::Placeholder(index));
        }

        // Numbered placeholder ($1, $2, etc.)
        if let Token::NumberedPlaceholder(n) = self.peek() {
            let index = *n;
            self.advance();
            return Ok(Expression::NumberedPlaceholder(index));
        }

        // Named placeholder (:name)
        if let Token::NamedPlaceholder(name) = self.peek() {
            let name = name.clone();
            self.advance();
            let name = self.intern(&name);
            return Ok(Expression::NamedPlaceholder(name));
        }

        // Session variable (@@...)
        if let Token::SessionVariable(name) = self.peek() {
            let name = name.clone();
            self.advance();
            let name = self.intern(&name);
            return Ok(Expression::Extended(
                self.arena.alloc(ExtendedExpr::SessionVariable { name }),
            ));
        }

        // Literals
        if let Some(expr) = self.parse_literal()? {
            return Ok(expr);
        }

        // EXISTS / NOT EXISTS
        if self.peek_keyword(Keyword::Exists) || self.peek_keyword(Keyword::Not) {
            if let Some(expr) = self.parse_exists()? {
                return Ok(expr);
            }
        }

        // CASE expression
        if self.peek_keyword(Keyword::Case) {
            return self.parse_case_expression();
        }

        // CAST expression
        if self.peek_keyword(Keyword::Cast) {
            return self.parse_cast_expression();
        }

        // Current date/time
        if let Some(expr) = self.parse_current_datetime()? {
            return Ok(expr);
        }

        // Function call or identifier
        // Extract identifier from token (handles both regular identifiers and keywords-as-identifiers)
        let first_ident = match self.peek() {
            Token::Identifier(name) => Some((name.clone(), false)),
            Token::DelimitedIdentifier(name) => Some((name.clone(), true)),
            Token::Keyword { keyword: kw, .. } if kw.can_be_identifier() => {
                // Keywords like TEMP, YEAR, MONTH, etc. can be used as identifiers
                Some((kw.to_string().to_lowercase(), false))
            }
            _ => None,
        };

        if let Some((name, first_quoted)) = first_ident {
            // Check if it's a function call
            if matches!(self.tokens.get(self.position + 1), Some(Token::LParen)) {
                return self.parse_function_call(&name);
            }

            // Otherwise it's a column reference
            self.advance();
            let name_sym = self.intern(&name);

            // Check for qualified name (table.column or schema.table.column)
            if self.try_consume(&Token::Symbol('.')) {
                // Second part: identifier or any keyword (keywords allowed after .)
                let second_ident = match self.peek() {
                    Token::Identifier(id) => Some((id.clone(), false)),
                    Token::DelimitedIdentifier(id) => Some((id.clone(), true)),
                    Token::Keyword { keyword: kw, .. } => {
                        // Any keyword can be used as table/column name when qualified
                        Some((kw.to_string().to_lowercase(), false))
                    }
                    _ => None,
                };

                if let Some((second, second_quoted)) = second_ident {
                    self.advance();
                    let second_sym = self.intern(&second);

                    // Check for three-part name (schema.table.column)
                    if self.try_consume(&Token::Symbol('.')) {
                        // Third part: identifier or any keyword
                        let third_ident = match self.peek() {
                            Token::Identifier(id) => Some((id.clone(), false)),
                            Token::DelimitedIdentifier(id) => Some((id.clone(), true)),
                            Token::Keyword { keyword: kw, .. } => {
                                Some((kw.to_string().to_lowercase(), false))
                            }
                            _ => None,
                        };

                        if let Some((third, third_quoted)) = third_ident {
                            self.advance();
                            let third_sym = self.intern(&third);
                            return Ok(Expression::ColumnRef {
                                schema: Some(name_sym),
                                table: Some(second_sym),
                                column: third_sym,
                                schema_quoted: first_quoted,
                                table_quoted: second_quoted,
                                column_quoted: third_quoted,
                            });
                        } else if matches!(self.peek(), Token::Symbol('*')) {
                            // schema.table.* - not supported, treat as error
                            self.advance();
                            return Ok(Expression::Wildcard);
                        }
                    }

                    // Two-part name (table.column)
                    return Ok(Expression::ColumnRef {
                        schema: None,
                        table: Some(name_sym),
                        column: second_sym,
                        schema_quoted: false,
                        table_quoted: first_quoted,
                        column_quoted: second_quoted,
                    });
                } else if matches!(self.peek(), Token::Symbol('*')) {
                    self.advance();
                    return Ok(Expression::Wildcard);
                }
            }

            return Ok(Expression::ColumnRef {
                schema: None,
                table: None,
                column: name_sym,
                schema_quoted: false,
                table_quoted: false,
                column_quoted: first_quoted,
            });
        }

        // Wildcard (*)
        if matches!(self.peek(), Token::Symbol('*')) {
            self.advance();
            return Ok(Expression::Wildcard);
        }

        // Parenthesized expression, subquery, or row value constructor (tuple)
        if matches!(self.peek(), Token::LParen) {
            self.advance();

            // Check for subquery (SELECT or WITH-prefixed SELECT)
            if self.peek_keyword(Keyword::Select) || self.peek_keyword(Keyword::With) {
                let subquery = self.parse_select_statement()?;
                self.expect_token(Token::RParen)?;
                return Ok(Expression::Extended(
                    self.arena.alloc(ExtendedExpr::ScalarSubquery(subquery)),
                ));
            }

            // Parse first expression
            let first_expr = self.parse_expression()?;

            // Check if this is a row value constructor (tuple): (expr, expr, ...)
            if matches!(self.peek(), Token::Comma) {
                let mut values = BumpVec::new_in(self.arena);
                values.push(first_expr);
                while matches!(self.peek(), Token::Comma) {
                    self.advance(); // consume ','
                    values.push(self.parse_expression()?);
                }
                self.expect_token(Token::RParen)?;
                return Ok(Expression::Extended(
                    self.arena.alloc(ExtendedExpr::RowValueConstructor(values)),
                ));
            }

            // Regular parenthesized expression
            self.expect_token(Token::RParen)?;
            return Ok(first_expr);
        }

        Err(ParseError { message: self.peek().syntax_error() })
    }

    /// Parse literal values.
    fn parse_literal(&mut self) -> Result<Option<Expression<'arena>>, ParseError> {
        let expr = match self.peek() {
            Token::Number(n) => {
                let n = n.clone();
                self.advance();
                // Try to parse as integer first, then as float
                if let Ok(i) = n.parse::<i64>() {
                    Some(Expression::Literal(SqlValue::Integer(i)))
                } else if let Ok(f) = n.parse::<f64>() {
                    Some(Expression::Literal(SqlValue::Double(f)))
                } else {
                    return Err(ParseError { message: format!("Invalid number: {}", n) });
                }
            }
            Token::String(s) => {
                let s = arcstr::ArcStr::from(s.as_str());
                self.advance();
                Some(Expression::Literal(SqlValue::Varchar(s)))
            }
            Token::BlobLiteral(bytes) => {
                let blob = bytes.clone();
                self.advance();
                Some(Expression::Literal(SqlValue::Blob(blob)))
            }
            Token::Keyword { keyword: Keyword::True, .. } => {
                self.advance();
                Some(Expression::Literal(SqlValue::Boolean(true)))
            }
            Token::Keyword { keyword: Keyword::False, .. } => {
                self.advance();
                Some(Expression::Literal(SqlValue::Boolean(false)))
            }
            Token::Keyword { keyword: Keyword::Null, .. } => {
                self.advance();
                Some(Expression::Literal(SqlValue::Null))
            }
            Token::Keyword { keyword: Keyword::Default, .. } => {
                self.advance();
                Some(Expression::Default)
            }
            // Typed literals: DATE 'string', TIME 'string', TIMESTAMP 'string'
            // If not followed by a string literal, treat as column name (SQLite compatibility)
            Token::Keyword { keyword: Keyword::Date, .. } => {
                // date(...) is a function call, not a typed literal - don't consume
                // the keyword; the identifier path routes it to parse_function_call
                // via can_be_identifier() (issue #5307)
                if matches!(self.peek_next(), Token::LParen) {
                    return Ok(None);
                }
                self.advance();
                match self.peek() {
                    Token::String(s) => {
                        let date_str = s.clone();
                        self.advance();
                        match date_str.parse::<vibesql_types::Date>() {
                            Ok(date) => Some(Expression::Literal(SqlValue::Date(date))),
                            Err(e) => {
                                return Err(ParseError {
                                    message: format!("Invalid DATE literal: {}", e),
                                })
                            }
                        }
                    }
                    _ => {
                        // Treat DATE as column name when not followed by string literal
                        Some(Expression::ColumnRef {
                            schema: None,
                            table: None,
                            column: self.interner.intern("DATE"),
                            schema_quoted: false,
                            table_quoted: false,
                            column_quoted: false,
                        })
                    }
                }
            }
            Token::Keyword { keyword: Keyword::Time, .. } => {
                // time(...) is a function call, not a typed literal - don't consume
                // the keyword; the identifier path routes it to parse_function_call
                // via can_be_identifier() (issue #5307)
                if matches!(self.peek_next(), Token::LParen) {
                    return Ok(None);
                }
                self.advance();
                match self.peek() {
                    Token::String(s) => {
                        let time_str = s.clone();
                        self.advance();
                        match time_str.parse::<vibesql_types::Time>() {
                            Ok(time) => Some(Expression::Literal(SqlValue::Time(time))),
                            Err(e) => {
                                return Err(ParseError {
                                    message: format!("Invalid TIME literal: {}", e),
                                })
                            }
                        }
                    }
                    _ => {
                        // Treat TIME as column name when not followed by string literal
                        Some(Expression::ColumnRef {
                            schema: None,
                            table: None,
                            column: self.interner.intern("TIME"),
                            schema_quoted: false,
                            table_quoted: false,
                            column_quoted: false,
                        })
                    }
                }
            }
            Token::Keyword { keyword: Keyword::Timestamp, .. } => {
                self.advance();
                match self.peek() {
                    Token::String(s) => {
                        let timestamp_str = s.clone();
                        self.advance();
                        match timestamp_str.parse::<vibesql_types::Timestamp>() {
                            Ok(timestamp) => {
                                Some(Expression::Literal(SqlValue::Timestamp(timestamp)))
                            }
                            Err(e) => {
                                return Err(ParseError {
                                    message: format!("Invalid TIMESTAMP literal: {}", e),
                                })
                            }
                        }
                    }
                    _ => {
                        // Treat TIMESTAMP as column name when not followed by string literal
                        Some(Expression::ColumnRef {
                            schema: None,
                            table: None,
                            column: self.interner.intern("TIMESTAMP"),
                            schema_quoted: false,
                            table_quoted: false,
                            column_quoted: false,
                        })
                    }
                }
            }
            Token::Keyword { keyword: Keyword::Interval, .. } => {
                return self.parse_interval_literal();
            }
            _ => None,
        };
        Ok(expr)
    }

    /// Parse INTERVAL literal: INTERVAL 'value' field [TO field]
    fn parse_interval_literal(&mut self) -> Result<Option<Expression<'arena>>, ParseError> {
        self.advance(); // consume INTERVAL keyword
        match self.peek() {
            Token::String(interval_str) => {
                let value_str = interval_str.clone();
                self.advance();

                // Parse interval field (YEAR, MONTH, DAY, etc.)
                let start_field = self.parse_interval_field()?;

                // Check for TO (multi-field interval)
                let interval_spec = if self.try_consume_keyword(Keyword::To) {
                    let end_field = self.parse_interval_field()?;
                    format!("{} {} TO {}", value_str, start_field, end_field)
                } else {
                    format!("{} {}", value_str, start_field)
                };

                // Parse the interval string into an Interval type
                match interval_spec.parse::<vibesql_types::Interval>() {
                    Ok(interval) => Ok(Some(Expression::Literal(SqlValue::Interval(interval)))),
                    Err(e) => {
                        Err(ParseError { message: format!("Invalid INTERVAL literal: {}", e) })
                    }
                }
            }
            _ => Err(ParseError {
                message: "Expected string literal after INTERVAL keyword".to_string(),
            }),
        }
    }

    /// Parse an interval field name (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND).
    fn parse_interval_field(&mut self) -> Result<String, ParseError> {
        let field = match self.peek() {
            Token::Identifier(field) => field.to_uppercase(),
            Token::Keyword { keyword: Keyword::Year, .. } => "YEAR".to_string(),
            Token::Keyword { keyword: Keyword::Month, .. } => "MONTH".to_string(),
            Token::Keyword { keyword: Keyword::Day, .. } => "DAY".to_string(),
            Token::Keyword { keyword: Keyword::Hour, .. } => "HOUR".to_string(),
            Token::Keyword { keyword: Keyword::Minute, .. } => "MINUTE".to_string(),
            Token::Keyword { keyword: Keyword::Second, .. } => "SECOND".to_string(),
            _ => {
                return Err(ParseError {
                    message: "Expected interval field (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND)"
                        .to_string(),
                })
            }
        };
        self.advance();
        Ok(field)
    }

    /// Parse EXISTS / NOT EXISTS.
    fn parse_exists(&mut self) -> Result<Option<Expression<'arena>>, ParseError> {
        let negated = if self.peek_keyword(Keyword::Not) {
            self.advance();
            if !self.peek_keyword(Keyword::Exists) {
                self.position -= 1;
                return Ok(None);
            }
            true
        } else {
            false
        };

        if self.peek_keyword(Keyword::Exists) {
            self.advance();
            self.expect_token(Token::LParen)?;
            let subquery = self.parse_select_statement()?;
            self.expect_token(Token::RParen)?;
            return Ok(Some(Expression::Extended(
                self.arena.alloc(ExtendedExpr::Exists { subquery, negated }),
            )));
        }

        Ok(None)
    }

    /// Parse CASE expression.
    fn parse_case_expression(&mut self) -> Result<Expression<'arena>, ParseError> {
        self.consume_keyword(Keyword::Case)?;

        // Check for simple CASE (CASE expr WHEN ...)
        let operand: Option<&'arena Expression<'arena>> = if !self.peek_keyword(Keyword::When) {
            let expr = self.parse_expression()?;
            Some(self.arena.alloc(expr))
        } else {
            None
        };

        // Parse WHEN clauses
        let mut when_clauses = BumpVec::new_in(self.arena);
        while self.peek_keyword(Keyword::When) {
            self.consume_keyword(Keyword::When)?;

            let mut conditions = BumpVec::new_in(self.arena);
            conditions.push(self.parse_expression()?);

            // Handle multiple conditions (WHEN a, b, c THEN ...)
            while self.try_consume(&Token::Comma) {
                conditions.push(self.parse_expression()?);
            }

            self.consume_keyword(Keyword::Then)?;
            let result = self.parse_expression()?;

            when_clauses.push(CaseWhen { conditions, result });
        }

        // Parse optional ELSE
        let else_result: Option<&'arena Expression<'arena>> =
            if self.try_consume_keyword(Keyword::Else) {
                let expr = self.parse_expression()?;
                Some(self.arena.alloc(expr))
            } else {
                None
            };

        self.consume_keyword(Keyword::End)?;

        Ok(Expression::Extended(self.arena.alloc(ExtendedExpr::Case {
            operand,
            when_clauses,
            else_result,
        })))
    }

    /// Parse CAST expression.
    fn parse_cast_expression(&mut self) -> Result<Expression<'arena>, ParseError> {
        self.consume_keyword(Keyword::Cast)?;
        self.expect_token(Token::LParen)?;

        let expr = self.parse_expression()?;
        let expr_ref = self.arena.alloc(expr);

        self.consume_keyword(Keyword::As)?;
        // SQLite tolerates a missing type name: CAST(x AS ) gets NUMERIC
        // affinity, same as an unrecognized type name
        // (sqlite3AffinityType("") falls through to NUMERIC).
        let data_type = if matches!(self.peek(), Token::RParen) {
            vibesql_types::DataType::Numeric { precision: 38, scale: 0 }
        } else {
            self.parse_data_type()?
        };

        self.expect_token(Token::RParen)?;

        Ok(Expression::Extended(self.arena.alloc(ExtendedExpr::Cast { expr: expr_ref, data_type })))
    }

    /// Parse current date/time functions.
    fn parse_current_datetime(&mut self) -> Result<Option<Expression<'arena>>, ParseError> {
        if self.peek_keyword(Keyword::CurrentDate) {
            self.advance();
            return Ok(Some(Expression::CurrentDate));
        }

        if self.peek_keyword(Keyword::CurrentTime) {
            self.advance();
            let precision = self.parse_optional_precision()?;
            return Ok(Some(Expression::CurrentTime { precision }));
        }

        if self.peek_keyword(Keyword::CurrentTimestamp) {
            self.advance();
            let precision = self.parse_optional_precision()?;
            return Ok(Some(Expression::CurrentTimestamp { precision }));
        }

        Ok(None)
    }

    /// Parse optional precision (e.g., CURRENT_TIME(3)).
    fn parse_optional_precision(&mut self) -> Result<Option<u32>, ParseError> {
        if self.try_consume(&Token::LParen) {
            if let Token::Number(n) = self.peek() {
                let n = n
                    .parse::<u32>()
                    .map_err(|_| ParseError { message: "Invalid precision".to_string() })?;
                self.advance();
                self.expect_token(Token::RParen)?;
                return Ok(Some(n));
            }
            self.expect_token(Token::RParen)?;
        }
        Ok(None)
    }

    /// Parse function call.
    fn parse_function_call(&mut self, name: &str) -> Result<Expression<'arena>, ParseError> {
        let name_upper = name.to_uppercase();
        let name_sym = self.intern(name);
        self.advance(); // consume function name
        self.expect_token(Token::LParen)?;

        // Check if this might be an aggregate function (before we know argument count)
        // Note: MIN/MAX with multiple arguments are scalar functions (like LEAST/GREATEST)
        // while MIN/MAX with a single argument are aggregate functions
        let might_be_aggregate = matches!(
            name_upper.as_str(),
            "COUNT" | "SUM" | "AVG" | "MIN" | "MAX" | "GROUP_CONCAT" | "STRING_AGG" | "TOTAL"
        );

        if might_be_aggregate {
            let distinct = self.try_consume_keyword(Keyword::Distinct);
            self.try_consume_keyword(Keyword::All); // ALL is default

            let args = if matches!(self.peek(), Token::RParen) {
                BumpVec::new_in(self.arena)
            } else {
                self.parse_expression_list()?
            };

            self.expect_token(Token::RParen)?;

            // Check for OVER clause (window function)
            if self.peek_keyword(Keyword::Over) {
                // Validate argument count for window functions
                Self::validate_window_function_args(&name_upper, args.len(), name)?;
                return self.parse_window_function(name_sym, &name_upper, args);
            }

            // Determine if this is truly an aggregate function
            // MIN/MAX with >1 argument are scalar functions (SQLite compatibility)
            // GROUP_CONCAT accepts 1 or 2 arguments (expr, separator)
            let is_aggregate = match name_upper.as_str() {
                "COUNT" | "SUM" | "AVG" | "TOTAL" => true,
                "GROUP_CONCAT" | "STRING_AGG" => args.len() <= 2, // 1 or 2 args
                "MIN" | "MAX" => args.len() <= 1 && !distinct,
                _ => false,
            };

            if is_aggregate {
                // DISTINCT aggregates must have exactly one argument (SQLite compatibility)
                if distinct && args.len() != 1 {
                    return Err(ParseError {
                        message: "DISTINCT aggregates must have exactly one argument".to_string(),
                    });
                }
                return Ok(Expression::Extended(
                    self.arena.alloc(ExtendedExpr::AggregateFunction {
                        name: name_sym,
                        distinct,
                        args,
                    }),
                ));
            } else {
                // Multi-argument MIN/MAX - treat as scalar function
                return Ok(Expression::Extended(self.arena.alloc(ExtendedExpr::Function {
                    name: name_sym,
                    args,
                    character_unit: None,
                })));
            }
        }

        // Regular function
        let args = if matches!(self.peek(), Token::RParen) {
            BumpVec::new_in(self.arena)
        } else {
            self.parse_expression_list()?
        };

        self.expect_token(Token::RParen)?;

        // Check for OVER clause
        if self.peek_keyword(Keyword::Over) {
            // Validate argument count for window functions
            Self::validate_window_function_args(&name_upper, args.len(), name)?;
            return self.parse_window_function(name_sym, &name_upper, args);
        }

        // Check if this is a window-only function used without OVER clause
        // These functions REQUIRE an OVER clause - they cannot be used as scalar functions
        if Self::is_window_only_function(&name_upper) {
            return Err(ParseError {
                message: format!("misuse of window function {}()", name.to_lowercase()),
            });
        }

        Ok(Expression::Extended(self.arena.alloc(ExtendedExpr::Function {
            name: name_sym,
            args,
            character_unit: None,
        })))
    }

    /// Check if a function is a window-only function that requires an OVER clause.
    /// These functions cannot be used as scalar functions - they MUST have an OVER clause.
    fn is_window_only_function(name: &str) -> bool {
        matches!(
            name,
            // Ranking functions
            "ROW_NUMBER" | "RANK" | "DENSE_RANK" | "NTILE" | "PERCENT_RANK" | "CUME_DIST" |
            // Value functions
            "LAG" | "LEAD" | "FIRST_VALUE" | "LAST_VALUE" | "NTH_VALUE"
        )
    }

    /// Validate argument count for window functions.
    fn validate_window_function_args(
        name: &str,
        arg_count: usize,
        original_name: &str,
    ) -> Result<(), ParseError> {
        let (min_args, max_args) = match name {
            // Zero-argument ranking functions
            "ROW_NUMBER" | "RANK" | "DENSE_RANK" | "PERCENT_RANK" | "CUME_DIST" => (0, 0),
            // Single-argument functions
            "NTILE" | "FIRST_VALUE" | "LAST_VALUE" => (1, 1),
            // Variable-argument value functions
            "LAG" | "LEAD" => (1, 3),
            // Two-argument function
            "NTH_VALUE" => (2, 2),
            // Not a window-only function, no validation needed
            _ => return Ok(()),
        };

        if arg_count < min_args || arg_count > max_args {
            return Err(ParseError {
                message: format!(
                    "wrong number of arguments to function {}()",
                    original_name.to_lowercase()
                ),
            });
        }

        Ok(())
    }

    /// Classify a window function as aggregate, ranking, or value.
    ///
    /// This mirrors the classification in the regular parser to ensure
    /// consistent behavior between parsing modes.
    fn classify_window_function(
        name_upper: &str,
        name: Symbol,
        args: BumpVec<'arena, Expression<'arena>>,
    ) -> WindowFunctionSpec<'arena> {
        match name_upper {
            // Ranking functions
            "ROW_NUMBER" | "RANK" | "DENSE_RANK" | "NTILE" | "PERCENT_RANK" | "CUME_DIST" => {
                WindowFunctionSpec::Ranking { name, args }
            }
            // Value functions
            "LAG" | "LEAD" | "FIRST_VALUE" | "LAST_VALUE" | "NTH_VALUE" => {
                WindowFunctionSpec::Value { name, args }
            }
            // Everything else is an aggregate function
            _ => WindowFunctionSpec::Aggregate { name, args },
        }
    }

    /// Parse window function (OVER clause).
    fn parse_window_function(
        &mut self,
        name: Symbol,
        name_upper: &str,
        args: BumpVec<'arena, Expression<'arena>>,
    ) -> Result<Expression<'arena>, ParseError> {
        self.consume_keyword(Keyword::Over)?;
        self.expect_token(Token::LParen)?;

        // Parse PARTITION BY
        let partition_by = if self.try_consume_keyword(Keyword::Partition) {
            self.consume_keyword(Keyword::By)?;
            Some(self.parse_expression_list()?)
        } else {
            None
        };

        // Parse ORDER BY
        let order_by = if self.try_consume_keyword(Keyword::Order) {
            self.consume_keyword(Keyword::By)?;
            Some(self.parse_order_by_list()?)
        } else {
            None
        };

        // Parse frame clause (simplified)
        let frame = None; // TODO: implement frame parsing

        self.expect_token(Token::RParen)?;

        // Classify the window function based on its name
        let function = Self::classify_window_function(name_upper, name, args);
        let over = WindowSpec { partition_by, order_by, frame };

        Ok(Expression::Extended(self.arena.alloc(ExtendedExpr::WindowFunction { function, over })))
    }

    /// Parse comma-separated expression list.
    pub(crate) fn parse_expression_list(
        &mut self,
    ) -> Result<BumpVec<'arena, Expression<'arena>>, ParseError> {
        let mut exprs = BumpVec::new_in(self.arena);

        if matches!(self.peek(), Token::RParen) {
            return Ok(exprs);
        }

        exprs.push(self.parse_expression()?);

        while self.try_consume(&Token::Comma) {
            exprs.push(self.parse_expression()?);
        }

        Ok(exprs)
    }

    /// Parse ORDER BY list.
    fn parse_order_by_list(&mut self) -> Result<BumpVec<'arena, OrderByItem<'arena>>, ParseError> {
        let mut items = BumpVec::new_in(self.arena);

        loop {
            let expr = self.parse_expression()?;
            let direction = if self.try_consume_keyword(Keyword::Desc) {
                OrderDirection::Desc
            } else {
                self.try_consume_keyword(Keyword::Asc);
                OrderDirection::Asc
            };

            // Parse optional NULLS FIRST/LAST (SQL:2003 extension)
            let nulls_order = if self.try_consume_keyword(Keyword::Nulls) {
                if self.try_consume_keyword(Keyword::First) {
                    Some(NullsOrder::First)
                } else if self.try_consume_keyword(Keyword::Last) {
                    Some(NullsOrder::Last)
                } else {
                    return Err(crate::ParseError {
                        message: format!(
                            "Expected FIRST or LAST after NULLS, found {:?}",
                            self.peek()
                        ),
                    });
                }
            } else {
                None
            };

            items.push(OrderByItem { expr, direction, nulls_order });

            if !self.try_consume(&Token::Comma) {
                break;
            }
        }

        Ok(items)
    }

    /// Parse data type (simplified).
    pub(crate) fn parse_data_type(&mut self) -> Result<vibesql_types::DataType, ParseError> {
        // Get type name as uppercase string
        let type_upper = match self.peek() {
            Token::Identifier(type_name) => type_name.to_uppercase(),
            Token::Keyword { keyword: Keyword::Date, .. } => "DATE".to_string(),
            Token::Keyword { keyword: Keyword::Time, .. } => "TIME".to_string(),
            Token::Keyword { keyword: Keyword::Timestamp, .. } => "TIMESTAMP".to_string(),
            Token::Keyword { keyword: Keyword::Interval, .. } => "INTERVAL".to_string(),
            Token::Keyword { keyword: Keyword::Character, .. } => "CHARACTER".to_string(),
            Token::Keyword { keyword: Keyword::Boolean, .. } => "BOOLEAN".to_string(),
            Token::Keyword { keyword: Keyword::Any, .. } => "ANY".to_string(),
            _ => return Err(ParseError { message: self.peek().syntax_error() }),
        };
        self.advance();

        match type_upper.as_str() {
            "INTEGER" | "INT" => Ok(vibesql_types::DataType::Integer),
            "SMALLINT" => Ok(vibesql_types::DataType::Smallint),
            "BIGINT" => Ok(vibesql_types::DataType::Bigint),
            "BOOLEAN" | "BOOL" => Ok(vibesql_types::DataType::Boolean),
            "FLOAT" => {
                // Parse optional precision
                if self.try_consume(&Token::LParen) {
                    if let Token::Number(_) = self.peek() {
                        self.advance();
                    }
                    self.expect_token(Token::RParen)?;
                }
                Ok(vibesql_types::DataType::Float { precision: 53 })
            }
            "REAL" => Ok(vibesql_types::DataType::Real),
            "DOUBLE" => {
                // Check for DOUBLE PRECISION
                if let Token::Identifier(next) = self.peek() {
                    if next.to_uppercase() == "PRECISION" {
                        self.advance();
                    }
                }
                Ok(vibesql_types::DataType::DoublePrecision)
            }
            "VARCHAR" | "CHARACTER" => {
                // Parse optional length
                if self.try_consume(&Token::LParen) {
                    if let Token::Number(n) = self.peek() {
                        let len = n.parse::<usize>().ok();
                        self.advance();
                        self.expect_token(Token::RParen)?;
                        return Ok(vibesql_types::DataType::Varchar { max_length: len });
                    }
                    self.expect_token(Token::RParen)?;
                }
                Ok(vibesql_types::DataType::Varchar { max_length: None })
            }
            "TEXT" => {
                // SQLite allows TEXT(n) for compatibility but ignores the size
                if self.try_consume(&Token::LParen) {
                    // Parse and ignore the size parameter
                    if let Token::Number(_) = self.peek() {
                        self.advance();
                    }
                    self.expect_token(Token::RParen)?;
                }
                Ok(vibesql_types::DataType::Varchar { max_length: None })
            }
            "DATE" => Ok(vibesql_types::DataType::Date),
            "TIME" => Ok(vibesql_types::DataType::Time { with_timezone: false }),
            "TIMESTAMP" => Ok(vibesql_types::DataType::Timestamp { with_timezone: false }),
            "NUMERIC" | "DECIMAL" | "DEC" => {
                // Parse optional precision and scale
                if self.try_consume(&Token::LParen) {
                    let precision = if let Token::Number(n) = self.peek() {
                        let p = n.parse::<u8>().unwrap_or(38);
                        self.advance();
                        p
                    } else {
                        38
                    };
                    let scale = if self.try_consume(&Token::Comma) {
                        if let Token::Number(n) = self.peek() {
                            let s = n.parse::<u8>().unwrap_or(0);
                            self.advance();
                            s
                        } else {
                            0
                        }
                    } else {
                        0
                    };
                    self.expect_token(Token::RParen)?;
                    Ok(vibesql_types::DataType::Numeric { precision, scale })
                } else {
                    Ok(vibesql_types::DataType::Numeric { precision: 38, scale: 0 })
                }
            }
            "UNSIGNED" => Ok(vibesql_types::DataType::Unsigned),
            "SIGNED" => Ok(vibesql_types::DataType::Integer),
            "BLOB" | "ANY" => Ok(vibesql_types::DataType::BinaryLargeObject),
            "CHAR" => {
                // Parse optional length
                let length = if self.try_consume(&Token::LParen) {
                    let len = if let Token::Number(n) = self.peek() {
                        let l = n.parse::<usize>().unwrap_or(1);
                        self.advance();
                        l
                    } else {
                        1
                    };
                    self.expect_token(Token::RParen)?;
                    len
                } else {
                    1
                };
                Ok(vibesql_types::DataType::Character { length })
            }
            _ => {
                // Unknown type - default to varchar
                Ok(vibesql_types::DataType::Varchar { max_length: None })
            }
        }
    }
}