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
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
// Copyright 2025 Stoolap Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Expression Compiler
//
// Transforms AST Expressions into compiled Programs.
// This is where the magic happens - we convert recursive AST into linear bytecode.
//
// Design principles:
// 1. Resolve everything at compile time (column indices, function pointers, patterns)
// 2. Flatten recursion into linear instruction sequences
// 3. Handle short-circuit evaluation with jumps
// 4. Pre-compute constant expressions where possible
use std::cell::Cell;
use std::sync::Arc;
use crate::common::CompactArc;
use crate::common::SmartString;
use crate::common::StringMap;
use rustc_hash::{FxHashMap, FxHashSet};
use super::ops::{CompareOp, CompiledPattern, Op};
use super::program::{Program, ProgramBuilder};
use super::vm::{ExecuteContext, ExprVM};
use crate::core::{DataType, Row, Value, ValueSet};
use crate::executor::utils::{expression_to_string, string_to_datatype};
use crate::functions::{global_registry, FunctionRegistry};
use crate::parser::ast::*;
/// Compilation error
#[derive(Debug, Clone)]
pub enum CompileError {
/// Column not found
ColumnNotFound(String),
/// Function not found
FunctionNotFound(String),
/// Invalid expression
InvalidExpression(String),
/// Unsupported expression type
UnsupportedExpression(String),
/// Type error
TypeError(String),
}
impl std::fmt::Display for CompileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CompileError::ColumnNotFound(name) => {
write!(f, "Column '{}' not found", name)
}
CompileError::FunctionNotFound(name) => write!(f, "Function not found: {}", name),
CompileError::InvalidExpression(msg) => write!(f, "Invalid expression: {}", msg),
CompileError::UnsupportedExpression(msg) => {
write!(f, "Unsupported expression: {}", msg)
}
CompileError::TypeError(msg) => write!(f, "Type error: {}", msg),
}
}
}
impl std::error::Error for CompileError {}
/// Result of column resolution - indicates which row the column is from
#[derive(Debug, Clone, Copy)]
pub enum ColumnSource {
/// Column from first row with given index
Row1(u16),
/// Column from second row (for joins) with given index
Row2(u16),
}
/// Compilation context
///
/// Contains all the information needed to compile expressions:
/// - Column name to index mapping
/// - Function registry
/// - Outer query columns (for correlated subqueries)
pub struct CompileContext<'a> {
/// Column name -> index (case-insensitive)
columns: StringMap<u16>,
/// Qualified column name -> (index, is_row2)
/// For row1 columns: index is the direct row1 index
/// For row2 columns: index is the row2 index (not offset)
qualified_columns: StringMap<StringMap<ColumnSource>>,
/// Second row columns (for joins)
columns2: Option<StringMap<u16>>,
/// Tables that belong to row2 (for tracking which tables are from second row)
row2_tables: FxHashSet<String>,
/// Outer query columns (for correlated subqueries)
outer_columns: Option<FxHashMap<CompactArc<str>, u16>>,
/// Function registry
functions: &'a FunctionRegistry,
/// Expression alias mapping (for HAVING with GROUP BY expressions)
expression_aliases: StringMap<u16>,
/// Column aliases
column_aliases: StringMap<String>,
}
impl<'a> CompileContext<'a> {
/// Create a new compilation context
pub fn new(columns: &[String], functions: &'a FunctionRegistry) -> Self {
let mut col_map = StringMap::new();
let mut qualified_map: StringMap<StringMap<ColumnSource>> = StringMap::new();
for (i, col) in columns.iter().enumerate() {
let lower = col.to_lowercase();
col_map.insert(lower.clone(), i as u16);
// Handle qualified names (table.column)
if let Some(dot_idx) = col.rfind('.') {
let table = col[..dot_idx].to_lowercase();
let column = col[dot_idx + 1..].to_lowercase();
qualified_map
.entry(table)
.or_default()
.insert(column.clone(), ColumnSource::Row1(i as u16));
// Also map unqualified column name for lookup without table prefix
// Don't overwrite if already exists (first occurrence wins)
col_map.entry(column).or_insert(i as u16);
}
}
Self {
columns: col_map,
qualified_columns: qualified_map,
columns2: None,
row2_tables: FxHashSet::default(),
outer_columns: None,
functions,
expression_aliases: StringMap::new(),
column_aliases: StringMap::new(),
}
}
/// Create context using global function registry
pub fn with_global_registry(columns: &[String]) -> Self {
Self::new(columns, global_registry())
}
/// Add second row columns (for join compilation)
pub fn with_second_row(mut self, columns2: &[String]) -> Self {
let mut col_map = StringMap::new();
for (i, col) in columns2.iter().enumerate() {
let lower = col.to_lowercase();
col_map.insert(lower.clone(), i as u16);
// Handle qualified names (table.column)
if let Some(dot_idx) = col.rfind('.') {
let table = col[..dot_idx].to_lowercase();
let column = col[dot_idx + 1..].to_lowercase();
// Track this table as belonging to row2
self.row2_tables.insert(table.clone());
// Add qualified name with Row2 source (index is local to row2)
self.qualified_columns
.entry(table)
.or_default()
.insert(column.clone(), ColumnSource::Row2(i as u16));
// Also map unqualified column name (don't overwrite if exists)
col_map.entry(column).or_insert(i as u16);
}
}
self.columns2 = Some(col_map);
self
}
/// Add outer columns for correlated subqueries
pub fn with_outer_columns(mut self, outer_cols: &[String]) -> Self {
let mut map = FxHashMap::default();
for (i, col) in outer_cols.iter().enumerate() {
map.insert(CompactArc::from(col.to_lowercase().as_str()), i as u16);
}
self.outer_columns = Some(map);
self
}
/// Add expression aliases (for HAVING clause)
pub fn with_expression_aliases(mut self, aliases: StringMap<u16>) -> Self {
self.expression_aliases = aliases;
self
}
/// Add column aliases
pub fn with_column_aliases(mut self, aliases: StringMap<String>) -> Self {
self.column_aliases = aliases;
self
}
/// Resolve a column name to its source (Row1 or Row2)
fn resolve_column(&self, name: &str) -> Option<ColumnSource> {
let lower = name.to_lowercase();
// Check column aliases first
if let Some(original) = self.column_aliases.get(&lower) {
if let Some(&idx) = self.columns.get(original) {
return Some(ColumnSource::Row1(idx));
}
}
// Direct lookup in primary columns (Row1)
if let Some(&idx) = self.columns.get(&lower) {
return Some(ColumnSource::Row1(idx));
}
// Try second row if available (Row2)
if let Some(ref cols2) = self.columns2 {
if let Some(&idx) = cols2.get(&lower) {
return Some(ColumnSource::Row2(idx));
}
}
None
}
/// Resolve a qualified column name (table.column)
fn resolve_qualified(&self, table: &str, column: &str) -> Option<ColumnSource> {
let table_lower = table.to_lowercase();
let column_lower = column.to_lowercase();
if let Some(table_cols) = self.qualified_columns.get(&table_lower) {
if let Some(&source) = table_cols.get(&column_lower) {
return Some(source);
}
}
// Check if the FULLY QUALIFIED name (table.column) exists in outer_columns.
// This distinguishes between `t.id` (outer reference) and `t2.id` (current row).
// Only if the qualified name is in outer context should we skip the fallback.
if let Some(ref outer_cols) = self.outer_columns {
let qualified_name = format!("{}.{}", table_lower, column_lower);
if outer_cols.contains_key(qualified_name.as_str()) {
// Qualified name exists in outer context - don't fall back
return None;
}
}
// Qualified name not in outer context - safe to fall back to unqualified lookup
self.resolve_column(&column_lower)
}
/// Resolve outer column (for correlated subqueries)
fn resolve_outer_column(&self, name: &str) -> Option<CompactArc<str>> {
let lower = name.to_lowercase();
self.outer_columns.as_ref().and_then(|cols| {
if cols.contains_key(lower.as_str()) {
Some(CompactArc::from(lower.as_str()))
} else {
None
}
})
}
/// Check if an expression matches an expression alias
fn check_expression_alias(&self, expr: &Expression) -> Option<u16> {
if self.expression_aliases.is_empty() {
return None;
}
let expr_str = expression_to_string(expr).to_lowercase();
self.expression_aliases.get(&expr_str).copied()
}
}
/// Expression compiler
pub struct ExprCompiler<'a> {
ctx: &'a CompileContext<'a>,
/// Guard flag to prevent recursive constant folding
folding: Cell<bool>,
}
impl<'a> ExprCompiler<'a> {
pub fn new(ctx: &'a CompileContext<'a>) -> Self {
Self {
ctx,
folding: Cell::new(false),
}
}
/// Compile an expression into a Program
pub fn compile(&self, expr: &Expression) -> Result<Program, CompileError> {
let mut builder = ProgramBuilder::new();
self.compile_expr(expr, &mut builder)?;
builder.emit(Op::Return);
Ok(builder.build())
}
/// Compile an expression for use as a boolean filter
pub fn compile_filter(&self, expr: &Expression) -> Result<Program, CompileError> {
// For simple filter expressions, we can optimize
let mut builder = ProgramBuilder::new();
self.compile_expr(expr, &mut builder)?;
builder.emit(Op::Return);
Ok(builder.build())
}
/// Flatten chained concatenation operators into a list of operands.
/// For `a || b || c || d`, returns [a, b, c, d] in order.
fn flatten_concat_chain_infix<'b>(
infix: &'b InfixExpression,
operands: &mut Vec<&'b Expression>,
) {
// Flatten left side
if let Expression::Infix(left_infix) = &*infix.left {
if left_infix.op_type == InfixOperator::Concat {
Self::flatten_concat_chain_infix(left_infix, operands);
} else {
operands.push(&infix.left);
}
} else {
operands.push(&infix.left);
}
// Flatten right side
if let Expression::Infix(right_infix) = &*infix.right {
if right_infix.op_type == InfixOperator::Concat {
Self::flatten_concat_chain_infix(right_infix, operands);
} else {
operands.push(&infix.right);
}
} else {
operands.push(&infix.right);
}
}
/// Try to fold a column-free expression into a constant at compile time.
/// Compiles the expression into a temporary program, executes it with an empty
/// row context, and returns the result if successful.
fn try_fold_constant(&self, expr: &Expression) -> Option<Value> {
use std::cell::RefCell;
thread_local! {
static FOLD_VM: RefCell<ExprVM> = RefCell::new(ExprVM::new());
static FOLD_ROW: Row = Row::new();
}
self.folding.set(true);
let empty_cols: &[String] = &[];
let ctx = CompileContext::new(empty_cols, self.ctx.functions);
let compiler = ExprCompiler::new(&ctx);
compiler.folding.set(true);
let mut builder = ProgramBuilder::new();
let ok = compiler.compile_expr(expr, &mut builder);
self.folding.set(false);
ok.ok()?;
builder.emit(Op::Return);
let program = builder.build_unoptimized();
FOLD_ROW.with(|empty_row| {
let exec_ctx = ExecuteContext::new(empty_row);
FOLD_VM.with(|vm_cell| {
let mut vm = vm_cell.borrow_mut();
vm.execute(&program, &exec_ctx).ok()
})
})
}
/// Compile an expression, emitting ops to the builder
fn compile_expr(
&self,
expr: &Expression,
builder: &mut ProgramBuilder,
) -> Result<(), CompileError> {
// Check if this expression matches an expression alias (for HAVING)
if let Some(idx) = self.ctx.check_expression_alias(expr) {
builder.emit(Op::LoadAggregateResult(idx));
return Ok(());
}
// Constant folding: if not already folding and expression is column-free
// and non-trivial, evaluate once at compile time and emit as LoadConst.
// This optimizes deterministic expressions like ABS(-5) + 1 or UPPER('text').
// Non-deterministic functions (NOW, RANDOM, etc.) are excluded by is_foldable_expr
// and handled separately by pushdown's try_eval_constant_expr at query time.
if !self.folding.get() && is_foldable_expr(expr) {
if let Some(value) = self.try_fold_constant(expr) {
builder.emit(Op::LoadConst(value));
return Ok(());
}
}
match expr {
// === LITERALS ===
Expression::IntegerLiteral(lit) => {
builder.emit(Op::LoadConst(Value::Integer(lit.value)));
}
Expression::FloatLiteral(lit) => {
builder.emit(Op::LoadConst(Value::Float(lit.value)));
}
Expression::StringLiteral(lit) => {
// Handle type hints (DATE, TIMESTAMP, etc.)
let value = if let Some(ref hint) = lit.type_hint {
match hint.to_uppercase().as_str() {
"TIMESTAMP" | "DATETIME" => crate::core::value::parse_timestamp(&lit.value)
.map(Value::Timestamp)
.unwrap_or_else(|_| Value::Text(lit.value.clone())),
"DATE" => crate::core::value::parse_timestamp(&lit.value)
.map(Value::Timestamp)
.unwrap_or_else(|_| Value::Text(lit.value.clone())),
_ => Value::Text(lit.value.clone()),
}
} else {
Value::Text(lit.value.clone())
};
builder.emit(Op::LoadConst(value));
}
Expression::BooleanLiteral(lit) => {
builder.emit(Op::LoadConst(Value::Boolean(lit.value)));
}
Expression::NullLiteral(_) => {
builder.emit(Op::LoadNull(DataType::Null));
}
// === IDENTIFIERS ===
Expression::Identifier(id) => {
// CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP are now parsed as
// FunctionCall by the parser, so they no longer reach this path.
match id.value_lower.as_str() {
"true" => {
builder.emit(Op::LoadConst(Value::Boolean(true)));
return Ok(());
}
"false" => {
builder.emit(Op::LoadConst(Value::Boolean(false)));
return Ok(());
}
_ => {}
}
// Try to resolve as column
// First, check if the identifier contains a dot (qualified name like "table.column")
if let Some(dot_idx) = id.value_lower.rfind('.') {
// Treat as qualified identifier
let table = &id.value_lower[..dot_idx];
let column = &id.value_lower[dot_idx + 1..];
if let Some(source) = self.ctx.resolve_qualified(table, column) {
match source {
ColumnSource::Row1(idx) => builder.emit(Op::LoadColumn(idx)),
ColumnSource::Row2(idx) => builder.emit(Op::LoadColumn2(idx)),
}
} else if let Some(name) = self.ctx.resolve_outer_column(column) {
builder.emit(Op::LoadOuterColumn(name));
} else if id.token.quoted {
// Double-quoted identifier falls back to string literal
builder.emit(Op::LoadConst(Value::text(id.value.as_str())));
} else {
return Err(CompileError::ColumnNotFound(id.value.to_string()));
}
} else if let Some(source) = self.ctx.resolve_column(&id.value_lower) {
match source {
ColumnSource::Row1(idx) => builder.emit(Op::LoadColumn(idx)),
ColumnSource::Row2(idx) => builder.emit(Op::LoadColumn2(idx)),
}
} else if let Some(name) = self.ctx.resolve_outer_column(&id.value_lower) {
builder.emit(Op::LoadOuterColumn(name));
} else if id.token.quoted {
// Double-quoted identifier falls back to string literal
builder.emit(Op::LoadConst(Value::text(id.value.as_str())));
} else {
return Err(CompileError::ColumnNotFound(id.value.to_string()));
}
}
Expression::QualifiedIdentifier(qid) => {
let table = &qid.qualifier.value_lower;
let column = &qid.name.value_lower;
if let Some(source) = self.ctx.resolve_qualified(table, column) {
match source {
ColumnSource::Row1(idx) => builder.emit(Op::LoadColumn(idx)),
ColumnSource::Row2(idx) => builder.emit(Op::LoadColumn2(idx)),
}
} else {
// For qualified identifiers (e.g., c.id), prefer the qualified
// name in outer_columns over unqualified. This prevents incorrect
// resolution when the unqualified key ("id") is overwritten in
// outer_row by an inner row's column with the same name.
let qualified_name =
format!("{}.{}", table.to_lowercase(), column.to_lowercase());
if let Some(name) = self
.ctx
.resolve_outer_column(&qualified_name)
.or_else(|| self.ctx.resolve_outer_column(column))
{
builder.emit(Op::LoadOuterColumn(name));
} else {
return Err(CompileError::ColumnNotFound(format!(
"{}.{}",
table, column
)));
}
}
}
// === PARAMETERS ===
Expression::Parameter(param) => {
if param.name.starts_with(':') {
let name = ¶m.name[1..];
builder.emit(Op::LoadNamedParam(CompactArc::from(name)));
} else if param.index > 0 {
builder.emit(Op::LoadParam((param.index - 1) as u16));
} else {
return Err(CompileError::InvalidExpression(
"Invalid parameter".to_string(),
));
}
}
// === INFIX EXPRESSIONS ===
Expression::Infix(infix) => {
self.compile_infix(infix, builder)?;
}
// === PREFIX EXPRESSIONS ===
Expression::Prefix(prefix) => {
self.compile_prefix(prefix, builder)?;
}
// === IN EXPRESSION ===
Expression::In(in_expr) => {
self.compile_in(in_expr, builder)?;
}
Expression::InHashSet(in_hash) => {
self.compile_expr(&in_hash.column, builder)?;
let has_null = in_hash.values.iter().any(|v| v.is_null());
if in_hash.not {
builder.emit(Op::NotInSet(in_hash.values.clone(), has_null));
} else {
builder.emit(Op::InSet(in_hash.values.clone(), has_null));
}
}
// === BETWEEN EXPRESSION ===
Expression::Between(between) => {
self.compile_expr(&between.expr, builder)?;
self.compile_expr(&between.lower, builder)?;
self.compile_expr(&between.upper, builder)?;
if between.not {
builder.emit(Op::NotBetween);
} else {
builder.emit(Op::Between);
}
}
// === LIKE EXPRESSION ===
Expression::Like(like) => {
self.compile_like(like, builder)?;
}
// === CASE EXPRESSION ===
Expression::Case(case) => {
self.compile_case(case, builder)?;
}
// === CAST EXPRESSION ===
Expression::Cast(cast) => {
self.compile_expr(&cast.expr, builder)?;
// DATE type requires special handling - truncate time to midnight
if cast.type_name.eq_ignore_ascii_case("DATE") {
builder.emit(Op::TruncateToDate);
} else {
let dt = string_to_datatype(&cast.type_name);
builder.emit(Op::Cast(dt));
}
}
// === FUNCTION CALL ===
Expression::FunctionCall(func) => {
self.compile_function(func, builder)?;
}
// === ALIASED EXPRESSION ===
Expression::Aliased(aliased) => {
self.compile_expr(&aliased.expression, builder)?;
}
// === DISTINCT ===
Expression::Distinct(distinct) => {
self.compile_expr(&distinct.expr, builder)?;
}
// === LIST ===
Expression::List(list) => {
if list.elements.is_empty() {
builder.emit(Op::LoadNull(DataType::Null));
} else {
// Compile first item (for single-value IN)
self.compile_expr(&list.elements[0], builder)?;
}
}
Expression::ExpressionList(list) => {
if list.expressions.is_empty() {
builder.emit(Op::LoadNull(DataType::Null));
} else {
self.compile_expr(&list.expressions[0], builder)?;
}
}
// === INTERVAL ===
Expression::IntervalLiteral(interval) => {
let s = format!("{} {}", interval.quantity, interval.unit);
builder.emit(Op::LoadConst(Value::Text(SmartString::from_string(s))));
}
// === SUBQUERIES ===
Expression::ScalarSubquery(_) => {
// Subqueries are handled via the subquery executor
// For now, emit a placeholder that will be resolved at runtime
builder.emit(Op::ExecScalarSubquery(0));
}
Expression::Exists(exists) => {
let _ = exists; // Subquery index would be resolved during planning
builder.emit(Op::ExecExists(0));
}
Expression::AllAny(all_any) => {
self.compile_expr(&all_any.left, builder)?;
let compare_op = match all_any.operator.as_str() {
"=" => CompareOp::Eq,
"!=" | "<>" => CompareOp::Ne,
"<" => CompareOp::Lt,
"<=" => CompareOp::Le,
">" => CompareOp::Gt,
">=" => CompareOp::Ge,
_ => CompareOp::Eq,
};
if matches!(all_any.all_any_type, AllAnyType::All) {
builder.emit(Op::ExecAll(0, compare_op));
} else {
builder.emit(Op::ExecAny(0, compare_op));
}
}
// === WINDOW (not supported in VM, requires special handling) ===
Expression::Window(_) => {
return Err(CompileError::UnsupportedExpression(
"Window functions require special execution context".to_string(),
));
}
// === TABLE SOURCES (not expressions) ===
Expression::TableSource(_)
| Expression::JoinSource(_)
| Expression::SubquerySource(_)
| Expression::ValuesSource(_)
| Expression::CteReference(_)
| Expression::FunctionTableSource(_)
| Expression::Star(_)
| Expression::QualifiedStar(_)
| Expression::Default(_) => {
return Err(CompileError::InvalidExpression(
"unexpected table reference or '*' in expression context".to_string(),
));
}
}
Ok(())
}
/// Compile an infix expression
fn compile_infix(
&self,
infix: &InfixExpression,
builder: &mut ProgramBuilder,
) -> Result<(), CompileError> {
match infix.op_type {
// Short-circuit AND
InfixOperator::And => {
// Compile left side
self.compile_expr(&infix.left, builder)?;
// Emit AND with placeholder jump target
let and_pos = builder.position();
builder.emit(Op::And(0)); // Placeholder
// Compile right side
self.compile_expr(&infix.right, builder)?;
// Emit finalize
builder.emit(Op::AndFinalize);
// Patch jump to skip right side if left is false
let end_pos = builder.position();
builder.patch_jump(and_pos as usize, end_pos);
}
// Short-circuit OR
InfixOperator::Or => {
// Compile left side
self.compile_expr(&infix.left, builder)?;
// Emit OR with placeholder jump target
let or_pos = builder.position();
builder.emit(Op::Or(0)); // Placeholder
// Compile right side
self.compile_expr(&infix.right, builder)?;
// Emit finalize
builder.emit(Op::OrFinalize);
// Patch jump to skip right side if left is true
let end_pos = builder.position();
builder.patch_jump(or_pos as usize, end_pos);
}
// Comparison operators
InfixOperator::Equal => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Eq);
}
InfixOperator::NotEqual => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Ne);
}
InfixOperator::LessThan => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Lt);
}
InfixOperator::LessEqual => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Le);
}
InfixOperator::GreaterThan => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Gt);
}
InfixOperator::GreaterEqual => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Ge);
}
// Arithmetic operators
InfixOperator::Add => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Add);
}
InfixOperator::Subtract => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Sub);
}
InfixOperator::Multiply => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Mul);
}
InfixOperator::Divide => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Div);
}
InfixOperator::Modulo => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Mod);
}
// String concatenation - optimize chained || into single ConcatN
InfixOperator::Concat => {
// Flatten chained concatenations: a || b || c -> ConcatN(3)
let mut operands = Vec::new();
Self::flatten_concat_chain_infix(infix, &mut operands);
if operands.len() > 2 && operands.len() <= 255 {
// Compile all operands in order
for operand in &operands {
self.compile_expr(operand, builder)?;
}
builder.emit(Op::ConcatN(operands.len() as u8));
} else {
// Fallback to binary concat
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Concat);
}
}
// Bitwise operators
InfixOperator::BitwiseAnd => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::BitAnd);
}
InfixOperator::BitwiseOr => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::BitOr);
}
InfixOperator::BitwiseXor => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::BitXor);
}
InfixOperator::LeftShift => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Shl);
}
InfixOperator::RightShift => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Shr);
}
// XOR
InfixOperator::Xor => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::Xor);
}
// IS / IS NOT
InfixOperator::Is => {
self.compile_expr(&infix.left, builder)?;
// Check if right side is NULL, TRUE, or FALSE
match &*infix.right {
Expression::NullLiteral(_) => {
builder.emit(Op::IsNull);
}
Expression::BooleanLiteral(lit) if lit.value => {
builder.emit(Op::IsTrue);
}
Expression::BooleanLiteral(lit) if !lit.value => {
builder.emit(Op::IsFalse);
}
Expression::Identifier(id) if id.value_lower == "true" => {
builder.emit(Op::IsTrue);
}
Expression::Identifier(id) if id.value_lower == "false" => {
builder.emit(Op::IsFalse);
}
_ => {
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::IsNotDistinctFrom);
}
}
}
InfixOperator::IsNot => {
self.compile_expr(&infix.left, builder)?;
match &*infix.right {
Expression::NullLiteral(_) => {
builder.emit(Op::IsNotNull);
}
Expression::BooleanLiteral(lit) if lit.value => {
builder.emit(Op::IsNotTrue);
}
Expression::BooleanLiteral(lit) if !lit.value => {
builder.emit(Op::IsNotFalse);
}
Expression::Identifier(id) if id.value_lower == "true" => {
builder.emit(Op::IsNotTrue);
}
Expression::Identifier(id) if id.value_lower == "false" => {
builder.emit(Op::IsNotFalse);
}
_ => {
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::IsDistinctFrom);
}
}
}
InfixOperator::IsDistinctFrom => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::IsDistinctFrom);
}
InfixOperator::IsNotDistinctFrom => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::IsNotDistinctFrom);
}
// Pattern matching via infix
InfixOperator::Like => {
self.compile_expr(&infix.left, builder)?;
let pattern_str = Self::extract_pattern_string(&infix.right);
if let Some(s) = pattern_str {
let pattern = CompiledPattern::compile(&s, false);
builder.emit(Op::Like(Arc::new(pattern), false));
} else {
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::LikeDynamic(false));
}
}
InfixOperator::ILike => {
self.compile_expr(&infix.left, builder)?;
let pattern_str = Self::extract_pattern_string(&infix.right);
if let Some(s) = pattern_str {
let pattern = CompiledPattern::compile(&s, true);
builder.emit(Op::Like(Arc::new(pattern), true));
} else {
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::LikeDynamic(true));
}
}
InfixOperator::NotLike => {
self.compile_expr(&infix.left, builder)?;
let pattern_str = Self::extract_pattern_string(&infix.right);
if let Some(s) = pattern_str {
let pattern = CompiledPattern::compile(&s, false);
builder.emit(Op::Like(Arc::new(pattern), false));
builder.emit(Op::Not);
} else {
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::LikeDynamic(false));
builder.emit(Op::Not);
}
}
InfixOperator::NotILike => {
self.compile_expr(&infix.left, builder)?;
let pattern_str = Self::extract_pattern_string(&infix.right);
if let Some(s) = pattern_str {
let pattern = CompiledPattern::compile(&s, true);
builder.emit(Op::Like(Arc::new(pattern), true));
builder.emit(Op::Not);
} else {
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::LikeDynamic(true));
builder.emit(Op::Not);
}
}
InfixOperator::Glob | InfixOperator::NotGlob => {
self.compile_expr(&infix.left, builder)?;
let pattern_str = Self::extract_pattern_string(&infix.right);
if let Some(s) = pattern_str {
let pattern = CompiledPattern::compile_glob(&s);
builder.emit(Op::Glob(Arc::new(pattern)));
} else {
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::GlobDynamic);
}
if matches!(infix.op_type, InfixOperator::NotGlob) {
builder.emit(Op::Not);
}
}
InfixOperator::Regexp | InfixOperator::NotRegexp => {
self.compile_expr(&infix.left, builder)?;
let pattern_str = Self::extract_pattern_string(&infix.right);
if let Some(s) = pattern_str {
let regex = regex::Regex::new(&s).map_err(|e| {
CompileError::InvalidExpression(format!("Invalid regex: {}", e))
})?;
builder.emit(Op::Regexp(Arc::new(regex)));
} else {
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::RegexpDynamic);
}
if matches!(infix.op_type, InfixOperator::NotRegexp) {
builder.emit(Op::Not);
}
}
// JSON operators
InfixOperator::JsonAccess => {
// json -> key (returns JSON)
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::JsonAccess);
}
InfixOperator::JsonAccessText => {
// json ->> key (returns TEXT)
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::JsonAccessText);
}
InfixOperator::Index => {
// Array/JSON index access - treat as JsonAccess
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::JsonAccess);
}
// Vector distance operator (<=>)
InfixOperator::VectorDistance => {
self.compile_expr(&infix.left, builder)?;
self.compile_expr(&infix.right, builder)?;
builder.emit(Op::VectorDistanceL2);
}
// Other/unknown operators
InfixOperator::Other => {
return Err(CompileError::UnsupportedExpression(format!(
"Unknown infix operator: {}",
infix.operator
)));
}
}
Ok(())
}
/// Compile a prefix expression
fn compile_prefix(
&self,
prefix: &PrefixExpression,
builder: &mut ProgramBuilder,
) -> Result<(), CompileError> {
self.compile_expr(&prefix.right, builder)?;
match prefix.operator.to_uppercase().as_str() {
"NOT" => builder.emit(Op::Not),
"-" => builder.emit(Op::Neg),
"+" => {} // Unary plus is a no-op
"~" => builder.emit(Op::BitNot),
_ => {
return Err(CompileError::InvalidExpression(format!(
"Unknown prefix operator: {}",
prefix.operator
)));
}
}
Ok(())
}
/// Compile an IN expression
fn compile_in(
&self,
in_expr: &InExpression,
builder: &mut ProgramBuilder,
) -> Result<(), CompileError> {
// Check if this is a multi-column IN: (a, b) IN ((1, 2), (3, 4))
let left_columns: Vec<&Expression> = match &*in_expr.left {
Expression::List(list) if list.elements.len() > 1 => list.elements.iter().collect(),
Expression::ExpressionList(list) if list.expressions.len() > 1 => {
list.expressions.iter().collect()
}
_ => Vec::new(),
};
if !left_columns.is_empty() {
// Multi-column IN expression
return self.compile_multi_column_in(in_expr, &left_columns, builder);
}
// Single-value IN expression
// Build the set of values at compile time if possible
let mut values = ValueSet::default();
let mut has_null = false;
let mut all_constant = true;
// Check if right side is a list of constants
match &*in_expr.right {
Expression::List(list) => {
for item in &list.elements {
if let Some(value) = try_eval_constant(item) {
if value.is_null() {
has_null = true;
} else {
values.insert(value);
}
} else {
all_constant = false;
break;
}
}
}
Expression::ExpressionList(list) => {
for item in &list.expressions {
if let Some(value) = try_eval_constant(item) {
if value.is_null() {
has_null = true;
} else {
values.insert(value);
}
} else {
all_constant = false;
break;
}
}
}
_ => {
all_constant = false;
}
}
if all_constant {
if values.is_empty() && !has_null {
// Empty IN list with no NULLs:
// x IN () -> FALSE (nothing matches)
// x NOT IN () -> TRUE (x is not in empty set)
if in_expr.not {
builder.emit(Op::LoadConst(Value::Boolean(true)));
} else {
builder.emit(Op::LoadConst(Value::Boolean(false)));
}
} else {
// Optimized: use pre-built HashSet
self.compile_expr(&in_expr.left, builder)?;
if in_expr.not {
builder.emit(Op::NotInSet(CompactArc::new(values), has_null));
} else {
builder.emit(Op::InSet(CompactArc::new(values), has_null));
}
}
} else {
// Fallback: evaluate each item (less efficient)
// For now, return error - would need runtime set building
return Err(CompileError::UnsupportedExpression(
"Dynamic IN list not yet supported in VM".to_string(),
));
}
Ok(())
}
/// Compile multi-column IN expression: (a, b) IN ((1, 2), (3, 4))
fn compile_multi_column_in(
&self,
in_expr: &InExpression,
left_columns: &[&Expression],
builder: &mut ProgramBuilder,
) -> Result<(), CompileError> {
let tuple_size = left_columns.len();
// Extract tuples from right side
let mut tuple_values: Vec<Vec<Value>> = Vec::new();
let mut all_constant = true;
match &*in_expr.right {
Expression::List(list) => {
for item in &list.elements {
if let Some(tuple) = self.extract_tuple_values(item, tuple_size) {
tuple_values.push(tuple);
} else {
all_constant = false;
break;
}
}
}
Expression::ExpressionList(list) => {
for item in &list.expressions {
if let Some(tuple) = self.extract_tuple_values(item, tuple_size) {
tuple_values.push(tuple);
} else {
all_constant = false;
break;
}
}
}
_ => {
all_constant = false;
}
}
if !all_constant || tuple_values.is_empty() {
return Err(CompileError::UnsupportedExpression(
"Dynamic multi-column IN not yet supported in VM".to_string(),
));
}
// Compile each column expression to push onto stack
for col in left_columns {
self.compile_expr(col, builder)?;
}
// Emit InTupleSet operation
builder.emit(Op::InTupleSet {
tuple_size: tuple_size as u8,
values: Arc::new(tuple_values),
negated: in_expr.not,
});
Ok(())
}
/// Extract tuple values from an expression (e.g., (1, 2) -> [1, 2])
fn extract_tuple_values(&self, expr: &Expression, expected_size: usize) -> Option<Vec<Value>> {
let elements: Vec<&Expression> = match expr {
Expression::List(list) => list.elements.iter().collect(),
Expression::ExpressionList(list) => list.expressions.iter().collect(),
_ => return None,
};
if elements.len() != expected_size {
return None;
}
let mut values = Vec::with_capacity(expected_size);
for element in elements {
if let Some(value) = try_eval_constant(element) {
values.push(value);
} else {
return None;
}
}
Some(values)
}
/// Compile a LIKE expression
fn compile_like(
&self,
like: &LikeExpression,
builder: &mut ProgramBuilder,
) -> Result<(), CompileError> {
self.compile_expr(&like.left, builder)?;
// Determine case sensitivity and negation from operator
let op_upper = like.operator.to_uppercase();
let case_insensitive = op_upper.contains("ILIKE");
let negated = op_upper.contains("NOT");
let is_glob = op_upper.contains("GLOB");
let is_regexp = op_upper.contains("REGEXP") || op_upper.contains("RLIKE");
// Extract escape character if present
let escape_char: Option<char> = if let Some(ref escape_expr) = like.escape {
if let Expression::StringLiteral(lit) = &**escape_expr {
lit.value.chars().next()
} else {
None
}
} else {
None
};
// Try to compile pattern at compile time
let pattern_str = Self::extract_pattern_string(&like.pattern);
if let Some(s) = pattern_str {
if is_regexp {
let regex = regex::Regex::new(&s).map_err(|e| {
CompileError::InvalidExpression(format!("Invalid regex: {}", e))
})?;
builder.emit(Op::Regexp(Arc::new(regex)));
} else if is_glob {
// Use compile_glob for GLOB patterns (uses * and ? wildcards)
let pattern = CompiledPattern::compile_glob(&s);
builder.emit(Op::Glob(Arc::new(pattern)));
} else if let Some(esc) = escape_char {
// LIKE with ESCAPE - pre-process pattern to handle escape character
let processed_pattern = self.process_like_escape(&s, esc);
let pattern = CompiledPattern::compile(&processed_pattern, case_insensitive);
builder.emit(Op::LikeEscape(Arc::new(pattern), case_insensitive, esc));
} else {
let pattern = CompiledPattern::compile(&s, case_insensitive);
builder.emit(Op::Like(Arc::new(pattern), case_insensitive));
}
if negated {
builder.emit(Op::Not);
}
} else {
// Dynamic pattern (e.g. parameter $1) — compile the pattern expression
// onto the stack and use the dynamic op
self.compile_expr(&like.pattern, builder)?;
if is_regexp {
builder.emit(Op::RegexpDynamic);
} else if is_glob {
builder.emit(Op::GlobDynamic);
} else if let Some(esc) = escape_char {
builder.emit(Op::LikeDynamicEscape(case_insensitive, esc));
} else {
builder.emit(Op::LikeDynamic(case_insensitive));
}
if negated {
builder.emit(Op::Not);
}
}
Ok(())
}
/// Extract a static pattern string from a StringLiteral or a double-quoted Identifier.
/// Returns None for dynamic expressions (column references, function calls, etc.).
fn extract_pattern_string(expr: &Expression) -> Option<SmartString> {
match expr {
Expression::StringLiteral(lit) => Some(lit.value.clone()),
Expression::Identifier(id) if id.token.quoted => Some(id.value.clone()),
_ => None,
}
}
/// Process LIKE pattern with escape character
/// Converts escaped wildcards to special markers and then to literal characters
fn process_like_escape(&self, pattern: &str, escape: char) -> String {
let mut result = String::with_capacity(pattern.len());
let mut chars = pattern.chars().peekable();
while let Some(c) = chars.next() {
if c == escape {
// Next character should be treated literally
if let Some(&next) = chars.peek() {
if next == '%' || next == '_' || next == escape {
// Escape the wildcard - use regex escape sequence
result.push('\\');
result.push(chars.next().unwrap());
} else {
// Not escaping a special character, keep the escape char
result.push(c);
}
} else {
// Escape at end of pattern
result.push(c);
}
} else {
result.push(c);
}
}
result
}
/// Compile a CASE expression
fn compile_case(
&self,
case: &CaseExpression,
builder: &mut ProgramBuilder,
) -> Result<(), CompileError> {
builder.emit(Op::CaseStart);
let is_simple = case.value.is_some();
let mut end_jumps = Vec::new();
// For simple CASE, compile the operand once
if let Some(ref operand) = case.value {
self.compile_expr(operand, builder)?;
}
for when_clause in &case.when_clauses {
if is_simple {
// Simple CASE: compare operand with WHEN value
builder.emit(Op::Dup); // Keep operand on stack
self.compile_expr(&when_clause.condition, builder)?;
builder.emit(Op::CaseCompare);
} else {
// Searched CASE: evaluate condition
self.compile_expr(&when_clause.condition, builder)?;
}
// Jump to next branch if condition is false
let when_pos = builder.position();
builder.emit(Op::CaseWhen(0)); // Placeholder
// Compile THEN result
if is_simple {
builder.emit(Op::Pop); // Remove operand copy
}
self.compile_expr(&when_clause.then_result, builder)?;
// Jump to end after THEN
let then_pos = builder.position();
builder.emit(Op::CaseThen(0)); // Placeholder
end_jumps.push(then_pos);
// Patch WHEN jump to here
let next_pos = builder.position();
builder.patch_jump(when_pos as usize, next_pos);
}
// Compile ELSE
if is_simple {
builder.emit(Op::Pop); // Remove operand
}
if let Some(ref else_value) = case.else_value {
builder.emit(Op::CaseElse);
self.compile_expr(else_value, builder)?;
} else {
builder.emit(Op::LoadNull(DataType::Null));
}
// Patch all THEN jumps to end
let end_pos = builder.position();
builder.emit(Op::CaseEnd);
for pos in end_jumps {
builder.patch_jump(pos as usize, end_pos);
}
Ok(())
}
/// Compile a function call
fn compile_function(
&self,
func: &FunctionCall,
builder: &mut ProgramBuilder,
) -> Result<(), CompileError> {
let func_name = func.function.to_uppercase();
// Special handling for certain functions
match func_name.as_str() {
"CURRENT_TRANSACTION_ID" => {
// Context-dependent function - loads from ExecuteContext
builder.emit(Op::LoadTransactionId);
return Ok(());
}
"COALESCE" => {
// Short-circuit COALESCE: stop evaluation as soon as we find non-null
// Bytecode pattern:
// Eval(Arg1)
// JumpIfNotNull(End) // If not null, jump to end (keep value)
// Pop // Pop the null value
// Eval(Arg2)
// JumpIfNotNull(End)
// Pop
// ...
// Eval(ArgN) // Last arg: keep on stack (null or not)
// Label(End)
if func.arguments.is_empty() {
builder.emit(Op::LoadNull(DataType::Null));
return Ok(());
}
let mut jump_positions = Vec::new();
let last_idx = func.arguments.len() - 1;
for (i, arg) in func.arguments.iter().enumerate() {
self.compile_expr(arg, builder)?;
if i < last_idx {
// For all but last: jump to end if not null, else pop and continue
let jump_pos = builder.position();
builder.emit(Op::JumpIfNotNull(0)); // Placeholder, will patch
jump_positions.push(jump_pos);
builder.emit(Op::Pop); // Pop the null value
}
// Last argument: just leave on stack
}
// Patch all jumps to point to end
let end_pos = builder.position();
for pos in jump_positions {
builder.patch_jump(pos as usize, end_pos);
}
return Ok(());
}
"NULLIF" if func.arguments.len() == 2 => {
self.compile_expr(&func.arguments[0], builder)?;
self.compile_expr(&func.arguments[1], builder)?;
builder.emit(Op::NullIf);
return Ok(());
}
"GREATEST" => {
for arg in &func.arguments {
self.compile_expr(arg, builder)?;
}
builder.emit(Op::Greatest(func.arguments.len() as u8));
return Ok(());
}
"LEAST" => {
for arg in &func.arguments {
self.compile_expr(arg, builder)?;
}
builder.emit(Op::Least(func.arguments.len() as u8));
return Ok(());
}
_ => {}
}
// Get function from registry
if let Some(scalar_func) = self.ctx.functions.get_scalar(&func_name) {
// Compile arguments
for arg in &func.arguments {
self.compile_expr(arg, builder)?;
}
// Try native function pointer for single-arg functions (no dynamic dispatch)
if func.arguments.len() == 1 {
if let Some(native_fn) = scalar_func.native_fn1() {
builder.emit(Op::NativeFn1(native_fn));
return Ok(());
}
}
// Fallback to dynamic dispatch
builder.emit(Op::CallScalar {
func: scalar_func.into(),
arg_count: func.arguments.len() as u8,
});
Ok(())
} else {
// Check if it's an aggregate being referenced post-aggregation
// This would be handled via LoadAggregateResult in a real implementation
Err(CompileError::FunctionNotFound(func_name.to_string()))
}
}
}
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
/// Check if a function must NOT be constant-folded.
///
/// Looks up the function in the global registry and checks `FunctionInfo.deterministic`.
/// Functions not in the registry (CURRENT_TRANSACTION_ID, UUID, RAND — handled as
/// special compiler ops or aliases) are hardcoded here.
///
/// Also used by `query_classification.rs` to detect non-deterministic functions
/// for semantic cache bypass, and by `evaluator_bridge.rs` to reject pushdown
/// of expressions containing non-deterministic functions.
pub fn is_non_foldable_function(name: &str) -> bool {
let upper = name.to_uppercase();
// Functions handled as special compiler ops, not in the registry
match upper.as_str() {
"CURRENT_TRANSACTION_ID" | "UUID" | "RAND" => return true,
_ => {}
}
// Registry-based check: non-deterministic functions declare it via FunctionInfo
let registry = crate::functions::registry::global_registry();
!registry.is_deterministic(&upper)
}
/// Check if an expression is column-free AND non-trivial (worth folding).
/// Returns true for expressions like `NOW()`, `1 + 2`, `NOW() - INTERVAL '24 hours'`
/// that can be evaluated once at compile time instead of per-row.
/// Simple literals return false (already handled efficiently by LoadConst).
fn is_foldable_expr(expr: &Expression) -> bool {
match expr {
// Simple literals are already constants — no folding benefit
Expression::IntegerLiteral(_)
| Expression::FloatLiteral(_)
| Expression::StringLiteral(_)
| Expression::BooleanLiteral(_)
| Expression::NullLiteral(_) => false,
// INTERVAL literals alone are already LoadConst — no folding benefit
Expression::IntervalLiteral(_) => false,
// Binary operations: foldable if BOTH sides are column-free
Expression::Infix(infix) => is_column_free(&infix.left) && is_column_free(&infix.right),
// Unary operations: foldable if operand is column-free
Expression::Prefix(prefix) => is_column_free(&prefix.right),
// Function calls: foldable if ALL arguments are column-free
// This covers NOW(), CURRENT_DATE, UPPER('text'), ABS(-5), etc.
// Excludes context-dependent and non-deterministic-per-call functions
Expression::FunctionCall(func) => {
if is_non_foldable_function(&func.function) {
return false;
}
func.arguments.iter().all(is_column_free)
}
// CAST: foldable if inner expression is column-free
Expression::Cast(cast) => is_column_free(&cast.expr),
// Everything else: not foldable
_ => false,
}
}
/// Check if an expression references no columns (is entirely self-contained).
fn is_column_free(expr: &Expression) -> bool {
match expr {
// Literals are always column-free
Expression::IntegerLiteral(_)
| Expression::FloatLiteral(_)
| Expression::StringLiteral(_)
| Expression::BooleanLiteral(_)
| Expression::NullLiteral(_)
| Expression::IntervalLiteral(_) => true,
// Identifiers reference columns (not column-free)
Expression::Identifier(_) | Expression::QualifiedIdentifier { .. } => false,
// Parameters: values aren't known at compile time
Expression::Parameter(_) => false,
// Binary operations
Expression::Infix(infix) => is_column_free(&infix.left) && is_column_free(&infix.right),
// Unary operations
Expression::Prefix(prefix) => is_column_free(&prefix.right),
// Function calls (NOW(), UPPER('text'), etc.)
// Exclude context-dependent and non-deterministic-per-call functions
Expression::FunctionCall(func) => {
if is_non_foldable_function(&func.function) {
return false;
}
func.arguments.iter().all(is_column_free)
}
// CAST
Expression::Cast(cast) => is_column_free(&cast.expr),
// CASE WHEN
Expression::Case(case) => {
case.value.as_ref().is_none_or(|e| is_column_free(e))
&& case
.when_clauses
.iter()
.all(|wc| is_column_free(&wc.condition) && is_column_free(&wc.then_result))
&& case.else_value.as_ref().is_none_or(|e| is_column_free(e))
}
// Subqueries, EXISTS — not column-free
Expression::ScalarSubquery(_) | Expression::Exists(_) => false,
// Between
Expression::Between(between) => {
is_column_free(&between.expr)
&& is_column_free(&between.lower)
&& is_column_free(&between.upper)
}
// Anything else: conservatively assume it references columns
_ => false,
}
}
/// Try to evaluate a constant expression at compile time
fn try_eval_constant(expr: &Expression) -> Option<Value> {
match expr {
Expression::IntegerLiteral(lit) => Some(Value::Integer(lit.value)),
Expression::FloatLiteral(lit) => Some(Value::Float(lit.value)),
Expression::StringLiteral(lit) => Some(Value::Text(lit.value.clone())),
Expression::BooleanLiteral(lit) => Some(Value::Boolean(lit.value)),
Expression::NullLiteral(_) => Some(Value::null_unknown()),
Expression::Identifier(id) if id.token.quoted => Some(Value::Text(id.value.clone())),
_ => None,
}
}
// Note: string_to_datatype and expression_to_string are now imported from utils
#[cfg(test)]
mod tests {
use super::*;
use crate::parser::ast::IntegerLiteral;
use crate::parser::token::{Position, Token, TokenType};
fn make_token() -> Token {
Token {
token_type: TokenType::Integer,
literal: "1".into(),
position: Position {
offset: 0,
line: 1,
column: 1,
},
quoted: false,
}
}
#[test]
fn test_compile_simple_comparison() {
let columns = vec!["a".to_string(), "b".to_string()];
let ctx = CompileContext::with_global_registry(&columns);
let compiler = ExprCompiler::new(&ctx);
// a > 5
let expr = Expression::Infix(InfixExpression {
token: make_token(),
left: Box::new(Expression::Identifier(Identifier::new(
make_token(),
"a".to_string(),
))),
operator: ">".into(),
op_type: InfixOperator::GreaterThan,
right: Box::new(Expression::IntegerLiteral(IntegerLiteral {
token: make_token(),
value: 5,
})),
});
let program = compiler.compile(&expr).unwrap();
assert!(!program.is_empty());
println!("{}", program.disassemble());
}
#[test]
fn test_compile_and_expression() {
let columns = vec!["a".to_string(), "b".to_string()];
let ctx = CompileContext::with_global_registry(&columns);
let compiler = ExprCompiler::new(&ctx);
// a > 5 AND b < 10
let expr = Expression::Infix(InfixExpression {
token: make_token(),
left: Box::new(Expression::Infix(InfixExpression {
token: make_token(),
left: Box::new(Expression::Identifier(Identifier::new(
make_token(),
"a".to_string(),
))),
operator: ">".into(),
op_type: InfixOperator::GreaterThan,
right: Box::new(Expression::IntegerLiteral(IntegerLiteral {
token: make_token(),
value: 5,
})),
})),
operator: "AND".into(),
op_type: InfixOperator::And,
right: Box::new(Expression::Infix(InfixExpression {
token: make_token(),
left: Box::new(Expression::Identifier(Identifier::new(
make_token(),
"b".to_string(),
))),
operator: "<".into(),
op_type: InfixOperator::LessThan,
right: Box::new(Expression::IntegerLiteral(IntegerLiteral {
token: make_token(),
value: 10,
})),
})),
});
let program = compiler.compile(&expr).unwrap();
assert!(!program.is_empty());
println!("{}", program.disassemble());
}
}