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
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
//! Loop compilation (for, while, loop expressions)
use crate::bytecode::{Constant, Instruction, OpCode, Operand};
use crate::type_tracking::NumericType;
use shape_ast::ast::{Expr, ForInit, RangeKind};
use shape_ast::error::{Result, ShapeError};
use super::{BytecodeCompiler, LoopContext};
/// State for a range counter loop specialization.
pub(super) struct RangeCounterLoopState {
/// Local slot holding the loop counter (also the user's binding).
pub counter_local: u16,
/// Bytecode offset of the LoopStart instruction.
pub loop_start: usize,
/// Bytecode index of the exit JumpIfFalse (to be patched).
pub exit_jump: usize,
}
impl BytecodeCompiler {
// ===== Range counter loop specialization =====
/// Try to begin a range counter loop specialization.
///
/// If the iterator is a `Range { start, end }` with both endpoints present,
/// emits a counter-based loop prologue and returns the state. The caller
/// emits the body, then calls `end_range_counter_loop`.
///
/// `var_name` is the simple identifier name for the loop variable.
/// Pass `None` to signal that the pattern is not a simple identifier
/// (returns `Ok(None)` immediately).
///
/// Returns `Ok(None)` (no side effects) when specialization is not applicable.
pub(super) fn try_begin_range_counter_loop(
&mut self,
var_name: Option<&str>,
iter: &Expr,
) -> Result<Option<RangeCounterLoopState>> {
// Only specialize simple identifier patterns
let var_name = match var_name {
Some(name) => name,
None => return Ok(None),
};
// Only specialize Range with both endpoints present
let (start_expr, end_expr, inclusive) = match iter {
Expr::Range {
start: Some(s),
end: Some(e),
kind,
..
} => (s.as_ref(), e.as_ref(), *kind == RangeKind::Inclusive),
_ => return Ok(None),
};
// === Point of no return: emit specialized bytecode ===
// Declare loop variable (user binding = counter)
let counter_local = self.declare_local(var_name)?;
let end_local = self.declare_local("__range_end")?;
// Strict-typing-sweep (Cluster 4): the counter is always `int` (range
// endpoints are coerced to int in the prologue). Without installing
// this in the type tracker, binary ops on the IV (`i + 1`, `s + i`)
// inside the loop body see the IV as `unknown` and fail strict-typing.
self.set_local_type_info(counter_local, "int");
self.set_local_type_info(end_local, "int");
// compile(start) → [NumberToInt if float] → StoreLocal(counter)
self.compile_expr(start_expr)?;
let start_nt = self.last_expr_numeric_type;
if matches!(start_nt, Some(NumericType::Number)) {
self.emit(Instruction::simple(OpCode::NumberToInt));
}
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(counter_local)),
));
// compile(end) → [NumberToInt if float] → StoreLocal(__end)
self.compile_expr(end_expr)?;
let end_nt = self.last_expr_numeric_type;
if matches!(end_nt, Some(NumericType::Number)) {
self.emit(Instruction::simple(OpCode::NumberToInt));
}
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(end_local)),
));
// LoopStart
let loop_start = self.program.current_offset();
self.emit(Instruction::simple(OpCode::LoopStart));
// LoadLocal(counter), LoadLocal(__end), LtInt/LteInt
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(counter_local)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(end_local)),
));
// Both endpoints are always int at this point (Int directly, or
// Number after NumberToInt conversion in the prologue).
self.emit(Instruction::simple(if inclusive {
OpCode::LteInt
} else {
OpCode::LtInt
}));
// JumpIfFalse(exit)
let exit_jump = self.emit_jump(OpCode::JumpIfFalse, 0);
Ok(Some(RangeCounterLoopState {
counter_local,
loop_start,
exit_jump,
}))
}
/// End a range counter loop: patch continue jumps, emit increment,
/// back-jump, LoopEnd, and patch exit jump.
pub(super) fn end_range_counter_loop(&mut self, state: &RangeCounterLoopState) {
// Patch deferred continue jumps to the increment block
if let Some(loop_ctx) = self.loop_stack.last() {
let continue_jumps: Vec<usize> = loop_ctx.continue_jumps.clone();
for cj in continue_jumps {
self.patch_jump(cj);
}
}
// Increment: LoadLocal(counter), PushConst(1), AddInt, StoreLocal(counter)
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(state.counter_local)),
));
// Counter is always int (range endpoints coerced to int in prologue)
let one_const = self.program.add_constant(Constant::Int(1));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(one_const)),
));
self.emit(Instruction::simple(OpCode::AddInt));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(state.counter_local)),
));
// Jump back to LoopStart
let offset = state.loop_start as i32 - self.program.current_offset() as i32 - 1;
self.emit(Instruction::new(
OpCode::Jump,
Some(Operand::Offset(offset)),
));
// LoopEnd
self.emit(Instruction::simple(OpCode::LoopEnd));
// Patch exit jump (past LoopEnd)
self.patch_jump(state.exit_jump);
}
pub(super) fn compile_while_loop(
&mut self,
while_loop: &shape_ast::ast::WhileLoop,
) -> Result<()> {
// Emit LoopStart marker for JIT loop optimizations (LICM, GC safepoint, int unboxing)
let loop_start = self.program.current_offset();
self.emit(Instruction::simple(OpCode::LoopStart));
// Create loop context — continue targets LoopStart so condition re-evaluates
let loop_ctx = LoopContext {
break_jumps: Vec::new(),
continue_target: loop_start,
break_value_local: None,
iterator_on_stack: false,
drop_scope_depth: self.drop_locals.len(),
continue_jumps: Vec::new(),
};
// Compile condition
self.compile_expr(&while_loop.condition)?;
// Jump out if false
let exit_jump = self.emit_jump(OpCode::JumpIfFalse, 0);
// Push loop context
self.loop_stack.push(loop_ctx);
// Compile body
self.push_repeating_reference_release_barrier();
let body_result = (|| -> Result<()> {
for (idx, stmt) in while_loop.body.iter().enumerate() {
let future_names = self.future_reference_use_names_for_remaining_statements(
&while_loop.body[idx + 1..],
);
self.push_future_reference_use_names(future_names);
let compile_result = self.compile_statement(stmt);
self.pop_future_reference_use_names();
compile_result?;
self.release_unused_local_reference_borrows_for_remaining_statements(
&while_loop.body[idx + 1..],
);
self.release_unused_module_reference_borrows_for_remaining_statements(
&while_loop.body[idx + 1..],
);
}
Ok(())
})();
self.pop_repeating_reference_release_barrier();
body_result?;
// Jump back to LoopStart
let offset = loop_start as i32 - self.program.current_offset() as i32 - 1;
self.emit(Instruction::new(
OpCode::Jump,
Some(Operand::Offset(offset)),
));
// Emit LoopEnd marker
self.emit(Instruction::simple(OpCode::LoopEnd));
// Patch exit jump (past LoopEnd)
self.patch_jump(exit_jump);
// Pop loop context and patch break jumps
if let Some(loop_ctx) = self.loop_stack.pop() {
for break_jump in loop_ctx.break_jumps {
self.patch_jump(break_jump);
}
}
Ok(())
}
pub(super) fn compile_while_expr(
&mut self,
while_expr: &shape_ast::ast::WhileExpr,
) -> Result<()> {
self.push_scope();
let result_local = self.declare_local("__while_result")?;
self.emit(Instruction::simple(OpCode::PushNull));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(result_local)),
));
let loop_start = self.program.current_offset();
self.emit(Instruction::simple(OpCode::LoopStart));
self.compile_expr(&while_expr.condition)?;
let exit_jump = self.emit_jump(OpCode::JumpIfFalse, 0);
self.loop_stack.push(LoopContext {
break_jumps: Vec::new(),
continue_target: loop_start,
break_value_local: Some(result_local),
iterator_on_stack: false,
drop_scope_depth: self.drop_locals.len(),
continue_jumps: Vec::new(),
});
self.push_repeating_reference_release_barrier();
let body_result = self.compile_expr(&while_expr.body);
self.pop_repeating_reference_release_barrier();
body_result?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(result_local)),
));
let offset = loop_start as i32 - self.program.current_offset() as i32 - 1;
self.emit(Instruction::new(
OpCode::Jump,
Some(Operand::Offset(offset)),
));
self.emit(Instruction::simple(OpCode::LoopEnd));
self.patch_jump(exit_jump);
if let Some(loop_ctx) = self.loop_stack.pop() {
for break_jump in loop_ctx.break_jumps {
self.patch_jump(break_jump);
}
}
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(result_local)),
));
self.pop_scope();
Ok(())
}
/// Compile for loop
pub(super) fn compile_for_loop(&mut self, for_loop: &shape_ast::ast::ForLoop) -> Result<()> {
// Validate: `for await` requires async context
if for_loop.is_async && !self.current_function_is_async {
return Err(ShapeError::SemanticError {
message: "'for await' can only be used inside an async function".to_string(),
location: None,
});
}
match &for_loop.init {
ForInit::ForIn { pattern, iter } => {
self.push_scope();
// Try range counter loop specialization (non-async only)
if !for_loop.is_async {
if let Some(rcl) = self.try_begin_range_counter_loop(
pattern.as_identifier(),
iter,
)? {
self.apply_binding_semantics_to_pattern_bindings(
pattern,
true,
Self::owned_mutable_binding_semantics(),
);
self.loop_stack.push(LoopContext {
break_jumps: Vec::new(),
continue_target: usize::MAX, // deferred
break_value_local: None,
iterator_on_stack: false,
drop_scope_depth: self.drop_locals.len(),
continue_jumps: Vec::new(),
});
// Compile body
self.push_repeating_reference_release_barrier();
let body_result = (|| -> Result<()> {
for (idx, stmt) in for_loop.body.iter().enumerate() {
let future_names = self
.future_reference_use_names_for_remaining_statements(
&for_loop.body[idx + 1..],
);
self.push_future_reference_use_names(future_names);
let compile_result = self.compile_statement(stmt);
self.pop_future_reference_use_names();
compile_result?;
self.release_unused_local_reference_borrows_for_remaining_statements(
&for_loop.body[idx + 1..],
);
self.release_unused_module_reference_borrows_for_remaining_statements(
&for_loop.body[idx + 1..],
);
}
Ok(())
})();
self.pop_repeating_reference_release_barrier();
body_result?;
self.end_range_counter_loop(&rcl);
if let Some(loop_ctx) = self.loop_stack.pop() {
for break_jump in loop_ctx.break_jumps {
self.patch_jump(break_jump);
}
}
self.pop_scope();
return Ok(());
}
}
// === Generic iterator path (unchanged) ===
// Compile iterator expression and leave it on stack
self.compile_expr(iter)?;
// Reserve local for index counter
let idx_local = self.declare_local("__idx")?;
// Initialize index to 0 (int — internal counter, always integer)
let zero_const = self.program.add_constant(Constant::Int(0));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(zero_const)),
));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(idx_local)),
));
// Pre-declare locals for destructuring pattern
// This ensures the locals are in scope for the entire loop
for name in pattern.get_identifiers() {
self.declare_local(&name)?;
}
self.apply_binding_semantics_to_pattern_bindings(
pattern,
true,
Self::owned_mutable_binding_semantics(),
);
// Phase 3e: propagate iterator element type to the loop
// variable. Without this, `for x in arr` (over an
// Array<int>) declares `x` with no type info, so
// `sum + x` can't emit AddInt and falls into trait
// dispatch (which has no runtime handler for int.add).
//
// Only handles the common single-identifier pattern.
// Complex destructuring patterns continue to leave the
// loop var(s) untyped — bidirectional inference can
// recover them when needed.
if let Some(var_name) = pattern.as_identifier() {
if let Some(local_idx) = self.resolve_local(var_name) {
if let Some(elem_type) = self.iter_element_type_name(iter) {
self.set_local_type_info(local_idx, &elem_type);
}
}
}
let loop_start = self.program.current_offset();
self.emit(Instruction::simple(OpCode::LoopStart));
let loop_ctx = LoopContext {
break_jumps: Vec::new(),
continue_target: loop_start,
break_value_local: None,
iterator_on_stack: true,
drop_scope_depth: self.drop_locals.len(),
continue_jumps: Vec::new(),
};
// Check if iterator is done (dup iterator and index, then IterDone)
self.emit(Instruction::simple(OpCode::Dup)); // Dup iterator
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(idx_local)),
));
self.emit(Instruction::simple(OpCode::IterDone));
let exit_jump = self.emit_jump(OpCode::JumpIfTrue, 0);
// Get next element (dup iterator and index, then IterNext)
self.emit(Instruction::simple(OpCode::Dup)); // Dup iterator
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(idx_local)),
));
self.emit(Instruction::simple(OpCode::IterNext));
// For `for await`, each element is a Future — await it before binding
if for_loop.is_async {
self.emit(Instruction::simple(OpCode::Await));
}
// Destructure value into loop variable(s)
self.compile_destructure_pattern(pattern)?;
// Increment index before body so continue jumps advance correctly
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(idx_local)),
));
let one_const = self.program.add_constant(Constant::Int(1));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(one_const)),
));
self.emit(Instruction::simple(OpCode::AddInt));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(idx_local)),
));
// Push loop context
self.loop_stack.push(loop_ctx);
// Compile body
self.push_repeating_reference_release_barrier();
let body_result = (|| -> Result<()> {
for (idx, stmt) in for_loop.body.iter().enumerate() {
let future_names = self
.future_reference_use_names_for_remaining_statements(
&for_loop.body[idx + 1..],
);
self.push_future_reference_use_names(future_names);
let compile_result = self.compile_statement(stmt);
self.pop_future_reference_use_names();
compile_result?;
self.release_unused_local_reference_borrows_for_remaining_statements(
&for_loop.body[idx + 1..],
);
self.release_unused_module_reference_borrows_for_remaining_statements(
&for_loop.body[idx + 1..],
);
}
Ok(())
})();
self.pop_repeating_reference_release_barrier();
body_result?;
// Jump back to LoopStart
let offset = loop_start as i32 - self.program.current_offset() as i32 - 1;
self.emit(Instruction::new(
OpCode::Jump,
Some(Operand::Offset(offset)),
));
self.emit(Instruction::simple(OpCode::LoopEnd));
// Patch exit jump (past LoopEnd)
self.patch_jump(exit_jump);
// Pop iterator from stack
self.emit(Instruction::simple(OpCode::Pop));
// Pop loop context and patch break jumps
if let Some(loop_ctx) = self.loop_stack.pop() {
for break_jump in loop_ctx.break_jumps {
self.patch_jump(break_jump);
}
}
self.pop_scope();
}
ForInit::ForC {
init,
condition,
update,
} => {
// Compile C-style for loop
self.push_scope();
// Initialize
self.compile_statement(init)?;
let loop_start = self.program.current_offset();
self.emit(Instruction::simple(OpCode::LoopStart));
// Create loop context
let update_start = self.program.current_offset();
let mut loop_ctx = LoopContext {
break_jumps: Vec::new(),
continue_target: update_start,
break_value_local: None,
iterator_on_stack: false,
drop_scope_depth: self.drop_locals.len(),
continue_jumps: Vec::new(),
};
// Check condition
self.compile_expr(condition)?;
let exit_jump = self.emit_jump(OpCode::JumpIfFalse, 0);
// Push loop context
self.loop_stack.push(loop_ctx);
// Compile body
self.push_repeating_reference_release_barrier();
let body_result = (|| -> Result<()> {
for (idx, stmt) in for_loop.body.iter().enumerate() {
let future_names = self
.future_reference_use_names_for_remaining_statements(
&for_loop.body[idx + 1..],
);
self.push_future_reference_use_names(future_names);
let compile_result = self.compile_statement(stmt);
self.pop_future_reference_use_names();
compile_result?;
self.release_unused_local_reference_borrows_for_remaining_statements(
&for_loop.body[idx + 1..],
);
self.release_unused_module_reference_borrows_for_remaining_statements(
&for_loop.body[idx + 1..],
);
}
Ok(())
})();
self.pop_repeating_reference_release_barrier();
body_result?;
// Update
loop_ctx = self
.loop_stack
.pop()
.expect("loop context was pushed above");
loop_ctx.continue_target = self.program.current_offset();
self.loop_stack.push(loop_ctx);
self.compile_expr(update)?;
self.emit(Instruction::simple(OpCode::Pop));
// Jump back to LoopStart
let offset = loop_start as i32 - self.program.current_offset() as i32 - 1;
self.emit(Instruction::new(
OpCode::Jump,
Some(Operand::Offset(offset)),
));
self.emit(Instruction::simple(OpCode::LoopEnd));
// Patch exit jump (past LoopEnd)
self.patch_jump(exit_jump);
// Pop loop context and patch break jumps
if let Some(loop_ctx) = self.loop_stack.pop() {
for break_jump in loop_ctx.break_jumps {
self.patch_jump(break_jump);
}
}
self.pop_scope();
}
}
Ok(())
}
pub(super) fn compile_for_expr(&mut self, for_expr: &shape_ast::ast::ForExpr) -> Result<()> {
// Validate: `for await` requires async context
if for_expr.is_async && !self.current_function_is_async {
return Err(ShapeError::SemanticError {
message: "'for await' can only be used inside an async function".to_string(),
location: None,
});
}
self.push_scope();
// Try range counter specialization (non-async, simple identifier pattern)
if !for_expr.is_async {
let pattern_name = match &for_expr.pattern {
shape_ast::ast::Pattern::Identifier(name) => Some(name.as_str()),
_ => None,
};
if let Some(rcl) =
self.try_begin_range_counter_loop(pattern_name, &for_expr.iterable)?
{
let result_local = self.declare_local("__for_result")?;
self.emit(Instruction::simple(OpCode::PushNull));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(result_local)),
));
self.apply_binding_semantics_to_value_pattern_bindings(
&for_expr.pattern,
Self::owned_mutable_binding_semantics(),
);
self.loop_stack.push(LoopContext {
break_jumps: Vec::new(),
continue_target: usize::MAX,
break_value_local: Some(result_local),
iterator_on_stack: false,
drop_scope_depth: self.drop_locals.len(),
continue_jumps: Vec::new(),
});
self.push_repeating_reference_release_barrier();
let body_result = self.compile_expr(&for_expr.body);
self.pop_repeating_reference_release_barrier();
body_result?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(result_local)),
));
self.end_range_counter_loop(&rcl);
if let Some(loop_ctx) = self.loop_stack.pop() {
for break_jump in loop_ctx.break_jumps {
self.patch_jump(break_jump);
}
}
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(result_local)),
));
self.pop_scope();
return Ok(());
}
}
// === Generic iterator path (unchanged) ===
// Determine binding pattern: simple identifier, object destructure, or array destructure.
let elem_local;
let mut destructure_fields: Vec<(String, u16)> = Vec::new();
let mut array_destructure_locals: Vec<u16> = Vec::new();
let is_object_destructure;
let mut is_array_destructure = false;
let result_local = self.declare_local("__for_result")?;
self.emit(Instruction::simple(OpCode::PushNull));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(result_local)),
));
self.compile_expr(&for_expr.iterable)?;
let idx_local = self.declare_local("__idx")?;
let zero_const = self.program.add_constant(Constant::Int(0));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(zero_const)),
));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(idx_local)),
));
match &for_expr.pattern {
shape_ast::ast::Pattern::Identifier(name) => {
elem_local = self.declare_local(name)?;
is_object_destructure = false;
}
shape_ast::ast::Pattern::Object(fields) => {
elem_local = self.declare_local("__elem")?;
for (key, pat) in fields {
let field_name = match pat {
shape_ast::ast::Pattern::Identifier(n) => n.as_str(),
_ => key.as_str(),
};
let local = self.declare_local(field_name)?;
destructure_fields.push((key.clone(), local));
}
is_object_destructure = true;
}
shape_ast::ast::Pattern::Array(patterns) => {
elem_local = self.declare_local("__elem")?;
for pat in patterns {
let name = match pat {
shape_ast::ast::Pattern::Identifier(n) => n.clone(),
shape_ast::ast::Pattern::Wildcard => "__discard".to_string(),
_ => {
return Err(ShapeError::RuntimeError {
message:
"Nested patterns in for-loop array destructure not supported"
.to_string(),
location: None,
});
}
};
let local = self.declare_local(&name)?;
array_destructure_locals.push(local);
}
is_object_destructure = false;
is_array_destructure = true;
}
shape_ast::ast::Pattern::Wildcard => {
elem_local = self.declare_local("__discard")?;
is_object_destructure = false;
}
_ => {
return Err(ShapeError::RuntimeError {
message: "VM for-expr only supports identifier, object, and array destructure patterns"
.to_string(),
location: None,
});
}
}
self.apply_binding_semantics_to_value_pattern_bindings(
&for_expr.pattern,
Self::owned_mutable_binding_semantics(),
);
// Phase 3e: propagate iterator element type to the loop variable
// for the simple identifier-pattern form. Same fix as
// `compile_for_loop`; `for x in arr` over `Array<int>` now
// declares `x` with tracker type `int` so `sum + x` emits
// `AddInt` rather than falling into trait dispatch.
if let shape_ast::ast::Pattern::Identifier(_) = &for_expr.pattern {
if let Some(elem_type) = self.iter_element_type_name(&for_expr.iterable) {
self.set_local_type_info(elem_local, &elem_type);
}
}
let loop_start = self.program.current_offset();
self.emit(Instruction::simple(OpCode::LoopStart));
self.emit(Instruction::simple(OpCode::Dup));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(idx_local)),
));
self.emit(Instruction::simple(OpCode::IterDone));
let exit_jump = self.emit_jump(OpCode::JumpIfTrue, 0);
self.emit(Instruction::simple(OpCode::Dup));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(idx_local)),
));
self.emit(Instruction::simple(OpCode::IterNext));
// For `for await`, each element is a Future — await it before binding
if for_expr.is_async {
self.emit(Instruction::simple(OpCode::Await));
}
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(elem_local)),
));
// Object destructuring: extract fields from the element.
if is_object_destructure {
for (key, local) in &destructure_fields {
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(elem_local)),
));
let key_const = self.program.add_constant(Constant::String(key.to_string()));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(key_const)),
));
self.emit(Instruction::simple(OpCode::GetProp));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(*local)),
));
}
}
// Array destructuring: extract elements by index.
if is_array_destructure {
for (idx, local) in array_destructure_locals.iter().enumerate() {
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(elem_local)),
));
let idx_const = self.program.add_constant(Constant::Number(idx as f64));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(idx_const)),
));
self.emit(Instruction::simple(OpCode::GetProp));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(*local)),
));
}
}
// Increment index before body so continue jumps advance correctly
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(idx_local)),
));
let one_const = self.program.add_constant(Constant::Int(1));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(one_const)),
));
self.emit(Instruction::simple(OpCode::AddInt));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(idx_local)),
));
self.loop_stack.push(LoopContext {
break_jumps: Vec::new(),
continue_target: loop_start,
break_value_local: Some(result_local),
iterator_on_stack: true,
drop_scope_depth: self.drop_locals.len(),
continue_jumps: Vec::new(),
});
self.push_repeating_reference_release_barrier();
let body_result = self.compile_expr(&for_expr.body);
self.pop_repeating_reference_release_barrier();
body_result?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(result_local)),
));
let offset = loop_start as i32 - self.program.current_offset() as i32 - 1;
self.emit(Instruction::new(
OpCode::Jump,
Some(Operand::Offset(offset)),
));
self.emit(Instruction::simple(OpCode::LoopEnd));
self.patch_jump(exit_jump);
self.emit(Instruction::simple(OpCode::Pop));
if let Some(loop_ctx) = self.loop_stack.pop() {
for break_jump in loop_ctx.break_jumps {
self.patch_jump(break_jump);
}
}
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(result_local)),
));
self.pop_scope();
Ok(())
}
pub(super) fn compile_loop_expr(&mut self, loop_expr: &shape_ast::ast::LoopExpr) -> Result<()> {
self.push_scope();
let result_local = self.declare_local("__loop_result")?;
self.emit(Instruction::simple(OpCode::PushNull));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(result_local)),
));
let loop_start = self.program.current_offset();
self.emit(Instruction::simple(OpCode::LoopStart));
self.loop_stack.push(LoopContext {
break_jumps: Vec::new(),
continue_target: loop_start,
break_value_local: Some(result_local),
iterator_on_stack: false,
drop_scope_depth: self.drop_locals.len(),
continue_jumps: Vec::new(),
});
self.push_repeating_reference_release_barrier();
let body_result = self.compile_expr(&loop_expr.body);
self.pop_repeating_reference_release_barrier();
body_result?;
// Discard the body value; break expressions store their values
// to result_local themselves. We must Pop here so the stack
// doesn't grow on each iteration.
self.emit(Instruction::simple(OpCode::Pop));
let offset = loop_start as i32 - self.program.current_offset() as i32 - 1;
self.emit(Instruction::new(
OpCode::Jump,
Some(Operand::Offset(offset)),
));
self.emit(Instruction::simple(OpCode::LoopEnd));
if let Some(loop_ctx) = self.loop_stack.pop() {
for break_jump in loop_ctx.break_jumps {
self.patch_jump(break_jump);
}
}
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(result_local)),
));
self.pop_scope();
Ok(())
}
/// W16.2-C (Round 6 WS-1, 2026-05-21) — resolve the [`TypedArrayKind`]
/// of a list-comprehension element expression that just compiled.
///
/// Reads, in order:
/// 1. `last_expr_numeric_type` — set when the element is a numeric
/// literal / operation (covers `x * 2`, `x + 1`, range-counter
/// loop variables which the range specialization types as `int`).
/// 2. `last_expr_type_info`'s `storage_hint` — covers the `bool`
/// case (a comparison result clears `last_expr_numeric_type` but
/// stamps `StorageHint::Bool`).
/// 3. `concrete_type_for_expr` on the element AST — covers a bare
/// identifier loop variable bound by a generic-iterator clause
/// (`[x for x in src]`), where the kind lives in the type tracker.
///
/// Per ADR-006 §2.7.5 every signal is a producer-side type proof set
/// when the element compiled (or a structural type-tracker fact) —
/// never fabricated, never decoded from runtime bits. Returns `None`
/// when no scalar kind is proven; the caller surfaces a clean compile
/// error.
fn resolve_pushed_element_typed_array_kind(
&self,
element: &Expr,
) -> Option<super::v2_typed_emission::TypedArrayKind> {
use super::monomorphization::type_resolution::concrete_type_for_expr;
use super::v2_typed_emission::{
should_use_typed_array, typed_array_kind_from_numeric_type,
TypedArrayKind,
};
if let Some(nt) = self.last_expr_numeric_type {
return Some(typed_array_kind_from_numeric_type(nt));
}
if let Some(info) = &self.last_expr_type_info {
if info.storage_hint == Some(crate::type_tracking::NativeKind::Bool) {
return Some(TypedArrayKind::Bool);
}
}
// Structural fallback — a bare identifier whose tracked type is a
// scalar (the generic-iterator loop variable case).
concrete_type_for_expr(self, element).and_then(|ct| should_use_typed_array(&ct))
}
pub(super) fn compile_list_comprehension(
&mut self,
comp: &shape_ast::ast::ListComprehension,
) -> Result<()> {
self.push_scope();
let result_local = self.declare_local("__comp_result")?;
// W16.2-C (Round 6 WS-1, 2026-05-21): the result accumulator MUST be
// a v2 typed array — `op_array_push` only accepts a
// `Ptr(HeapKind::TypedArray)` receiver, and there is no untyped
// runtime array carrier. The element kind is proven only AFTER the
// body compiles, so emit a placeholder allocator here, record its
// instruction index, then patch it once
// `compile_comprehension_clauses` writes the proven
// `comprehension_element_kind`. Per ADR-006 §2.7.5 the kind is
// stamped at the producer site (the compiled element expression) —
// never decoded from runtime bits, never Bool-defaulted.
let alloc_instr_idx = self.program.instructions.len();
self.emit(Instruction::new(OpCode::NewArray, Some(Operand::Count(0))));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(result_local)),
));
// Save/restore both comprehension-scoped fields so a nested
// comprehension (`[[y for y in r] for x in ...]`) does not bleed
// its element kind / push sites into the enclosing one.
let saved_element_kind = self.comprehension_element_kind.take();
let saved_push_sites = std::mem::take(&mut self.comprehension_push_sites);
self.compile_comprehension_clauses(&comp.element, &comp.clauses, result_local, 0)?;
let element_kind = self.comprehension_element_kind.take();
let push_sites = std::mem::take(&mut self.comprehension_push_sites);
self.comprehension_element_kind = saved_element_kind;
self.comprehension_push_sites = saved_push_sites;
match element_kind {
Some(kind) => {
// Patch the placeholder allocator with the resolved typed
// allocator (capacity 0). Record the typed-array kind
// against the result slot so downstream `.method()`
// dispatch resolves the carrier.
self.program.instructions[alloc_instr_idx] =
Instruction::new(kind.new_opcode(), Some(Operand::Count(0)));
// Patch every element-push site to the matching typed
// `TypedArrayPush*` opcode — the typed push unambiguously
// identifies the v2 typed-array carrier for both the VM
// and JIT (no generic-carrier slot-kind ambiguity).
for &site in &push_sites {
self.program.instructions[site] =
Instruction::simple(kind.push_opcode());
}
self.v2_typed_array_locals.insert(result_local, kind);
// Signal the typed-array kind to the enclosing `let c = [...]`
// binding path (`Statement::VarDecl`), which records it
// against the destination slot via
// `pending_variable_typed_array_kind` — the same hand-off
// `compile_expr_array` uses for bare typed literals. Without
// this the destination binding is untyped and `.len()` /
// method dispatch on it falls to the generic carrier path.
self.pending_variable_typed_array_kind = Some(kind);
}
None => {
return Err(ShapeError::SemanticError {
message: "list comprehension element type could not be \
determined at compile time. Strict typing \
requires the element expression to have a \
proven scalar type (int / number / bool / \
decimal / sized integer). Annotate the \
comprehension's source so the element type \
resolves."
.to_string(),
location: None,
});
}
}
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(result_local)),
));
// The comprehension body compiled the element expression, leaving
// `last_expr_numeric_type` stamped with the ELEMENT's scalar type
// (e.g. `Int` for `[x for x in 0..5]`). If left set, the enclosing
// `let c = [...]` binding's `propagate_initializer_type_to_slot`
// would record `c` as a bare `int`, mis-stamping the method-call
// receiver tag. Reset to the array shape — mirrors the tail of
// `compile_expr_array`.
if let Some(kind) = element_kind {
self.last_expr_type_info = Some(
crate::type_tracking::VariableTypeInfo::named(
super::v2_typed_emission::vec_type_name_for_typed_array_kind(kind)
.to_string(),
),
);
} else {
self.last_expr_type_info = None;
}
self.last_expr_numeric_type = None;
self.last_expr_schema = None;
self.pop_scope();
Ok(())
}
pub(super) fn compile_comprehension_clauses(
&mut self,
element: &Expr,
clauses: &[shape_ast::ast::ComprehensionClause],
result_local: u16,
depth: usize,
) -> Result<()> {
if clauses.is_empty() {
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(result_local)),
));
self.compile_expr(element)?;
// W16.2-C (Round 6 WS-1): capture the proven element kind for
// `compile_list_comprehension` to patch the accumulator
// allocator with the matching typed `NewTypedArray*` opcode. The
// element expression has just compiled — `last_expr_numeric_type`
// / `last_expr_type_info` carry the producer-side type proof per
// ADR-006 §2.7.5. A `bool`-typed element (comparison result)
// surfaces via `last_expr_type_info.storage_hint == Bool`.
let resolved_kind = self.resolve_pushed_element_typed_array_kind(element);
// Every base-case visit compiles the SAME element expression, so
// the resolved kind is identical across loop/filter clauses;
// recording it once is sufficient. If a later visit somehow
// disagrees, downgrade to `None` (un-provable) rather than
// silently picking one.
match (self.comprehension_element_kind, resolved_kind) {
(None, k) => self.comprehension_element_kind = k,
(Some(prev), Some(k)) if prev == k => {}
(Some(_), _) => self.comprehension_element_kind = None,
}
// Emit a placeholder `ArrayPush` and record its index.
// `compile_list_comprehension` patches it to the matching
// `TypedArrayPush*` opcode once the element kind is resolved.
// The typed push pops `[arr, val]` and pushes nothing back
// (the `TypedArray<T>` struct pointer is stable across the
// in-place `TypedArray::push` — only the inner data buffer
// reallocs), so NO `StoreLocal` re-store is emitted: the
// accumulator slot already holds the stable pointer. The
// placeholder `ArrayPush` is never executed — it is always
// patched before the program runs (or the comprehension
// fails to compile).
self.comprehension_push_sites
.push(self.program.instructions.len());
self.emit(Instruction::simple(OpCode::ArrayPush));
return Ok(());
}
let clause = &clauses[0];
// Try range counter specialization for this comprehension clause
if let Some(rcl) = self.try_begin_range_counter_loop(
clause.pattern.as_identifier(),
&clause.iterable,
)? {
self.apply_binding_semantics_to_pattern_bindings(
&clause.pattern,
true,
Self::owned_mutable_binding_semantics(),
);
if let Some(filter) = &clause.filter {
self.compile_expr(filter)?;
let skip_jump = self.emit_jump(OpCode::JumpIfFalse, 0);
self.compile_comprehension_clauses(
element,
&clauses[1..],
result_local,
depth + 1,
)?;
self.patch_jump(skip_jump);
} else {
self.compile_comprehension_clauses(
element,
&clauses[1..],
result_local,
depth + 1,
)?;
}
// No LoopContext for comprehensions (no break/continue),
// so end_range_counter_loop just emits increment + jump + patch.
self.end_range_counter_loop(&rcl);
return Ok(());
}
// === Generic iterator path (unchanged) ===
self.compile_expr(&clause.iterable)?;
let iter_local = self.declare_local(&format!("__comp_iter_{depth}"))?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(iter_local)),
));
let idx_local = self.declare_local(&format!("__comp_idx_{depth}"))?;
let zero_const = self.program.add_constant(Constant::Int(0));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(zero_const)),
));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(idx_local)),
));
let loop_start = self.program.current_offset();
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(iter_local)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(idx_local)),
));
self.emit(Instruction::simple(OpCode::IterDone));
let exit_jump = self.emit_jump(OpCode::JumpIfTrue, 0);
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(iter_local)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(idx_local)),
));
self.emit(Instruction::simple(OpCode::IterNext));
self.compile_destructure_pattern(&clause.pattern)?;
self.apply_binding_semantics_to_pattern_bindings(
&clause.pattern,
true,
Self::owned_mutable_binding_semantics(),
);
// W16.2-C (Round 6 WS-1, 2026-05-21): type the comprehension loop
// variable from the iterable's element type — mirrors the `for x in
// iter` loop-variable typing (`compile_for_loop` `iter_element_type
// _name` + `set_local_type_info`). Without this, `[x for x in arr]`
// leaves `x` untyped and `resolve_pushed_element_typed_array_kind`
// cannot prove the comprehension's element kind. Per ADR-006 §2.7.5
// the iterable's tracked `Array<T>` element type IS the proof.
if let (Some(loop_var), Some(elem_type)) = (
clause.pattern.as_identifier(),
self.iter_element_type_name(&clause.iterable),
) {
if let Some(local_idx) = self.resolve_local(loop_var) {
self.set_local_type_info(local_idx, &elem_type);
}
}
if let Some(filter) = &clause.filter {
self.compile_expr(filter)?;
let skip_jump = self.emit_jump(OpCode::JumpIfFalse, 0);
self.compile_comprehension_clauses(element, &clauses[1..], result_local, depth + 1)?;
self.patch_jump(skip_jump);
} else {
self.compile_comprehension_clauses(element, &clauses[1..], result_local, depth + 1)?;
}
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(idx_local)),
));
let one_const = self.program.add_constant(Constant::Int(1));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(one_const)),
));
self.emit(Instruction::simple(OpCode::AddInt));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(idx_local)),
));
let offset = loop_start as i32 - self.program.current_offset() as i32 - 1;
self.emit(Instruction::new(
OpCode::Jump,
Some(Operand::Offset(offset)),
));
self.patch_jump(exit_jump);
Ok(())
}
/// W16.2-C (Round 6 WS-1, 2026-05-21) — resolve the homogeneous
/// [`TypedArrayKind`] of an array-spread literal's elements.
///
/// Walks every element of `[...src, tail, ...]`: a `...src` spread
/// contributes `src`'s array-element type (a `0..n` range spread
/// contributes `int`); a bare element contributes its own type. The
/// accumulator kind is the single kind every element agrees on. Returns
/// `None` for a genuinely heterogeneous literal (e.g. `[...intArr,
/// "str"]`) or an element whose type is not statically provable — the
/// caller surfaces a clean compile error. Per ADR-006 §2.7.5 every kind
/// is proven structurally at the producer site; no runtime inference.
fn resolve_spread_accumulator_kind(
&self,
elements: &[Expr],
) -> Option<super::v2_typed_emission::TypedArrayKind> {
use super::monomorphization::type_resolution::concrete_type_for_expr;
use super::v2_typed_emission::should_use_typed_array;
use shape_value::v2::ConcreteType;
let mut acc: Option<super::v2_typed_emission::TypedArrayKind> = None;
for elem in elements {
let elem_kind = match elem {
Expr::Spread(inner, _) => {
// A `0..n` / `0..=n` range spread yields `int` counters.
if let Expr::Range {
start: Some(_),
end: Some(_),
..
} = inner.as_ref()
{
Some(super::v2_typed_emission::TypedArrayKind::I64)
} else {
// Any other spread source must be an `Array<T>`;
// its element type is the contributed kind.
match concrete_type_for_expr(self, inner) {
Some(ConcreteType::Array(inner_ct)) => {
should_use_typed_array(&inner_ct)
}
_ => None,
}
}
}
_ => concrete_type_for_expr(self, elem)
.and_then(|ct| should_use_typed_array(&ct)),
};
let elem_kind = elem_kind?;
match acc {
None => acc = Some(elem_kind),
Some(prev) if prev == elem_kind => {}
// Heterogeneous element kinds — not a typed-array literal.
Some(_) => return None,
}
}
acc
}
pub(super) fn compile_array_with_spread(&mut self, elements: &[Expr]) -> Result<()> {
self.push_scope();
// W16.2-C (Round 6 WS-1): the spread accumulator MUST be a v2 typed
// array — `op_array_push` rejects any non-`Ptr(HeapKind::TypedArray)`
// receiver. Resolve the homogeneous element kind structurally before
// emission (per ADR-006 §2.7.5 the producer-side proof is the spread
// sources' / tail elements' statically-known `ConcreteType`s).
let accumulator_kind = self.resolve_spread_accumulator_kind(elements);
let result_local = self.declare_local("__array_result")?;
match accumulator_kind {
Some(kind) => {
self.emit(Instruction::new(
kind.new_opcode(),
Some(Operand::Count(0)),
));
self.v2_typed_array_locals.insert(result_local, kind);
// Signal the kind to the enclosing `let b = [...spread]`
// binding path so the destination slot is recorded as a
// typed array (mirrors `compile_expr_array`).
self.pending_variable_typed_array_kind = Some(kind);
}
None => {
return Err(ShapeError::SemanticError {
message: "array spread element types could not be \
reconciled at compile time. Strict typing \
requires every spread source and bare element \
to share one proven scalar element type \
(int / number / bool / decimal / sized \
integer). A heterogeneous spread literal is \
not supported."
.to_string(),
location: None,
});
}
}
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(result_local)),
));
for (idx, elem) in elements.iter().enumerate() {
match elem {
Expr::Spread(inner, _) => {
// Try range counter specialization for spread-over-range
if let Expr::Range {
start: Some(start_expr),
end: Some(end_expr),
kind,
..
} = inner.as_ref()
{
let inclusive = *kind == RangeKind::Inclusive;
let counter_local =
self.declare_local(&format!("__spread_counter_{idx}"))?;
let end_local = self.declare_local(&format!("__spread_end_{idx}"))?;
// Compile start → [NumberToInt if float] → store
self.compile_expr(start_expr)?;
let start_nt = self.last_expr_numeric_type;
if matches!(start_nt, Some(NumericType::Number)) {
self.emit(Instruction::simple(OpCode::NumberToInt));
}
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(counter_local)),
));
// Compile end → [NumberToInt if float] → store
self.compile_expr(end_expr)?;
let end_nt = self.last_expr_numeric_type;
if matches!(end_nt, Some(NumericType::Number)) {
self.emit(Instruction::simple(OpCode::NumberToInt));
}
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(end_local)),
));
let loop_start = self.program.current_offset();
// counter < end (or <=) — always int after NumberToInt coercion
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(counter_local)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(end_local)),
));
self.emit(Instruction::simple(if inclusive {
OpCode::LteInt
} else {
OpCode::LtInt
}));
let exit_jump = self.emit_jump(OpCode::JumpIfFalse, 0);
// Push counter value to result array
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(result_local)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(counter_local)),
));
self.emit(Instruction::simple(OpCode::ArrayPush));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(result_local)),
));
// Increment counter
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(counter_local)),
));
// Counter is always int (range endpoints coerced to int)
let one_const = self.program.add_constant(Constant::Int(1));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(one_const)),
));
self.emit(Instruction::simple(OpCode::AddInt));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(counter_local)),
));
let offset =
loop_start as i32 - self.program.current_offset() as i32 - 1;
self.emit(Instruction::new(
OpCode::Jump,
Some(Operand::Offset(offset)),
));
self.patch_jump(exit_jump);
} else {
// Generic iterator path for non-range spreads
self.plan_flexible_binding_escape_from_expr(inner);
self.compile_expr(inner)?;
let iter_local =
self.declare_local(&format!("__spread_iter_{idx}"))?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(iter_local)),
));
let idx_local =
self.declare_local(&format!("__spread_idx_{idx}"))?;
let zero_const = self.program.add_constant(Constant::Int(0));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(zero_const)),
));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(idx_local)),
));
let loop_start = self.program.current_offset();
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(iter_local)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(idx_local)),
));
self.emit(Instruction::simple(OpCode::IterDone));
let exit_jump = self.emit_jump(OpCode::JumpIfTrue, 0);
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(result_local)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(iter_local)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(idx_local)),
));
self.emit(Instruction::simple(OpCode::IterNext));
self.emit(Instruction::simple(OpCode::ArrayPush));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(result_local)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(idx_local)),
));
let one_const = self.program.add_constant(Constant::Int(1));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(one_const)),
));
self.emit(Instruction::simple(OpCode::AddInt));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(idx_local)),
));
let offset =
loop_start as i32 - self.program.current_offset() as i32 - 1;
self.emit(Instruction::new(
OpCode::Jump,
Some(Operand::Offset(offset)),
));
self.patch_jump(exit_jump);
}
}
_ => {
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(result_local)),
));
self.plan_flexible_binding_escape_from_expr(elem);
self.compile_expr(elem)?;
self.emit(Instruction::simple(OpCode::ArrayPush));
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(result_local)),
));
}
}
}
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(result_local)),
));
// Reset `last_expr_*` to the array shape so the enclosing
// `let b = [...spread]` binding records `b` as an array, not as
// the bare element scalar the last spread element left behind.
if let Some(kind) = accumulator_kind {
self.last_expr_type_info = Some(
crate::type_tracking::VariableTypeInfo::named(
super::v2_typed_emission::vec_type_name_for_typed_array_kind(kind)
.to_string(),
),
);
} else {
self.last_expr_type_info = None;
}
self.last_expr_numeric_type = None;
self.last_expr_schema = None;
self.pop_scope();
Ok(())
}
/// Phase 3e helper: infer the element type name of a `for x in ITER`
/// iterator expression.
///
/// Currently handles:
/// - Identifier referring to a tracked typed array (`Vec<T>` /
/// `Array<T>` tracker name) — returns the inner type name.
/// - Array literal — peeks the first element and uses its
/// literal kind.
///
/// Returns `None` for iterators whose element type can't be proven at
/// compile time (HashMap iteration, custom iterables, untyped arrays).
pub(super) fn iter_element_type_name(&self, iter: &Expr) -> Option<String> {
match iter {
Expr::Identifier(name, _) => {
let type_name = if let Some(local_idx) = self.resolve_local(name) {
self.type_tracker
.get_local_type(local_idx)?
.type_name
.clone()?
} else if let Some(scoped) = self.resolve_scoped_module_binding_name(name) {
let binding_idx = *self.module_bindings.get(&scoped)?;
self.type_tracker
.get_binding_type(binding_idx)?
.type_name
.clone()?
} else {
return None;
};
Self::array_type_name_inner(&type_name)
}
Expr::Array(elems, _) => {
let first = elems.first()?;
match first {
Expr::Literal(shape_ast::ast::Literal::Int(_), _) => {
Some("int".to_string())
}
Expr::Literal(shape_ast::ast::Literal::Number(_), _) => {
Some("number".to_string())
}
Expr::Literal(shape_ast::ast::Literal::Bool(_), _) => {
Some("bool".to_string())
}
Expr::Literal(shape_ast::ast::Literal::String(_), _) => {
Some("string".to_string())
}
_ => None,
}
}
_ => None,
}
}
/// Strip an `Array<T>` / `Vec<T>` wrapper to recover the element type
/// name. Returns `None` for non-array tracker names.
fn array_type_name_inner(name: &str) -> Option<String> {
let trimmed = name.trim();
let inner = trimmed
.strip_prefix("Vec<")
.or_else(|| trimmed.strip_prefix("Array<"))?
.strip_suffix('>')?;
Some(inner.trim().to_string())
}
}
// ADR-006 §2.7.4 — Phase 2c rebuild (R8 C1-temporal-lowering, 2026-05-23).
//
// The original suite asserted via `shape_value::ValueWordExt::as_i64`
// against a `vm.execute(None) -> ValueWord` return. Post-strict-typing,
// `VirtualMachine::execute(None) -> Result<KindedSlot, VMError>` and
// `KindedSlot` exposes intrinsic per-kind accessors (`as_i64`, `as_f64`,
// `as_bool`, `as_str`) per §2.7.6 / Q8. The migration drops the deleted
// `ValueWordExt` trait import; every accessor body is byte-identical to
// the pre-W-series shape because the kinded API was designed to be a
// drop-in replacement for the deleted tagged-bits accessors.
#[cfg(test)]
mod tests {
use crate::VMConfig;
use crate::compiler::BytecodeCompiler;
use crate::executor::VirtualMachine;
use shape_ast::parser::parse_program;
fn compile_and_run_i64(code: &str) -> i64 {
let program = parse_program(code).unwrap();
let mut compiler = BytecodeCompiler::new();
compiler.allow_internal_builtins = true;
let bytecode = compiler.compile(&program).unwrap();
let mut vm = VirtualMachine::new(VMConfig::default());
vm.load_program(bytecode);
vm.execute(None)
.unwrap()
.as_i64()
.expect("expected i64 top-level return")
}
#[test]
fn test_range_loop_exclusive() {
let result = compile_and_run_i64(
"fn t() { let mut s = 0; for i in 0..5 { s = s + i }; s } t()",
);
assert_eq!(result, 10);
}
#[test]
fn test_range_loop_inclusive() {
let result = compile_and_run_i64(
"fn t() { let mut s = 0; for i in 0..=5 { s = s + i }; s } t()",
);
assert_eq!(result, 15);
}
#[test]
fn test_range_loop_empty() {
let result = compile_and_run_i64(
"fn t() { let mut s = 0; for i in 5..0 { s = s + i }; s } t()",
);
assert_eq!(result, 0);
}
#[test]
fn test_range_loop_break() {
let result = compile_and_run_i64(
"fn t() { let mut s = 0; for i in 0..100 { if i == 5 { break }; s = s + i }; s } t()",
);
assert_eq!(result, 10);
}
#[test]
fn test_range_loop_continue() {
let result = compile_and_run_i64(
"fn t() { let mut s = 0; for i in 0..10 { if i % 2 == 0 { continue }; s = s + i }; s } t()",
);
assert_eq!(result, 25);
}
#[test]
fn test_range_loop_no_makerange() {
// Range-counter loops compile to a direct increment-and-compare
// pattern; they must NOT emit MakeRange/IterDone (which would
// allocate a Range heap value).
let code = "fn t() { let mut s = 0; for i in 0..10 { s = s + i }; s }";
let program = parse_program(code).unwrap();
let bytecode = BytecodeCompiler::new().compile(&program).unwrap();
let opcodes: Vec<_> = bytecode.instructions.iter().map(|i| i.opcode).collect();
assert!(
!opcodes.contains(&crate::bytecode::OpCode::MakeRange),
"Range counter loop must not emit MakeRange"
);
assert!(
!opcodes.contains(&crate::bytecode::OpCode::IterDone),
"Range counter loop must not emit IterDone"
);
}
#[test]
fn test_range_loop_for_expr() {
let result = compile_and_run_i64(
"fn t() { let r = for i in 0..5 { i * 2 }; r } t()",
);
assert_eq!(result, 8);
}
#[test]
fn test_range_loop_comprehension() {
let result = compile_and_run_i64(
"fn t() { let a = [i * 2 for i in 0..5]; a.len() } t()",
);
assert_eq!(result, 5);
}
#[test]
fn test_range_loop_spread() {
let result = compile_and_run_i64(
"fn t() { let a = [...0..5]; a.len() } t()",
);
assert_eq!(result, 5);
}
#[test]
fn test_non_range_fallback() {
let result = compile_and_run_i64(
"fn t() { let mut s = 0; for x in [10, 20, 30] { s = s + x }; s } t()",
);
assert_eq!(result, 60);
}
}