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
//! AST → bytecode compiler.
//!
//! Register discipline follows PUC Lua: locals occupy fixed registers from
//! the frame base upward; expression temporaries are allocated above the
//! live locals and released after each statement. Call windows (callee +
//! args) are built from consecutive temporaries so the VM can splice frames.
use crate::ast::{Attrib, BinOp, Block, Expr, FuncBody, Stmt, UnOp};
use crate::bytecode::{ArithOp, CmpOp, Instr, Proto, UnaryOp, UpvalDesc};
use crate::value::{Strings, Value};
use std::collections::HashMap;
use std::fmt;
use std::rc::Rc;
#[derive(Debug, Clone)]
pub struct CompileError {
pub message: String,
pub line: u32,
}
impl fmt::Display for CompileError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "compile error at line {}: {}", self.line, self.message)
}
}
/// Compiles a parsed [`Block`] into a [`Proto`].
///
/// # Errors
///
/// Returns a [`CompileError`] if the block is not valid Lua, e.g. it assigns
/// to a `<const>` local, uses `break` outside a loop, or contains an
/// unresolved `goto`.
///
/// # Panics
///
/// Panics if the compiler's function stack is empty when the main chunk is
/// popped; this cannot happen because the main chunk is pushed before
/// compilation begins.
pub fn compile(
block: &Block,
strings: &mut Strings,
chunk_name: &str,
) -> Result<Rc<Proto>, CompileError> {
let source: Rc<str> = chunk_name.into();
let mut c = Compiler {
strings,
funcs: Vec::new(),
source,
};
let mut main = FuncState::new(format!("main chunk ({chunk_name})"), 0, true);
// The main chunk has _ENV as its sole upvalue (Lua 5.4); the host fills
// it with the globals table when instantiating the chunk.
main.upvals.push(UpvalDesc::Upval(0));
main.upval_names.push("_ENV".into());
main.upval_attribs.push(Attrib::None);
c.funcs.push(main);
c.block_scope(block)?;
c.check_pending_gotos()?;
c.emit(Instr::Return { base: 0, n: 1 });
let fs = c.funcs.pop().unwrap();
let source = c.source.clone();
Ok(Rc::new(fs.into_proto(source)))
}
/// Hashable identity of a constant for deduplication.
#[derive(PartialEq, Eq, Hash)]
enum CKey {
Int(i64),
Float(u64),
Str(crate::value::StrRef),
}
struct LocalVar {
name: Box<str>,
reg: u8,
captured: bool,
attrib: Attrib,
}
struct LoopCtx {
breaks: Vec<usize>,
/// Register floor at loop entry; `break` closes upvalues from here.
reg_floor: u8,
}
/// A `goto` whose label hasn't been seen yet. `close_pc` points at a
/// placeholder `Close` (from=255, a no-op) patched when the target's
/// register floor is known.
struct PendingGoto {
name: Box<str>,
close_pc: usize,
jump_pc: usize,
/// Active-local count at the goto, capped at each enclosing block exit.
nact: usize,
/// Set when the goto leaves a block that has a captured or to-be-closed
/// local, so its placeholder `Close` must be patched (PUC's `gt->close`).
close: bool,
line: u32,
}
/// A label visible at the current point.
struct LabelDef {
name: Box<str>,
pc: usize,
reg: u8,
/// Source line of the `::name::` definition (for repeated-label errors).
line: u32,
}
struct FuncState {
code: Vec<Instr>,
lines: Vec<u32>,
consts: Vec<Value>,
const_map: HashMap<CKey, u16>,
protos: Vec<Rc<Proto>>,
upvals: Vec<UpvalDesc>,
upval_names: Vec<Box<str>>,
/// Attribute of each upvalue, parallel to `upvals`/`upval_names`. Only
/// needed at compile time to reject writes to captured `<const>`/`<close>`
/// locals; not carried into the `Proto`.
upval_attribs: Vec<Attrib>,
/// Debug call names, parallel to `code` (see `Proto::call_names`).
call_names: Vec<Option<(&'static str, Box<str>)>>,
/// Live register extent per instruction, parallel to `code` (see
/// `Proto::reg_extent`).
reg_extent: Vec<u8>,
locals: Vec<LocalVar>,
loops: Vec<LoopCtx>,
gotos: Vec<PendingGoto>,
labels: Vec<LabelDef>,
/// Gotos below this index belong to enclosing blocks and cannot see a
/// label defined in the current statement sequence.
goto_floor: usize,
nparams: u8,
is_vararg: bool,
free_reg: u8,
max_regs: u8,
cur_line: u32,
name: String,
/// Line of the `function` keyword (0 for the main chunk).
linedefined: u32,
/// Line of the closing `end` (0 for the main chunk).
line_end: u32,
/// True once a to-be-closed local is declared in this function; proper
/// tail calls are disabled while a `__close` handler may be pending
/// (PUC's `insidetbc` rule).
has_tbc: bool,
}
impl FuncState {
fn new(name: String, nparams: u8, is_vararg: bool) -> Self {
FuncState {
code: Vec::new(),
lines: Vec::new(),
consts: Vec::new(),
const_map: HashMap::new(),
protos: Vec::new(),
upvals: Vec::new(),
upval_names: Vec::new(),
upval_attribs: Vec::new(),
call_names: Vec::new(),
reg_extent: Vec::new(),
locals: Vec::new(),
loops: Vec::new(),
gotos: Vec::new(),
labels: Vec::new(),
goto_floor: 0,
nparams,
is_vararg,
free_reg: 0,
max_regs: nparams.max(2),
cur_line: 0,
name,
linedefined: 0,
line_end: 0,
has_tbc: false,
}
}
fn into_proto(self, source: Rc<str>) -> Proto {
// The main chunk reports `lastlinedefined` 0 (PUC sets it in
// `lua_load`); real functions report the line of their closing `end`.
let lastlinedefined = if self.linedefined == 0 {
0
} else {
self.line_end
};
Proto {
code: self.code,
source,
lines: self.lines,
consts: self.consts,
protos: self.protos,
upvals: self.upvals,
upval_names: self.upval_names,
nparams: self.nparams,
is_vararg: self.is_vararg,
max_regs: self.max_regs,
reg_extent: self.reg_extent,
name: self.name,
linedefined: self.linedefined,
lastlinedefined,
call_names: self.call_names,
}
}
}
/// Resolved location of a name.
enum NameLoc {
Local(u8),
Upval(u8),
Global,
}
/// Where the current `_ENV` table can be found.
enum EnvLoc {
/// A `local _ENV` in scope (use its register directly).
Local(u8),
/// The implicit upvalue (load it into a temporary first).
Upval(u8),
}
/// An assignment target with its prefix expressions already evaluated.
enum Target {
Local(u8),
Upval(u8),
Global(u16),
Index { obj: u8, key: u8 },
Field { obj: u8, k: u16 },
}
struct Compiler<'h> {
strings: &'h mut Strings,
funcs: Vec<FuncState>,
source: Rc<str>,
}
fn enc(n: Option<usize>) -> u8 {
n.map_or(0, |c| c as u8 + 1)
}
impl Compiler<'_> {
fn fs(&mut self) -> &mut FuncState {
self.funcs.last_mut().unwrap()
}
fn err<T>(&mut self, message: impl Into<String>) -> Result<T, CompileError> {
Err(CompileError {
message: message.into(),
line: self.fs().cur_line,
})
}
fn at_line(&mut self, line: u32) {
self.fs().cur_line = line;
}
fn emit(&mut self, i: Instr) -> usize {
let fs = self.fs();
fs.code.push(i);
fs.lines.push(fs.cur_line);
fs.call_names.push(None);
// `free_reg` is the current allocation high-water: every operand the
// instruction can touch is already allocated, so this is a safe (and
// tight) live extent for the collector.
fs.reg_extent.push(fs.free_reg);
fs.code.len() - 1
}
/// Emits a placeholder jump-like instruction, to be patched later.
fn emit_jump(&mut self, i: Instr) -> usize {
self.emit(i)
}
fn here(&mut self) -> usize {
self.fs().code.len()
}
fn patch_to_here(&mut self, idx: usize) {
let target = self.here();
let off = target as i32 - (idx as i32 + 1);
match &mut self.fs().code[idx] {
Instr::Jump { off: o } | Instr::Test { off: o, .. } | Instr::ForPrep { off: o, .. } => {
*o = off;
}
other => unreachable!("patching non-jump {other:?}"),
}
}
/// Offset for a backward jump from the *next* emitted instruction to `target`.
fn back_off(&mut self, target: usize) -> i32 {
target as i32 - (self.here() as i32 + 1)
}
fn alloc_reg(&mut self) -> Result<u8, CompileError> {
let fs = self.fs();
if fs.free_reg >= 250 {
return self.err("function or expression too complex (out of registers)");
}
let r = fs.free_reg;
fs.free_reg += 1;
if fs.free_reg > fs.max_regs {
fs.max_regs = fs.free_reg;
}
Ok(r)
}
/// Allocates `n` consecutive registers, returning the first.
fn alloc_regs(&mut self, n: usize) -> Result<u8, CompileError> {
let base = self.fs().free_reg;
for _ in 0..n {
self.alloc_reg()?;
}
Ok(base)
}
fn const_idx(&mut self, key: CKey, v: Value) -> Result<u16, CompileError> {
if let Some(&i) = self.fs().const_map.get(&key) {
return Ok(i);
}
let fs = self.fs();
if fs.consts.len() >= u16::MAX as usize {
return self.err("too many constants in function");
}
let i = fs.consts.len() as u16;
fs.consts.push(v);
fs.const_map.insert(key, i);
Ok(i)
}
fn str_const(&mut self, s: &[u8]) -> Result<u16, CompileError> {
// proto constants live outside the GC heap: intern as fixed
let id = self.strings.intern_fixed(s);
self.const_idx(CKey::Str(id), Value::Str(id))
}
// ---- scopes & locals ----
fn local_top(&self) -> u8 {
self.funcs
.last()
.unwrap()
.locals
.iter()
.map(|l| l.reg + 1)
.max()
.unwrap_or(0)
}
fn declare_local(&mut self, name: Box<str>, reg: u8, attrib: Attrib) {
self.fs().locals.push(LocalVar {
name,
reg,
captured: false,
attrib,
});
}
fn enter_scope(&mut self) -> usize {
self.funcs.last().unwrap().locals.len()
}
/// Pops locals down to `floor`, emitting `Close` if any was captured,
/// and releases their registers.
fn exit_scope(&mut self, floor: usize) {
let fs = self.funcs.last_mut().unwrap();
let mut close_from: Option<u8> = None;
while fs.locals.len() > floor {
let l = fs.locals.pop().unwrap();
if l.captured || l.attrib == Attrib::Close {
close_from = Some(close_from.map_or(l.reg, |c| c.min(l.reg)));
}
}
if let Some(from) = close_from {
self.emit(Instr::Close { from });
}
let top = self.local_top();
self.fs().free_reg = top;
}
fn block_scope(&mut self, b: &Block) -> Result<(), CompileError> {
let floor = self.enter_scope();
self.stmt_seq(&b.stmts, true)?;
self.exit_scope(floor);
Ok(())
}
/// Compiles a statement sequence, handling label visibility: a label is
/// "at the end of the block" (and may be jumped to over the block's
/// locals) when only other labels follow it.
fn stmt_seq(&mut self, stmts: &[Stmt], trailing_label_last: bool) -> Result<(), CompileError> {
let nact_entry = self.funcs.last().unwrap().locals.len();
let labels_floor = self.funcs.last().unwrap().labels.len();
let gotos_floor = self.funcs.last().unwrap().gotos.len();
let outer_goto_floor = self.funcs.last().unwrap().goto_floor;
self.funcs.last_mut().unwrap().goto_floor = gotos_floor;
for (i, s) in stmts.iter().enumerate() {
if let Stmt::Label(name, line) = s {
// PUC treats a label as "at the end of the block" only when
// nothing but no-op statements (`;` and other labels) follow
// *and* the block's closing token is not `until` (a repeat's
// condition still sees the body's locals).
let rest_noop = stmts[i + 1..]
.iter()
.all(|s| matches!(s, Stmt::Label(..) | Stmt::Empty));
let last = trailing_label_last && rest_noop;
self.define_label(name, *line, last, nact_entry)?;
} else {
self.stmt(s)?;
}
}
self.funcs.last_mut().unwrap().goto_floor = outer_goto_floor;
// leaving the block: labels go out of scope; unmatched gotos float
// up with their local count capped at this block's entry level. A
// goto that leaves a block holding captured or to-be-closed locals
// must run their `Close` (PUC's `movegotosout`/`gt->close`).
let fs = self.funcs.last_mut().unwrap();
fs.labels.truncate(labels_floor);
let block_has_upval = fs.locals[nact_entry.min(fs.locals.len())..]
.iter()
.any(|l| l.captured || l.attrib == Attrib::Close);
let start = gotos_floor.min(fs.gotos.len());
for g in &mut fs.gotos[start..] {
if block_has_upval && g.nact > nact_entry {
g.close = true;
}
g.nact = g.nact.min(nact_entry);
}
Ok(())
}
fn define_label(
&mut self,
name: &str,
line: u32,
last_in_block: bool,
block_nact: usize,
) -> Result<(), CompileError> {
if let Some(old) = self
.funcs
.last()
.unwrap()
.labels
.iter()
.find(|l| &*l.name == name)
{
let old_line = old.line;
return self.err(format!("label '{name}' already defined on line {old_line}"));
}
let fs = self.funcs.last().unwrap();
let nact = if last_in_block {
block_nact
} else {
fs.locals.len()
};
let reg = fs.locals[..nact]
.iter()
.map(|l| l.reg + 1)
.max()
.unwrap_or(0);
let floor = fs.goto_floor;
let pc = self.here();
// resolve pending gotos targeting this label; only gotos opened in
// this block can see it (labels are not visible to enclosing blocks)
let mut i = floor;
while i < self.funcs.last().unwrap().gotos.len() {
let (gname, gline, gnact) = {
let g = &self.funcs.last().unwrap().gotos[i];
(g.name.clone(), g.line, g.nact)
};
if &*gname != name {
i += 1;
continue;
}
if gnact < nact {
// PUC names the first local active at the label but not at
// the goto, i.e. `actvar[goto.nactvar]`.
let var = self
.funcs
.last()
.unwrap()
.locals
.get(gnact)
.map(|l| l.name.to_string())
.unwrap_or_default();
self.fs().cur_line = line;
return self.err(format!(
"<goto {gname}> at line {gline} jumps into the scope of local '{var}'"
));
}
let g = self.funcs.last_mut().unwrap().gotos.remove(i);
if g.close || nact < g.nact {
// jumping out of local scopes: close their upvalues / TBC vars
if let Instr::Close { from } = &mut self.funcs.last_mut().unwrap().code[g.close_pc]
{
*from = reg;
}
}
let off = pc as i32 - (g.jump_pc as i32 + 1);
if let Instr::Jump { off: o } = &mut self.funcs.last_mut().unwrap().code[g.jump_pc] {
*o = off;
}
}
self.funcs.last_mut().unwrap().labels.push(LabelDef {
name: name.into(),
pc,
reg,
line,
});
Ok(())
}
fn check_pending_gotos(&mut self) -> Result<(), CompileError> {
if let Some(g) = self.funcs.last().unwrap().gotos.first() {
let (name, line) = (g.name.clone(), g.line);
self.fs().cur_line = line;
if &*name == "break" {
return self.err(format!("break outside loop at line {line}"));
}
return self.err(format!(
"no visible label '{name}' for <goto> at line {line}"
));
}
Ok(())
}
// ---- name resolution ----
fn resolve(&mut self, name: &str) -> NameLoc {
self.resolve_at(self.funcs.len() - 1, name)
}
fn resolve_at(&mut self, level: usize, name: &str) -> NameLoc {
if let Some(i) = self.funcs[level]
.locals
.iter()
.rposition(|l| &*l.name == name)
{
return NameLoc::Local(self.funcs[level].locals[i].reg);
}
if let Some(i) = self.funcs[level]
.upval_names
.iter()
.position(|n| &**n == name)
{
return NameLoc::Upval(i as u8);
}
if level == 0 {
return NameLoc::Global;
}
// resolve in the enclosing function, then capture
let (desc, attrib) = if let Some(i) = self.funcs[level - 1]
.locals
.iter()
.rposition(|l| &*l.name == name)
{
self.funcs[level - 1].locals[i].captured = true;
(
UpvalDesc::Local(self.funcs[level - 1].locals[i].reg),
self.funcs[level - 1].locals[i].attrib,
)
} else {
match self.resolve_at(level - 1, name) {
NameLoc::Local(_) => unreachable!("handled above"),
NameLoc::Upval(i) => (
UpvalDesc::Upval(i),
self.funcs[level - 1].upval_attribs[i as usize],
),
NameLoc::Global => return NameLoc::Global,
}
};
let fs = &mut self.funcs[level];
fs.upvals.push(desc);
fs.upval_names.push(name.into());
fs.upval_attribs.push(attrib);
NameLoc::Upval(fs.upvals.len() as u8 - 1)
}
// ---- statements ----
fn stmt(&mut self, s: &Stmt) -> Result<(), CompileError> {
let watermark = self.local_top();
match s {
Stmt::Empty => {}
Stmt::Label(name, line) => {
// labels are normally handled by stmt_seq (which knows
// block-end position); a stray one is not last-in-block
let nact = self.funcs.last().unwrap().locals.len();
self.define_label(name, *line, false, nact)?;
}
Stmt::Goto { label, line } => {
self.at_line(*line);
let fs = self.funcs.last().unwrap();
// backward goto: label already visible (innermost match)
if let Some(l) = fs.labels.iter().rev().find(|l| l.name == *label) {
let (pc, reg) = (l.pc, l.reg);
self.emit(Instr::Close { from: reg });
let off = self.back_off(pc);
self.emit(Instr::Jump { off });
} else {
// forward goto: placeholder Close (no-op until patched)
let close_pc = self.emit(Instr::Close { from: 255 });
let jump_pc = self.emit(Instr::Jump { off: 0 });
let nact = self.funcs.last().unwrap().locals.len();
self.funcs.last_mut().unwrap().gotos.push(PendingGoto {
name: label.clone(),
close_pc,
jump_pc,
nact,
close: false,
line: *line,
});
}
}
Stmt::Local {
names,
values,
line,
} => {
self.at_line(*line);
if names.iter().filter(|(_, a)| *a == Attrib::Close).count() > 1 {
return self.err("multiple to-be-closed variables in local list");
}
let base = self.fs().free_reg;
self.explist_to(values, names.len())?;
for (i, (name, attrib)) in names.iter().enumerate() {
self.declare_local(name.clone(), base + i as u8, *attrib);
if *attrib == Attrib::Close {
self.fs().has_tbc = true;
let name_k = self.str_const(name.as_bytes())?;
self.emit(Instr::Tbc {
reg: base + i as u8,
name: name_k,
});
}
}
// locals stay allocated
self.fs().free_reg = base + names.len() as u8;
return Ok(());
}
Stmt::LocalFunction { name, body } => {
self.at_line(body.line);
let reg = self.alloc_reg()?;
self.declare_local(name.clone(), reg, Attrib::None);
self.function_to_reg(body, format!("function '{name}'"), reg)?;
return Ok(());
}
Stmt::Function { target, body } => {
self.at_line(body.line);
let tmp = self.alloc_reg()?;
self.function_to_reg(body, "function".to_string(), tmp)?;
let t = self.target_of(target)?;
self.store(&t, tmp)?;
}
Stmt::Assign {
targets,
values,
line,
} => {
self.at_line(*line);
let tmp_start = self.fs().free_reg;
let resolved: Vec<Target> = targets
.iter()
.map(|t| self.target_of(t))
.collect::<Result<_, _>>()?;
let base = self.fs().free_reg;
self.explist_to(values, targets.len())?;
for (i, t) in resolved.into_iter().enumerate() {
self.store(&t, base + i as u8)?;
}
// Drop the target-prefix temporaries: the collector scans the
// whole stack (including dead slots), so leaving a captured
// value there would over-retain it (e.g. a weak key).
self.clear_regs(tmp_start, base);
}
Stmt::ExprStat(e) => {
self.call_like(e, Some(0))?;
}
Stmt::Do(b) => self.block_scope(b)?,
Stmt::While { cond, body } => {
let top = self.here();
let r = self.expr_to_any(cond)?;
let exit = self.emit_jump(Instr::Test {
src: r,
if_true: false,
off: 0,
});
self.fs().free_reg = self.local_top();
let floor = self.fs().free_reg;
self.funcs.last_mut().unwrap().loops.push(LoopCtx {
breaks: Vec::new(),
reg_floor: floor,
});
self.block_scope(body)?;
let off = self.back_off(top);
self.emit(Instr::Jump { off });
self.patch_to_here(exit);
self.finish_loop();
}
Stmt::Repeat { body, cond } => {
let top = self.here();
let floor = self.enter_scope();
let reg_floor = self.fs().free_reg;
self.funcs.last_mut().unwrap().loops.push(LoopCtx {
breaks: Vec::new(),
reg_floor,
});
self.stmt_seq(&body.stmts, false)?;
// condition sees the body's locals (Lua scoping rule)
let r = self.expr_to_any(cond)?;
let exit = self.emit_jump(Instr::Test {
src: r,
if_true: true,
off: 0,
});
self.emit(Instr::Close { from: reg_floor });
let off = self.back_off(top);
self.emit(Instr::Jump { off });
self.patch_to_here(exit);
self.exit_scope(floor);
self.finish_loop();
}
Stmt::If { arms, else_block } => {
let mut end_jumps = Vec::new();
for (i, (cond, body)) in arms.iter().enumerate() {
let r = self.expr_to_any(cond)?;
let skip = self.emit_jump(Instr::Test {
src: r,
if_true: false,
off: 0,
});
self.fs().free_reg = self.local_top();
self.block_scope(body)?;
let is_last_arm = i + 1 == arms.len() && else_block.is_none();
if !is_last_arm {
end_jumps.push(self.emit_jump(Instr::Jump { off: 0 }));
}
self.patch_to_here(skip);
}
if let Some(b) = else_block {
self.block_scope(b)?;
}
for j in end_jumps {
self.patch_to_here(j);
}
}
Stmt::NumericFor {
var,
start,
end,
step,
body,
line,
} => {
self.at_line(*line);
let floor = self.enter_scope();
let base = self.fs().free_reg;
let r0 = self.alloc_reg()?;
self.expr_to_reg(start, r0)?;
let r1 = self.alloc_reg()?;
self.expr_to_reg(end, r1)?;
let r2 = self.alloc_reg()?;
if let Some(e) = step {
self.expr_to_reg(e, r2)?;
} else {
let k = self.const_idx(CKey::Int(1), Value::Int(1))?;
self.emit(Instr::LoadK { dst: r2, k });
}
// hidden control registers are pseudo-locals (names can't collide)
self.declare_local("(for state)".into(), r0, Attrib::None);
self.declare_local("(for state)".into(), r1, Attrib::None);
self.declare_local("(for state)".into(), r2, Attrib::None);
let var_reg = self.alloc_reg()?;
self.declare_local(var.clone(), var_reg, Attrib::None);
let prep = self.emit_jump(Instr::ForPrep { base, off: 0 });
let body_top = self.here();
self.funcs.last_mut().unwrap().loops.push(LoopCtx {
breaks: Vec::new(),
reg_floor: base,
});
self.block_scope(body)?;
if self.var_captured(var_reg) {
self.emit(Instr::Close { from: var_reg });
}
let off = self.back_off(body_top);
self.emit(Instr::ForLoop { base, off });
self.patch_to_here(prep);
self.finish_loop();
self.exit_scope(floor);
}
Stmt::GenericFor {
vars,
exprs,
body,
line,
} => {
self.at_line(*line);
let floor = self.enter_scope();
let base = self.fs().free_reg;
// explist is adjusted to four values: iterator, state, control,
// and the closing value (5.4's 4th result, closed at loop exit).
self.explist_to(exprs, 4)?;
self.declare_local("(for state)".into(), base, Attrib::None);
self.declare_local("(for state)".into(), base + 1, Attrib::None);
self.declare_local("(for state)".into(), base + 2, Attrib::None);
self.declare_local("(for close)".into(), base + 3, Attrib::Close);
self.fs().has_tbc = true;
let name_k = self.str_const(b"(for state)")?;
self.emit(Instr::Tbc {
reg: base + 3,
name: name_k,
});
let vars_base = self.fs().free_reg;
debug_assert_eq!(vars_base, base + 4);
for v in vars {
let r = self.alloc_reg()?;
self.declare_local(v.clone(), r, Attrib::None);
}
let to_call = self.emit_jump(Instr::Jump { off: 0 });
let body_top = self.here();
self.funcs.last_mut().unwrap().loops.push(LoopCtx {
breaks: Vec::new(),
reg_floor: base,
});
self.block_scope(body)?;
let captured = (0..vars.len()).any(|i| self.var_captured(vars_base + i as u8));
if captured {
self.emit(Instr::Close { from: vars_base });
}
self.patch_to_here(to_call);
// call site: iterator(state, control) -> vars
let nvars = vars.len();
let save = self.fs().free_reg;
let tmp = self.alloc_regs(3)?;
self.emit(Instr::Move {
dst: tmp,
src: base,
});
self.emit(Instr::Move {
dst: tmp + 1,
src: base + 1,
});
self.emit(Instr::Move {
dst: tmp + 2,
src: base + 2,
});
self.emit(Instr::Call {
base: tmp,
nargs: 3,
nres: nvars as u8 + 1,
});
for i in 0..nvars {
self.emit(Instr::Move {
dst: vars_base + i as u8,
src: tmp + i as u8,
});
}
let off = self.back_off(body_top);
self.emit(Instr::TForLoop { base, off });
self.fs().free_reg = save;
self.finish_loop();
self.exit_scope(floor);
}
Stmt::Return { exprs, line } => {
self.at_line(*line);
// `return f(...)` in a function with no pending to-be-closed
// variables is a proper tail call: no frame is left behind.
if exprs.len() == 1
&& !self.fs().has_tbc
&& matches!(exprs[0], Expr::Call { .. } | Expr::MethodCall { .. })
{
self.tail_call_like(&exprs[0])?;
return Ok(());
}
let (base, count) = self.explist_open(exprs)?;
self.emit(Instr::Return {
base,
n: enc(count),
});
}
Stmt::Break(line) => {
self.at_line(*line);
if self.funcs.last().unwrap().loops.is_empty() {
return self.err(format!("break outside loop at line {line}"));
}
let floor = self.funcs.last().unwrap().loops.last().unwrap().reg_floor;
self.emit(Instr::Close { from: floor });
let j = self.emit_jump(Instr::Jump { off: 0 });
self.funcs
.last_mut()
.unwrap()
.loops
.last_mut()
.unwrap()
.breaks
.push(j);
}
}
self.fs().free_reg = watermark.max(self.local_top());
Ok(())
}
fn var_captured(&self, reg: u8) -> bool {
self.funcs
.last()
.unwrap()
.locals
.iter()
.any(|l| l.reg == reg && l.captured)
}
fn finish_loop(&mut self) {
let ctx = self.funcs.last_mut().unwrap().loops.pop().unwrap();
for j in ctx.breaks {
self.patch_to_here(j);
}
}
/// Resolves an assignment target, evaluating prefix expressions to temps.
fn target_of(&mut self, e: &Expr) -> Result<Target, CompileError> {
match e {
Expr::Name(n, line) => {
self.at_line(*line);
match self.resolve(n) {
NameLoc::Local(reg) => {
let is_const = self
.funcs
.last()
.unwrap()
.locals
.iter()
.rev()
.find(|l| l.reg == reg)
.is_some_and(|l| l.attrib != Attrib::None);
if is_const {
return self.err(format!("attempt to assign to const variable '{n}'"));
}
Ok(Target::Local(reg))
}
NameLoc::Upval(i) => {
let read_only = self
.funcs
.last()
.unwrap()
.upval_attribs
.get(i as usize)
.is_some_and(|a| *a != Attrib::None);
if read_only {
return self.err(format!("attempt to assign to const variable '{n}'"));
}
Ok(Target::Upval(i))
}
NameLoc::Global => Ok(Target::Global(self.str_const(n.as_bytes())?)),
}
}
Expr::Index { obj, key, line } => {
self.at_line(*line);
// Target prefixes must capture their pre-assignment values,
// because an earlier or later target may overwrite the local
// they read (e.g. `i, a[i], a = ...`). Force fresh temps
// instead of aliasing a local's register.
let o = self.expr_to_fresh(obj)?;
if let Expr::Str(s) = &**key {
let k = self.str_const(s)?;
Ok(Target::Field { obj: o, k })
} else {
let k = self.expr_to_fresh(key)?;
Ok(Target::Index { obj: o, key: k })
}
}
_ => self.err("cannot assign to this expression"),
}
}
fn store(&mut self, t: &Target, src: u8) -> Result<(), CompileError> {
match t {
Target::Local(reg) => {
if *reg != src {
self.emit(Instr::Move { dst: *reg, src });
}
}
Target::Upval(up) => {
self.emit(Instr::SetUpval { up: *up, src });
}
Target::Global(k) => match self.env_loc() {
EnvLoc::Local(r) => {
self.emit(Instr::SetField { obj: r, k: *k, src });
}
EnvLoc::Upval(up) => {
let tmp = self.alloc_reg()?;
self.emit(Instr::GetUpval { dst: tmp, up });
self.emit(Instr::SetField {
obj: tmp,
k: *k,
src,
});
self.fs().free_reg -= 1;
}
},
Target::Index { obj, key } => {
self.emit(Instr::SetIndex {
obj: *obj,
key: *key,
src,
});
}
Target::Field { obj, k } => {
self.emit(Instr::SetField {
obj: *obj,
k: *k,
src,
});
}
}
Ok(())
}
/// Where the current environment table lives: a local `_ENV` (Lua 5.4
/// allows `local _ENV = ...`) or the implicit `_ENV` upvalue.
fn env_loc(&mut self) -> EnvLoc {
match self.resolve("_ENV") {
NameLoc::Local(r) => EnvLoc::Local(r),
NameLoc::Upval(i) => EnvLoc::Upval(i),
NameLoc::Global => unreachable!("_ENV always resolves"),
}
}
// ---- expression lists ----
/// Compiles `exprs` adjusted to exactly `want` values in `want` freshly
/// allocated consecutive registers starting at the current free register.
fn explist_to(&mut self, exprs: &[Expr], want: usize) -> Result<(), CompileError> {
let base = self.fs().free_reg;
if exprs.is_empty() {
if want > 0 {
self.alloc_regs(want)?;
self.emit(Instr::LoadNil {
dst: base,
n: want as u8,
});
}
return Ok(());
}
for (i, e) in exprs.iter().enumerate() {
let last = i + 1 == exprs.len();
if !last || i >= want {
// middle expressions, and extra expressions beyond `want`,
// are evaluated for side effects (one value, maybe discarded)
let save = self.fs().free_reg;
let r = self.alloc_reg()?;
self.expr_to_reg(e, r)?;
if i >= want {
self.fs().free_reg = save;
}
} else {
let have = i; // values produced so far
let need = want - have;
if e.is_multret() {
self.multret_tail(e, Some(need))?;
} else {
let r = self.alloc_reg()?;
self.expr_to_reg(e, r)?;
if need > 1 {
let pad = self.alloc_regs(need - 1)?;
self.emit(Instr::LoadNil {
dst: pad,
n: (need - 1) as u8,
});
}
}
}
}
debug_assert!(self.fs().free_reg >= base + want.min(exprs.len()) as u8);
Ok(())
}
/// Compiles `exprs` for an open (multret) context: call arguments or
/// return values. Returns (base, Some(count)) for a fixed number of
/// values, or (base, None) when the last expression expands to top.
fn explist_open(&mut self, exprs: &[Expr]) -> Result<(u8, Option<usize>), CompileError> {
let base = self.fs().free_reg;
if exprs.is_empty() {
return Ok((base, Some(0)));
}
for (i, e) in exprs.iter().enumerate() {
let last = i + 1 == exprs.len();
if last && e.is_multret() {
self.multret_tail(e, None)?;
return Ok((base, None));
}
let r = self.alloc_reg()?;
self.expr_to_reg(e, r)?;
}
Ok((base, Some(exprs.len())))
}
/// Compiles a multret-capable expression (call/method call/vararg) at the
/// current free register with `nres` results (None = up to top).
/// Allocates the result registers when `nres` is fixed.
fn multret_tail(&mut self, e: &Expr, nres: Option<usize>) -> Result<u8, CompileError> {
match e {
Expr::Call { .. } | Expr::MethodCall { .. } => self.call_like(e, nres),
Expr::Vararg(line) => {
self.at_line(*line);
if !self.funcs.last().unwrap().is_vararg {
return self.err("cannot use '...' outside a vararg function");
}
let base = self.alloc_regs(nres.unwrap_or(1).max(1))?;
if nres.is_none() {
self.fs().free_reg = base; // results tracked via top
}
self.emit(Instr::Vararg {
dst: base,
n: enc(nres),
});
Ok(base)
}
_ => unreachable!("multret_tail on non-multret expression"),
}
}
/// Best-effort PUC `getobjname` for a call's callee: the name (and
/// `namewhat` category) to report from `debug.getinfo`'s `n` option.
fn callee_name(&mut self, e: &Expr) -> Option<(&'static str, Box<str>)> {
match e {
Expr::Name(n, _) => {
let namewhat = match self.resolve(n) {
NameLoc::Global => "global",
NameLoc::Local(_) => "local",
NameLoc::Upval(_) => "upvalue",
};
Some((namewhat, n.clone()))
}
Expr::Index { key, .. } => match &**key {
Expr::Str(s) => Some((
"field",
String::from_utf8_lossy(s).into_owned().into_boxed_str(),
)),
_ => None,
},
_ => None,
}
}
/// Compiles a call or method call. Results land at the returned base
/// register; for fixed `nres` the result registers stay allocated.
fn call_like(&mut self, e: &Expr, nres: Option<usize>) -> Result<u8, CompileError> {
let base = self.alloc_reg()?;
match e {
Expr::Call { func, args, line } => {
self.at_line(*line);
let name = self.callee_name(func);
self.expr_to_reg(func, base)?;
self.fs().free_reg = base + 1;
let argc = self.compile_args(args)?;
self.at_line(*line);
let idx = self.emit(Instr::Call {
base,
nargs: argc.map_or(0, |c| c as u8 + 1),
nres: enc(nres),
});
self.fs().call_names[idx] = name;
}
Expr::MethodCall {
obj,
name,
args,
line,
} => {
self.at_line(*line);
let selfr = self.alloc_reg()?; // base + 1
self.expr_to_reg(obj, selfr)?;
self.fs().free_reg = base + 2;
let k = self.str_const(name.as_bytes())?;
self.emit(Instr::GetField {
dst: base,
obj: selfr,
k,
});
let argc = self.compile_args(args)?;
self.at_line(*line);
let idx = self.emit(Instr::Call {
base,
nargs: argc.map_or(0, |c| c as u8 + 2),
nres: enc(nres),
});
self.fs().call_names[idx] = Some(("method", name.clone()));
}
_ => unreachable!("call_like on non-call"),
}
// release the call window, keep fixed results
self.fs().free_reg = base + nres.unwrap_or(0) as u8;
let watermark = self.local_top();
if self.fs().free_reg < watermark {
self.fs().free_reg = watermark;
}
if let Some(n) = nres {
let fs = self.fs();
let end = base as usize + n;
if end > fs.max_regs as usize {
fs.max_regs = end as u8;
}
}
Ok(base)
}
/// Compiles `return <call>` as a proper tail call. Mirrors `call_like`
/// but emits `TailCall` (open results) so the VM reuses the frame.
fn tail_call_like(&mut self, e: &Expr) -> Result<(), CompileError> {
let base = self.alloc_reg()?;
match e {
Expr::Call { func, args, line } => {
self.at_line(*line);
let name = self.callee_name(func);
self.expr_to_reg(func, base)?;
self.fs().free_reg = base + 1;
let argc = self.compile_args(args)?;
self.at_line(*line);
let idx = self.emit(Instr::TailCall {
base,
nargs: argc.map_or(0, |c| c as u8 + 1),
});
self.fs().call_names[idx] = name;
}
Expr::MethodCall {
obj,
name,
args,
line,
} => {
self.at_line(*line);
let selfr = self.alloc_reg()?; // base + 1
self.expr_to_reg(obj, selfr)?;
self.fs().free_reg = base + 2;
let k = self.str_const(name.as_bytes())?;
self.emit(Instr::GetField {
dst: base,
obj: selfr,
k,
});
let argc = self.compile_args(args)?;
self.at_line(*line);
let idx = self.emit(Instr::TailCall {
base,
nargs: argc.map_or(0, |c| c as u8 + 2),
});
self.fs().call_names[idx] = Some(("method", name.clone()));
}
_ => unreachable!("tail_call_like on non-call"),
}
Ok(())
}
/// Compiles call arguments into consecutive registers above the current
/// free register. Returns Some(count) or None for an open tail.
fn compile_args(&mut self, args: &[Expr]) -> Result<Option<usize>, CompileError> {
for (i, a) in args.iter().enumerate() {
let last = i + 1 == args.len();
if last && a.is_multret() {
self.multret_tail(a, None)?;
return Ok(None);
}
let r = self.alloc_reg()?;
self.expr_to_reg(a, r)?;
}
Ok(Some(args.len()))
}
// ---- expressions ----
/// Returns a register holding the expression's value: the variable's own
/// register for plain local names, otherwise a fresh temporary.
fn expr_to_any(&mut self, e: &Expr) -> Result<u8, CompileError> {
if let Expr::Name(n, line) = e {
self.at_line(*line);
if let NameLoc::Local(r) = self.resolve(n) {
return Ok(r);
}
}
let r = self.alloc_reg()?;
self.expr_to_reg(e, r)?;
Ok(r)
}
/// Like [`Self::expr_to_any`], but always materializes the value in a
/// fresh temporary, even for a local. Assignment-target prefixes use this
/// so a later store to that local cannot invalidate the captured value.
fn expr_to_fresh(&mut self, e: &Expr) -> Result<u8, CompileError> {
let r = self.alloc_reg()?;
self.expr_to_reg(e, r)?;
Ok(r)
}
/// Sets registers `from..to` to nil. Keeps stale references out of dead
/// slots, which the whole-stack collector would otherwise treat as roots.
fn clear_regs(&mut self, from: u8, to: u8) {
if from < to {
self.emit(Instr::LoadNil {
dst: from,
n: to - from,
});
}
}
fn expr_to_reg(&mut self, e: &Expr, dst: u8) -> Result<(), CompileError> {
match e {
Expr::Nil => {
self.emit(Instr::LoadNil { dst, n: 1 });
}
Expr::True => {
self.emit(Instr::LoadBool { dst, b: true });
}
Expr::False => {
self.emit(Instr::LoadBool { dst, b: false });
}
Expr::Int(i) => {
let k = self.const_idx(CKey::Int(*i), Value::Int(*i))?;
self.emit(Instr::LoadK { dst, k });
}
Expr::Float(f) => {
let k = self.const_idx(CKey::Float(f.to_bits()), Value::Float(*f))?;
self.emit(Instr::LoadK { dst, k });
}
Expr::Str(s) => {
let k = self.str_const(s)?;
self.emit(Instr::LoadK { dst, k });
}
Expr::Vararg(line) => {
self.at_line(*line);
if !self.funcs.last().unwrap().is_vararg {
return self.err("cannot use '...' outside a vararg function");
}
self.emit(Instr::Vararg { dst, n: 2 });
}
Expr::Function(fb) => {
self.function_to_reg(fb, "anonymous function".into(), dst)?;
}
Expr::Name(n, line) => {
self.at_line(*line);
match self.resolve(n) {
NameLoc::Local(r) => {
if r != dst {
self.emit(Instr::Move { dst, src: r });
}
}
NameLoc::Upval(up) => {
self.emit(Instr::GetUpval { dst, up });
}
NameLoc::Global => {
let k = self.str_const(n.as_bytes())?;
match self.env_loc() {
EnvLoc::Local(r) => {
self.emit(Instr::GetField { dst, obj: r, k });
}
EnvLoc::Upval(up) => {
self.emit(Instr::GetUpval { dst, up });
self.emit(Instr::GetField { dst, obj: dst, k });
}
}
}
}
}
Expr::Index { obj, key, line } => {
self.at_line(*line);
let save = self.fs().free_reg;
let o = self.expr_to_any(obj)?;
if let Expr::Str(s) = &**key {
let k = self.str_const(s)?;
self.emit(Instr::GetField { dst, obj: o, k });
} else {
let kr = self.expr_to_any(key)?;
self.emit(Instr::GetIndex {
dst,
obj: o,
key: kr,
});
}
self.fs().free_reg = save;
}
Expr::Call { .. } | Expr::MethodCall { .. } => {
let save = self.fs().free_reg;
let base = self.call_like(e, Some(1))?;
self.fs().free_reg = save;
if base != dst {
self.emit(Instr::Move { dst, src: base });
}
}
Expr::BinOp { op, lhs, rhs, line } => {
self.at_line(*line);
self.binop_to_reg(*op, lhs, rhs, dst, *line)?;
}
Expr::UnOp { op, operand, line } => {
self.at_line(*line);
let save = self.fs().free_reg;
let src = self.expr_to_any(operand)?;
let op = match op {
UnOp::Neg => UnaryOp::Neg,
UnOp::Not => UnaryOp::Not,
UnOp::Len => UnaryOp::Len,
UnOp::BNot => UnaryOp::BNot,
};
self.emit(Instr::Unary { op, dst, src });
self.fs().free_reg = save;
}
Expr::Table { items, pairs, line } => {
self.at_line(*line);
self.emit(Instr::NewTable { dst });
let save = self.fs().free_reg;
// array items, flushed in batches of 50
let mut start: u32 = 1;
let mut pending: usize = 0;
let mut batch_base = self.fs().free_reg;
for (i, item) in items.iter().enumerate() {
let last = i + 1 == items.len();
if last && item.is_multret() {
self.multret_tail(item, None)?;
self.emit(Instr::SetList {
obj: dst,
base: batch_base,
n: 0,
start,
});
pending = 0;
break;
}
let r = self.alloc_reg()?;
self.expr_to_reg(item, r)?;
pending += 1;
if pending == 50 {
self.emit(Instr::SetList {
obj: dst,
base: batch_base,
n: pending as u8,
start,
});
start += pending as u32;
pending = 0;
self.fs().free_reg = save;
batch_base = save;
}
}
if pending > 0 {
self.emit(Instr::SetList {
obj: dst,
base: batch_base,
n: pending as u8,
start,
});
}
self.fs().free_reg = save;
for (k, v) in pairs {
let save = self.fs().free_reg;
if let Expr::Str(s) = k {
let kc = self.str_const(s)?;
let vr = self.expr_to_any(v)?;
self.emit(Instr::SetField {
obj: dst,
k: kc,
src: vr,
});
} else {
let kr = self.expr_to_any(k)?;
let vr = self.expr_to_any(v)?;
self.emit(Instr::SetIndex {
obj: dst,
key: kr,
src: vr,
});
}
self.fs().free_reg = save;
}
}
Expr::Paren(inner) => {
self.expr_to_reg(inner, dst)?;
}
}
Ok(())
}
fn binop_to_reg(
&mut self,
op: BinOp,
lhs: &Expr,
rhs: &Expr,
dst: u8,
line: u32,
) -> Result<(), CompileError> {
match op {
BinOp::And | BinOp::Or => {
self.expr_to_reg(lhs, dst)?;
let j = self.emit_jump(Instr::Test {
src: dst,
if_true: op == BinOp::Or,
off: 0,
});
self.expr_to_reg(rhs, dst)?;
self.patch_to_here(j);
}
BinOp::Concat => {
// flatten the right-leaning concat chain into one Concat op
let save = self.fs().free_reg;
let mut parts: Vec<&Expr> = vec![lhs];
let mut cur = rhs;
while let Expr::BinOp {
op: BinOp::Concat,
lhs,
rhs,
..
} = cur
{
parts.push(lhs);
cur = rhs;
}
parts.push(cur);
let base = self.fs().free_reg;
for p in &parts {
let r = self.alloc_reg()?;
self.expr_to_reg(p, r)?;
}
self.at_line(line);
self.emit(Instr::Concat {
dst,
base,
n: parts.len() as u8,
});
self.fs().free_reg = save;
}
BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
let save = self.fs().free_reg;
let (cmp, l, r) = match op {
BinOp::Eq => (CmpOp::Eq, lhs, rhs),
BinOp::Ne => (CmpOp::Ne, lhs, rhs),
BinOp::Lt => (CmpOp::Lt, lhs, rhs),
BinOp::Le => (CmpOp::Le, lhs, rhs),
// a > b ==> b < a ; a >= b ==> b <= a
BinOp::Gt => (CmpOp::Lt, rhs, lhs),
BinOp::Ge => (CmpOp::Le, rhs, lhs),
_ => unreachable!(),
};
let lr = self.expr_to_any(l)?;
let rr = self.expr_to_any(r)?;
self.at_line(line);
self.emit(Instr::Cmp {
op: cmp,
dst,
lhs: lr,
rhs: rr,
});
self.fs().free_reg = save;
}
_ => {
let save = self.fs().free_reg;
let aop = match op {
BinOp::Add => ArithOp::Add,
BinOp::Sub => ArithOp::Sub,
BinOp::Mul => ArithOp::Mul,
BinOp::Div => ArithOp::Div,
BinOp::IDiv => ArithOp::IDiv,
BinOp::Mod => ArithOp::Mod,
BinOp::Pow => ArithOp::Pow,
BinOp::BAnd => ArithOp::BAnd,
BinOp::BOr => ArithOp::BOr,
BinOp::BXor => ArithOp::BXor,
BinOp::Shl => ArithOp::Shl,
BinOp::Shr => ArithOp::Shr,
_ => unreachable!(),
};
let lr = self.expr_to_any(lhs)?;
let rr = self.expr_to_any(rhs)?;
self.at_line(line);
self.emit(Instr::Arith {
op: aop,
dst,
lhs: lr,
rhs: rr,
});
self.fs().free_reg = save;
}
}
Ok(())
}
fn function_to_reg(
&mut self,
fb: &FuncBody,
name: String,
dst: u8,
) -> Result<(), CompileError> {
if fb.params.len() > 200 {
return self.err("too many parameters");
}
let mut fs = FuncState::new(name, fb.params.len() as u8, fb.is_vararg);
fs.cur_line = fb.line;
fs.linedefined = fb.line;
self.funcs.push(fs);
for p in &fb.params {
let r = self.alloc_reg()?;
self.declare_local(p.clone(), r, Attrib::None);
}
self.block_scope(&fb.body)?;
self.check_pending_gotos()?;
// The implicit final `RETURN` carries the line of the closing `end`,
// which is what PUC records in `lastlinedefined` and `activelines`.
self.at_line(fb.end_line);
self.fs().line_end = fb.end_line;
self.emit(Instr::Return { base: 0, n: 1 });
let done = self.funcs.pop().unwrap();
let proto = Rc::new(done.into_proto(self.source.clone()));
let fs = self.fs();
if fs.protos.len() >= u16::MAX as usize {
return self.err("too many nested functions");
}
let p = fs.protos.len() as u16;
fs.protos.push(proto);
self.emit(Instr::Closure { dst, p });
Ok(())
}
}