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
//! Bytecode compiler - translates AST to bytecode
use shape_ast::error::{Result, ShapeError, SourceLocation};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crate::blob_cache_v2::BlobCache;
/// Borrow mode for reference parameters - Shared (&) or Exclusive (&mut).
/// Kept for codegen even though the lexical borrow checker has been removed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BorrowMode {
Shared,
Exclusive,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ExprResultMode {
Value,
PreserveRef,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct ExprReferenceResult {
pub raw_mode: Option<BorrowMode>,
pub auto_deref_mode: Option<BorrowMode>,
}
/// A borrow place key used for encoding borrow targets in codegen.
pub type BorrowPlace = u32;
use crate::bytecode::{
BuiltinFunction, BytecodeProgram, Constant, FunctionBlob, FunctionHash, Instruction, OpCode,
Operand, Program as ContentAddressedProgram,
};
use crate::type_tracking::{TypeTracker, VariableTypeInfo};
use shape_ast::ast::{FunctionDef, Program, Span, TypeAnnotation};
use shape_runtime::type_schema::SchemaId;
use shape_runtime::type_system::{
Type, TypeAnalysisMode, TypeError, TypeErrorWithLocation, analyze_program_with_mode,
checking::MethodTable,
};
// Sub-modules
pub(crate) mod comptime;
pub(crate) mod comptime_builtins;
pub(crate) mod comptime_concrete;
pub(crate) mod comptime_target;
mod control_flow;
mod expressions;
mod functions;
mod functions_annotations;
mod functions_foreign;
mod helpers;
mod helpers_binding;
mod helpers_reference;
mod literals;
mod loops;
pub(crate) mod mir_schema_threading;
pub(crate) mod monomorphization;
mod patterns;
pub(crate) mod post_inference_verify;
mod statements;
pub mod string_interpolation;
mod trait_object_emission;
/// Loop compilation context
pub(crate) struct LoopContext {
/// Break jump targets
pub(crate) break_jumps: Vec<usize>,
/// Continue jump target (usize::MAX = deferred, use continue_jumps)
pub(crate) continue_target: usize,
/// Optional local to store break values for expression loops
pub(crate) break_value_local: Option<u16>,
/// Whether a for-in iterator is on the stack (break must pop it)
pub(crate) iterator_on_stack: bool,
/// Drop scope depth when the loop was entered (for break/continue early exit drops)
pub(crate) drop_scope_depth: usize,
/// Forward-patched continue jumps for range counter loops where the
/// increment block is after the body (so continue must forward-jump).
pub(crate) continue_jumps: Vec<usize>,
}
/// Information about an imported symbol (fields used for diagnostics/LSP)
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct ImportedSymbol {
/// Original name in the source module
pub original_name: String,
/// Module path the symbol was imported from
pub module_path: String,
/// High-level kind of the imported symbol (function, type, etc.)
/// `None` for legacy inlining path where kind is not tracked.
pub kind: Option<shape_ast::module_utils::ModuleExportKind>,
}
/// Imported annotation binding routed through a hidden synthetic module.
#[derive(Debug, Clone)]
pub(crate) struct ImportedAnnotationSymbol {
/// Original annotation name in the source module.
pub original_name: String,
/// Source module path the annotation was imported from.
pub _module_path: String,
/// Hidden synthetic module name that owns the compiled annotation scope.
pub hidden_module_name: String,
}
/// Module-scoped builtin function declaration with a runtime source module.
#[derive(Debug, Clone)]
pub(crate) struct ModuleBuiltinFunction {
/// The callable name as exported by the runtime/native module.
pub export_name: String,
/// Original source module path that provides the runtime implementation.
pub source_module_path: String,
}
/// Compiler-internal scope taxonomy for name resolution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
pub(crate) enum ResolutionScope {
Local,
ModuleBinding,
NamedImport,
NamespaceImport,
TypeAssociated,
Prelude,
SyntaxReserved,
InternalIntrinsic,
}
impl ResolutionScope {
pub(crate) const fn label(self) -> &'static str {
match self {
Self::Local => "local scope",
Self::ModuleBinding => "module scope",
Self::NamedImport => "named import scope",
Self::NamespaceImport => "namespace import scope",
Self::TypeAssociated => "type-associated scope",
Self::Prelude => "implicit prelude scope",
Self::SyntaxReserved => "syntax-reserved scope",
Self::InternalIntrinsic => "internal intrinsic scope",
}
}
}
/// Builtin lookup result annotated with the scope class it currently belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BuiltinNameResolution {
Surface {
builtin: BuiltinFunction,
scope: ResolutionScope,
},
InternalOnly {
builtin: BuiltinFunction,
scope: ResolutionScope,
},
}
impl BuiltinNameResolution {
pub(crate) const fn scope(self) -> ResolutionScope {
match self {
Self::Surface { scope, .. } | Self::InternalOnly { scope, .. } => scope,
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct StructGenericInfo {
pub type_params: Vec<shape_ast::ast::TypeParam>,
pub runtime_field_types: HashMap<String, shape_ast::ast::TypeAnnotation>,
}
/// Whether a type's Drop impl is sync-only, async-only, or both.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DropKind {
SyncOnly,
AsyncOnly,
Both,
}
/// Canonical compile-time parameter passing contract.
///
/// This is the single source of truth used by compiler lowering and LSP rendering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParamPassMode {
ByValue,
ByRefShared,
ByRefExclusive,
}
impl ParamPassMode {
pub const fn is_reference(self) -> bool {
!matches!(self, Self::ByValue)
}
pub const fn is_exclusive(self) -> bool {
matches!(self, Self::ByRefExclusive)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FunctionReturnReferenceSummary {
pub param_index: usize,
pub mode: BorrowMode,
pub projection: Option<Vec<crate::mir::types::ProjectionStep>>,
}
impl From<crate::mir::analysis::ReturnReferenceSummary> for FunctionReturnReferenceSummary {
fn from(value: crate::mir::analysis::ReturnReferenceSummary) -> Self {
Self {
param_index: value.param_index,
mode: match value.kind {
crate::mir::types::BorrowKind::Shared => BorrowMode::Shared,
crate::mir::types::BorrowKind::Exclusive => BorrowMode::Exclusive,
},
projection: value.projection,
}
}
}
/// Per-function blob builder for content-addressed compilation.
///
/// Uses a **snapshot** strategy: records the global instruction/constant/string
/// pool sizes at the start of function compilation, then at finalization
/// extracts the delta and remaps global indices to blob-local indices.
pub(crate) struct FunctionBlobBuilder {
/// Function name.
pub name: String,
/// Global instruction index where this function's code starts.
pub instr_start: usize,
/// Global constant pool size when this function started compiling.
#[allow(dead_code)]
pub const_start: usize,
/// Global string pool size when this function started compiling.
#[allow(dead_code)]
pub string_start: usize,
/// Names of functions called by this function (for dependency tracking).
pub called_functions: Vec<String>,
/// Type schema names this function constructs.
pub type_schemas: Vec<String>,
/// Accumulated permissions required by this function's direct calls.
pub required_permissions: shape_abi_v1::PermissionSet,
}
impl FunctionBlobBuilder {
pub fn new(name: String, instr_start: usize, const_start: usize, string_start: usize) -> Self {
Self {
name,
instr_start,
const_start,
string_start,
called_functions: Vec::new(),
type_schemas: Vec::new(),
required_permissions: shape_abi_v1::PermissionSet::pure(),
}
}
/// Record that this function calls another function by name.
pub fn record_call(&mut self, callee_name: &str) {
if !self.called_functions.iter().any(|n| n == callee_name) {
self.called_functions.push(callee_name.to_owned());
}
}
/// Record that this function requires the given permissions
/// (e.g., from a stdlib module call identified by capability_tags).
pub fn record_permissions(&mut self, perms: &shape_abi_v1::PermissionSet) {
self.required_permissions = self.required_permissions.union(perms);
}
/// Finalize this builder into a FunctionBlob by extracting the delta from
/// the global program pools and remapping indices to blob-local ones.
pub fn finalize(
&self,
program: &crate::bytecode::BytecodeProgram,
func: &crate::bytecode::Function,
blob_name_to_hash: &HashMap<String, FunctionHash>,
instr_end: usize,
) -> FunctionBlob {
use crate::bytecode::Operand;
// Extract global-indexed instructions for this function.
let global_instructions = &program.instructions[self.instr_start..instr_end];
// Build constant remap: global index -> local index.
let mut const_remap: HashMap<u16, u16> = HashMap::new();
let mut local_constants: Vec<Constant> = Vec::new();
// Build string remap similarly.
let mut string_remap: HashMap<u16, u16> = HashMap::new();
let mut local_strings: Vec<String> = Vec::new();
// Build function operand remap: global function index -> dependency-local index.
let mut func_remap: HashMap<u16, u16> = HashMap::new();
// Start from explicitly recorded call dependencies, then augment with
// function-value references found in constants/operands.
let mut called_functions = self.called_functions.clone();
let mut ensure_called = |callee_name: &str| -> u16 {
if let Some(dep_idx) = called_functions.iter().position(|n| n == callee_name) {
dep_idx as u16
} else {
called_functions.push(callee_name.to_owned());
(called_functions.len() - 1) as u16
}
};
// Scan instructions for all constant/string references and build
// blob-local pools with remapped indices.
for instr in global_instructions {
if let Some(ref operand) = instr.operand {
match operand {
Operand::Const(idx) => {
if !const_remap.contains_key(idx) {
let local_idx = local_constants.len() as u16;
const_remap.insert(*idx, local_idx);
let mut constant = program.constants[*idx as usize].clone();
if let Constant::Function(fid) = constant {
let global_idx = fid as usize;
if let Some(callee) = program.functions.get(global_idx) {
let dep_idx = ensure_called(&callee.name);
constant = Constant::Function(dep_idx);
}
}
local_constants.push(constant);
}
}
Operand::Property(idx) => {
if !string_remap.contains_key(idx) {
let local_idx = local_strings.len() as u16;
string_remap.insert(*idx, local_idx);
local_strings.push(program.strings[*idx as usize].clone());
}
}
Operand::Name(sid) => {
let gidx = sid.0 as u16;
if !string_remap.contains_key(&gidx) {
let local_idx = local_strings.len() as u16;
string_remap.insert(gidx, local_idx);
local_strings.push(program.strings[gidx as usize].clone());
}
}
Operand::TypedMethodCall { string_id, .. } => {
let gidx = *string_id;
if !string_remap.contains_key(&gidx) {
let local_idx = local_strings.len() as u16;
string_remap.insert(gidx, local_idx);
local_strings.push(program.strings[gidx as usize].clone());
}
}
Operand::Function(fid) => {
let global_idx = fid.0 as usize;
if !func_remap.contains_key(&fid.0) {
// Map global function index -> dependency-local index.
// If this call target was not explicitly recorded (e.g. emitted via
// function-valued constants), add it so content-addressed linking can
// remap stable function IDs correctly.
if let Some(callee) = program.functions.get(global_idx) {
let dep_idx = ensure_called(&callee.name);
func_remap.insert(fid.0, dep_idx);
}
}
}
// Closure spec H5: `MakeClosure` now carries the function id
// (plus the escape flag) in a `ClosureAlloc` operand when the
// closure escapes. Treat it exactly like `Operand::Function`
// for dependency tracking — the content-addressed blob must
// record the closure's compiled body as a dependency.
Operand::ClosureAlloc { fid, .. } => {
let global_idx = fid.0 as usize;
if !func_remap.contains_key(&fid.0) {
if let Some(callee) = program.functions.get(global_idx) {
let dep_idx = ensure_called(&callee.name);
func_remap.insert(fid.0, dep_idx);
}
}
}
_ => {}
}
}
}
// Remap instructions to use local indices.
let local_instructions: Vec<Instruction> = global_instructions
.iter()
.map(|instr| {
let mut remapped = instr.clone();
if let Some(operand) = &mut remapped.operand {
match operand {
Operand::Const(idx) => {
if let Some(&local) = const_remap.get(idx) {
*idx = local;
}
}
Operand::Property(idx) => {
if let Some(&local) = string_remap.get(idx) {
*idx = local;
}
}
Operand::Name(sid) => {
if let Some(&local) = string_remap.get(&(sid.0 as u16)) {
sid.0 = local as u32;
}
}
Operand::TypedMethodCall { string_id, .. } => {
if let Some(&local) = string_remap.get(string_id) {
*string_id = local;
}
}
Operand::Function(fid) => {
if let Some(&local) = func_remap.get(&fid.0) {
fid.0 = local;
}
}
// Closure spec H5: parallel remap for `ClosureAlloc`.
Operand::ClosureAlloc { fid, .. } => {
if let Some(&local) = func_remap.get(&fid.0) {
fid.0 = local;
}
}
_ => {}
}
}
remapped
})
.collect();
// Build dependency list from called function names.
// Use FunctionHash::ZERO as sentinel for forward references (not yet compiled).
let dependencies: Vec<FunctionHash> = called_functions
.iter()
.map(|callee| {
blob_name_to_hash
.get(callee)
.copied()
.unwrap_or(FunctionHash::ZERO)
})
.collect();
// Build source map from global debug info.
let source_map: Vec<(usize, u32, u32)> = program
.debug_info
.line_numbers
.iter()
.filter(|(idx, _, _)| *idx >= self.instr_start && *idx < instr_end)
.map(|(idx, fid, line)| (idx - self.instr_start, *fid as u32, *line))
.collect();
// Scan instructions for CallForeign operands and collect content hashes
// from the program's foreign_functions table.
let mut foreign_deps: Vec<[u8; 32]> = Vec::new();
for instr in &local_instructions {
if instr.opcode == crate::bytecode::OpCode::CallForeign {
if let Some(Operand::ForeignFunction(idx)) = instr.operand {
if let Some(entry) = program.foreign_functions.get(idx as usize) {
if let Some(hash) = entry.content_hash {
foreign_deps.push(hash);
}
}
}
}
}
foreign_deps.sort();
foreign_deps.dedup();
let mut blob = FunctionBlob {
content_hash: FunctionHash::ZERO,
name: self.name.clone(),
arity: func.arity,
param_names: func.param_names.clone(),
locals_count: func.locals_count,
is_closure: func.is_closure,
captures_count: func.captures_count,
is_async: func.is_async,
ref_params: func.ref_params.clone(),
ref_mutates: func.ref_mutates.clone(),
mutable_captures: func.mutable_captures.clone(),
frame_descriptor: func.frame_descriptor.clone(),
required_permissions: self.required_permissions.clone(),
instructions: local_instructions,
constants: local_constants,
strings: local_strings,
dependencies,
callee_names: called_functions,
type_schemas: self.type_schemas.clone(),
foreign_dependencies: foreign_deps,
source_map,
};
blob.finalize();
blob
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeDiagnosticMode {
ReliableOnly,
Strict,
RecoverAll,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompileDiagnosticMode {
FailFast,
RecoverAll,
}
/// cluster-2-cw-IB-class-b (2026-05-16, supervisor R3 binding-ratified):
/// retained closure-literal peek used to re-run body return-type
/// inference at the value-call site with caller-context arg type hints.
/// Stored per-local-slot in `BytecodeCompiler.local_callable_closure_bodies`
/// at let-binding time (`update_callable_binding_from_expr` /
/// `FunctionExpr` arm). The body is the AST `Vec<Statement>` clone — no
/// bytecode-lowering happens at lookup time; the inference walker only
/// inspects AST shape.
#[derive(Debug, Clone)]
pub struct ClosureBodyPeek {
/// Formal parameters of the closure literal (`|inner|` →
/// `[FunctionParameter { pattern: Identifier("inner"), .. }]`).
pub params: Vec<shape_ast::ast::FunctionParameter>,
/// Closure literal body statements.
pub body: Vec<shape_ast::ast::Statement>,
/// Explicit `-> T` return annotation, if any.
pub return_type: Option<shape_ast::ast::TypeAnnotation>,
/// Compiled-function index assigned to the closure body by
/// `compile_expr_closure`. `None` until the closure literal is
/// actually lowered (the peek is built from the AST; the function
/// index is assigned at compile-emission time). Used by the value-
/// call propagation path to retroactively patch
/// `mir.local_typed_array_element_types` for the closure body's
/// MIR-side typed-array param seed.
pub function_index: Option<usize>,
}
/// Phase 4b Round 6 WS-1b W16.2-C residual (2026-05-21) — identifies the
/// binding slot that holds a bare empty-array accumulator awaiting a
/// downstream-`.push()`-resolved element kind.
///
/// A `let mut out = []` either lands in a function-body local slot or a
/// top-level module binding; both are keyed by their `u16` index. The push
/// site (`compile_expr_method_call`) resolves the receiver to the same key,
/// patches the placeholder allocator, and promotes the binding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum EmptyArrayAccumulatorKey {
/// Function-body local slot index.
Local(u16),
/// Top-level module-binding index.
ModuleBinding(u16),
}
/// Phase 4b Round 6 WS-1b W16.2-C residual — a pending bare empty-array
/// accumulator. Carries the placeholder `NewArray(0)` instruction index so
/// the first `.push()` (or the end-of-compilation finalizer) can patch it.
#[derive(Debug, Clone)]
pub(crate) struct EmptyArrayAccumulator {
/// Instruction index of the placeholder `OpCode::NewArray` emitted at the
/// empty-array literal site. Patched in-place to `kind.new_opcode()` once
/// the element kind is proven.
pub alloc_instr_idx: usize,
/// Source location of the empty-array literal — used for the clean
/// "element type un-resolvable" diagnostic if no push ever resolves it.
pub literal_loc: Option<SourceLocation>,
/// The accumulator variable's source name (for diagnostics).
pub var_name: String,
}
/// Compiler state
pub struct BytecodeCompiler {
/// The program being built
pub(crate) program: BytecodeProgram,
/// Current function being compiled
pub(crate) current_function: Option<usize>,
/// Local variable mappings (name -> index)
pub(crate) locals: Vec<HashMap<String, u16>>,
/// ModuleBinding variable mappings (name -> index)
pub(crate) module_bindings: HashMap<String, u16>,
/// Next local variable index
pub(crate) next_local: u16,
/// Next module_binding variable index
pub(crate) next_global: u16,
/// Loop context stack for break/continue
pub(crate) loop_stack: Vec<LoopContext>,
/// Counter for synthetic closure function names
pub(crate) closure_counter: u64,
/// Closure function indices discovered during bytecode compilation of the
/// current function. Each entry is (closure_function_name, function_index).
/// Used to back-patch MIR ClosurePlaceholder/ClosureCapture after compilation.
pub(crate) closure_function_ids: Vec<(String, u16)>,
/// Registry of closure capture layouts (v2 closure specialization Phase A).
///
/// Keyed on capture signature (`Vec<ConcreteType>`): two closures with
/// identical capture signatures share a `ClosureTypeId`. Phase C will
/// consume this to extend the monomorphization cache key.
pub(crate) closure_registry: shape_value::v2::closure_layout::ClosureRegistry,
/// Mapping from closure function index to its `ClosureTypeId`.
/// Populated alongside `closure_function_ids` as each closure literal is
/// lowered. Phase C reads this to key monomorphization on the closure type.
pub(crate) closure_type_ids: Vec<(u16, shape_value::v2::concrete_type::ClosureTypeId)>,
/// Track A.1C — per-closure `CaptureKind` vector, one entry per capture
/// in declaration order. Populated alongside `closure_type_ids` so that
/// `compiler_impl_reference_model::build_closure_function_layouts` can
/// construct the per-function `ClosureLayout` with the correct
/// `CaptureKind` per capture (rather than defaulting to the
/// `ClosureRegistry::intern`'d all-`Immutable` shape). A missing entry
/// (closure registered via the legacy path, e.g. test helpers) falls
/// back to all-`Immutable`, matching the pre-A.1C layout.
pub(crate) closure_capture_kinds: Vec<(u16, Vec<shape_value::v2::closure_layout::CaptureKind>)>,
/// Registry of `Function<A, R>` signatures (v2 closure specialization
/// Phase F). `FunctionTypeId`s assigned here are written into
/// `TypedClosureHeader.type_id` in the JIT path and consumed by
/// `CallFunctionIndirect` to pick a Cranelift `call_indirect` signature.
pub(crate) function_type_registry:
shape_value::v2::function_type_registry::FunctionTypeRegistry,
/// Mapping from closure function index to the `FunctionTypeId` of its
/// callable signature (params + return). Populated alongside
/// `closure_type_ids` when a closure literal is lowered. The JIT reads
/// this to emit the per-`ClosureTypeId` direct-call signature and the
/// polymorphic `CallFunctionIndirect` signature.
pub(crate) function_type_ids: Vec<(u16, shape_value::v2::concrete_type::FunctionTypeId)>,
/// Phase F one-shot: if set, the next closure-literal emission uses
/// `MakeClosureHeap` instead of the legacy `MakeClosure`. The flag is
/// consumed (reset to false) as soon as `compile_expr_closure`
/// finishes emitting the opcode. Callers that want to force the heap
/// ABI (e.g. the return-statement compiler when the returned value is
/// a closure literal) set this right before lowering the closure.
pub(crate) emit_make_closure_heap_next: bool,
/// Wave E+5-cleanup task #108 side-channel: native-kind hint for
/// `GetProp` emit sites where the producer-flip in `op_get_prop`
/// pushes raw native bits (I64 / Timestamp / F64 / Bool field tags
/// against non-heap slots). Keyed by emitted-instruction index;
/// consumed by `last_emitted_native_kind`'s `GetProp` arm so the
/// host-boundary synthesizer re-tags raw bits per the recorded
/// kind. `GetProp` is `Instruction::simple` (no operand) so neither
/// operand-decode nor walk-back recovers the field tag — the
/// compiler must record the resolved kind at the emit site
/// (`compile_expr_property_access`).
pub(crate) get_prop_native_kinds: HashMap<usize, crate::type_tracking::StorageHint>,
/// When compiling a DataTable closure method (e.g. dt.filter(row => ...)),
/// this holds the (schema_id, type_name) to tag the closure's row parameter as RowView.
pub(crate) closure_row_schema: Option<(u32, String)>,
/// Strict-typing-sweep (Cluster 3): bidirectional closure inference for
/// HOF method calls. When the next compiled closure literal is the
/// argument to `arr.map(|x| …)` / `.filter` / `.reduce` / etc., the
/// outer `compile_expr_method_call` resolves the receiver's element
/// type and stashes per-user-param `TypeAnnotation` hints here. The
/// closure compile reads these hints and attaches them to params with
/// no explicit annotation, then clears the field. The vector indexes
/// USER params only (excludes synthesized capture-params).
pub(crate) pending_closure_param_types: Option<Vec<Option<shape_ast::ast::TypeAnnotation>>>,
/// Unified type metadata for the last compiled expression.
///
/// This is the single source for relational/value kind propagation
/// (Table<T>, Indexed<T>, known object schema, etc.).
pub(crate) last_expr_type_info: Option<VariableTypeInfo>,
/// Type tracker for optimized field access
pub(crate) type_tracker: TypeTracker,
/// Schema ID of the last compiled expression (if it's a TypedObject).
/// Used for compile-time typed merge optimization.
pub(crate) last_expr_schema: Option<SchemaId>,
/// Numeric type of the last compiled expression (for typed opcode emission).
/// Set by literal compilation, variable loads, and other expression compilers.
/// Read by binary op compilation to emit typed opcodes (e.g., MulInt).
pub(crate) last_expr_numeric_type: Option<crate::type_tracking::NumericType>,
/// E+5.5 Unit C step 2: captured top-level program return-kind, snapshotted
/// right after the last item compiles (before drop-scope emission and
/// Halt overwrite `last_expr_*`). Consumed by
/// `populate_program_storage_hints` to populate
/// `top_level_frame.return_kind` so the host boundary reads the kind
/// off the parallel-kind track (per ADR-006 §2.7.7 — the deleted
/// ValueWord-tagged synthesis is gone).
///
/// Per ADR-006 §2.7.5.1 (compiler-tier intermediate state policy),
/// "kind not yet stamped" is carried as `Option<StorageHint>` —
/// `None` is the post-bulldozer replacement for the deleted
/// `StorageHint::Unknown` sentinel.
pub(crate) top_level_program_return_kind: Option<crate::type_tracking::StorageHint>,
/// Result mode for the expression currently being compiled.
pub(crate) current_expr_result_mode: ExprResultMode,
/// Whether the last compiled expression left a raw reference on the stack.
///
/// `auto_deref_mode` is only set for propagated ref results (identifier loads,
/// ref-returning calls) that should implicitly dereference in value contexts.
/// Explicit `&expr` results keep `raw_mode` without enabling auto-deref.
pub(crate) last_expr_reference_result: ExprReferenceResult,
/// Known pass modes for local callable bindings (closures / function aliases).
pub(crate) local_callable_pass_modes: HashMap<u16, Vec<ParamPassMode>>,
/// Known safe return-reference summaries for local callable bindings.
pub(crate) local_callable_return_reference_summaries:
HashMap<u16, FunctionReturnReferenceSummary>,
/// Known pass modes for module-binding callable values.
pub(crate) module_binding_callable_pass_modes: HashMap<u16, Vec<ParamPassMode>>,
/// Known safe return-reference summaries for module-binding callable values.
pub(crate) module_binding_callable_return_reference_summaries:
HashMap<u16, FunctionReturnReferenceSummary>,
/// Sweep phase 3c.1: inferred return-type names for closures stored in
/// local slots. Populated when `update_callable_binding_from_expr`
/// observes a `FunctionExpr` initializer; consumed by `infer_expr_type`
/// so a `FunctionCall { name: f, .. }` against `let f = |…| body` can
/// recover the body's return type for strict-typing binop dispatch.
pub(crate) local_callable_return_types: HashMap<u16, String>,
/// Sweep phase 3c.1: inferred return-type names for closures stored in
/// module-binding slots (top-level / REPL `let f = |…|` style).
pub(crate) module_binding_callable_return_types: HashMap<u16, String>,
/// Sweep phase 3c.x: inferred return-type names for arrays whose elements
/// are closure literals with a homogeneous return type. Keyed by the
/// local slot holding the array. Consumed by `infer_expr_type` for the
/// `arr[i](args...)` callsite (which the parser models as
/// `MethodCall { method: "__call__", receiver: IndexAccess { .. } }`).
/// Without this lookup, `arr[0](1) + arr[1](1)` fails strict-typing as
/// `unknown + unknown`.
pub(crate) local_array_callable_return_types: HashMap<u16, String>,
/// Sweep phase 3c.x: inferred return-type names for arrays of closures
/// stored in module-binding slots (top-level `let arr = [|x| ..., ...]`).
pub(crate) module_binding_array_callable_return_types: HashMap<u16, String>,
/// cluster-2-cw-IB-class-b (2026-05-16, supervisor R3 binding-
/// ratified): retained closure-literal body for local `let f = |..|
/// ..` bindings. Populated at let-binding time by
/// `update_callable_binding_from_expr`'s `FunctionExpr` arm;
/// consumed at `compile_expr_function_call`'s value-call branch when
/// re-running closure-body return-type inference with caller-context
/// arg types.
///
/// The retained body is the AST `Vec<Statement>` clone (no lowering
/// occurs at lookup time — the inference walker only inspects AST
/// shape, never emits bytecode for the body). Released on
/// `clear_callable_binding` and on per-function compilation
/// snapshot/restore alongside the existing `local_callable_*`
/// maps (`functions.rs:1148-1151` / `:1496-1499` / `:1607-1608`).
///
/// Memory cost: bounded by the number of local closure bindings in
/// the active function frame; the body is the same AST already held
/// by the parent `Statement::VariableDecl` initializer, just held
/// for the lifetime of the enclosing function-compile pass to avoid
/// re-walking the AST at every value-call site. Released when the
/// enclosing function compile completes.
pub(crate) local_callable_closure_bodies:
HashMap<u16, ClosureBodyPeek>,
/// cluster-2-cw-IB-class-b: module-binding variant of the closure
/// body peek. Covers top-level / REPL `let f = |..|` bindings whose
/// slots live in the module-binding space (not the local-slot
/// space). Populated/cleared alongside the existing
/// `module_binding_callable_return_types` map at the
/// `update_callable_binding_from_expr` `FunctionExpr` arm.
pub(crate) module_binding_callable_closure_bodies:
HashMap<u16, ClosureBodyPeek>,
/// ADR-006 §2.7.24 Q25.C trait-object emission (Wave 2.6 round-2):
/// per-local-slot trait name for `let a: dyn Animal = ...` bindings.
/// Consumed by `compile_expr_method_call` (`expressions/function_calls.rs`)
/// to route method dispatch through `OpCode::DynMethodCall` instead
/// of the standard `OpCode::CallMethod` path. Empty for non-dyn
/// locals.
pub(crate) dyn_locals: HashMap<u16, String>,
/// ADR-006 §2.7.24 Q25.C trait-object emission: per-module-binding
/// trait name for top-level `let a: dyn Animal = ...` declarations.
/// Same role as `dyn_locals` but for the module-binding slot space.
pub(crate) dyn_module_bindings: HashMap<u16, String>,
/// Named functions that safely return one reference parameter unchanged.
pub(crate) function_return_reference_summaries: HashMap<String, FunctionReturnReferenceSummary>,
/// The return-reference summary of the function currently being compiled, if any.
pub(crate) current_function_return_reference_summary: Option<FunctionReturnReferenceSummary>,
/// Type inference engine for match exhaustiveness and type checking
pub(crate) type_inference: shape_runtime::type_system::inference::TypeInferenceEngine,
/// Track type aliases defined in the program
/// Maps alias name -> target type (for type validation)
pub(crate) type_aliases: HashMap<String, String>,
/// Current source line being compiled (for debug info)
pub(crate) current_line: u32,
/// Current source file ID (for multi-file debug info)
pub(crate) current_file_id: u16,
/// Source text (for error messages)
pub(crate) source_text: Option<String>,
/// Source lines (split from source_text for quick access)
pub(crate) source_lines: Vec<String>,
/// Imported symbols: local_name -> ImportedSymbol
pub(crate) imported_names: HashMap<String, ImportedSymbol>,
/// Imported annotations: local_name -> ImportedAnnotationSymbol
pub(crate) imported_annotations: HashMap<String, ImportedAnnotationSymbol>,
/// R8 W8 Cluster A (2026-05-24): imported `pub const NAME = expr`
/// initializers, keyed by the local binding name (alias-respecting).
/// At identifier-load time, references to these names compile to an
/// inlined `PushConst(<comptime-value>)` rather than a
/// `LoadModuleBinding` — the dispatch's "use the existing
/// comptime-evaluated-constant mechanism (the `Constant` pool); NOT a
/// new opcode, NOT a deferred init runtime computation" binding.
/// ADR-006 §2.7.5 stamp-at-compile-time invariant preserved: the
/// constant's kind is stamped from the literal's shape at compile time.
pub(crate) imported_consts: HashMap<String, shape_ast::ast::Expr>,
/// Qualified builtin function declarations available as module-scoped callables.
pub(crate) module_builtin_functions: HashMap<String, ModuleBuiltinFunction>,
/// Module namespace bindings introduced by `use module.path`.
/// Used to avoid UFCS rewrites for module calls like `duckdb.connect(...)`.
pub(crate) module_namespace_bindings: HashSet<String>,
/// Imported synthetic/local module path -> original source module path.
/// Used when code inside a wrapper module needs to dispatch to native exports
/// from the underlying source module.
pub(crate) module_scope_sources: HashMap<String, String>,
/// Active lexical module scope stack while compiling `mod Name { ... }`.
pub(crate) module_scope_stack: Vec<String>,
/// Known exports for import suggestions: function_name -> module_path
/// Used to provide helpful error messages like "Did you mean to import from...?"
pub(crate) known_exports: HashMap<String, String>,
/// Function arity bounds keyed by function name: (required_params, total_params).
/// Required params are non-default parameters. Defaults are only allowed
/// in trailing positions.
pub(crate) function_arity_bounds: HashMap<String, (usize, usize)>,
/// Function const parameter indices keyed by function name.
/// Const parameters must receive compile-time constant arguments at call sites.
pub(crate) function_const_params: HashMap<String, Vec<usize>>,
/// Original function definitions keyed by function name.
/// Used for const-template specialization at call sites.
pub(crate) function_defs: HashMap<String, FunctionDef>,
/// Foreign function definitions keyed by function name.
/// Used to resolve the effective (Result-wrapped) return type at call sites.
pub(crate) foreign_function_defs: HashMap<String, shape_ast::ast::ForeignFunctionDef>,
/// Sweep phase 3c.x: per-(enum, variant) struct-variant field
/// annotations. The schema-level `EnumVariantInfo` only carries field
/// counts (`payload_fields`) and uses `__payload_N` field names with
/// `FieldType::Any`, so the named-field types of `enum E { V { x: int,
/// y: int } }` are otherwise lost at pattern compile time. Populated
/// by `register_enum`; consumed by `compile_typed_enum_binding` (struct
/// arm) so `match m::E::V { x, y } => x + y` propagates int onto x and
/// y.
pub(crate) enum_struct_variant_fields:
HashMap<(String, String), Vec<(String, shape_ast::ast::TypeAnnotation)>>,
/// R8 W7: per-(enum, variant) tuple-payload positional type
/// annotations. Symmetric to `enum_struct_variant_fields` for
/// tuple variants. The runtime schema collapses tuple payloads
/// into `__payload_N: Any`, so per-position types of
/// `enum E { V(string) }` are otherwise lost at pattern-compile
/// time. Populated by `register_enum`; consumed by
/// `compile_typed_enum_binding` (tuple arm) so `match E::V(id) =>
/// id + "!"` propagates `string` onto `id`.
pub(crate) enum_tuple_variant_fields:
HashMap<(String, String), Vec<shape_ast::ast::TypeAnnotation>>,
/// Cached const specializations keyed by `(base_name + const-arg fingerprint)`.
pub(crate) const_specializations: HashMap<String, usize>,
/// Monotonic counter for unique specialization symbol names.
pub(crate) next_const_specialization_id: u64,
/// Const-parameter bindings for specialized function symbols.
/// These bindings are exposed to comptime handlers as typed module_bindings.
/// Kinded carrier per ADR-006 §2.7 / Q7 (`KindedSlot`); the prior
/// `shape_value::ValueWord` shape was deleted by the strict-typing
/// bulldozer and the comptime ABI in
/// `compiler/comptime.rs:execute_comptime_with_annotation_handler`
/// already migrated to `(String, KindedSlot)` pairs.
pub(crate) specialization_const_bindings:
HashMap<String, Vec<(String, shape_value::KindedSlot)>>,
/// Struct type definitions: type_name -> (field_names in order, definition span)
pub(crate) struct_types: HashMap<String, (Vec<String>, shape_ast::ast::Span)>,
/// Generic metadata for struct types used to instantiate runtime type names
/// (e.g. `MyType<number>`) at struct-literal construction sites.
pub(crate) struct_generic_info: HashMap<String, StructGenericInfo>,
/// Names of `type C` declarations with native layout metadata.
pub(crate) native_layout_types: HashSet<String>,
/// Generated conversion pair cache keys: `c_type::object_type`.
pub(crate) generated_native_conversion_pairs: HashSet<String>,
/// Whether the current function being compiled is async
pub(crate) current_function_is_async: bool,
/// Directory of the source file being compiled (for resolving relative source paths)
pub(crate) source_dir: Option<std::path::PathBuf>,
/// Collected compilation errors (for multi-error reporting)
pub(crate) errors: Vec<shape_ast::error::ShapeError>,
/// Hoisted fields from optimistic hoisting pre-pass.
/// Maps variable name → list of property names assigned later (e.g., a.y = 2 → "a" → ["y"]).
/// Used to include future property assignments in inline object schemas at compile time.
pub(crate) hoisted_fields: HashMap<String, Vec<String>>,
/// Phase 3e: inferred FieldType for hoisted fields, when the assigned
/// RHS is a simple literal whose primitive type is statically known.
/// Maps variable name → property name → inferred FieldType.
///
/// Used by `compile_typed_object_literal` to register the schema with
/// concrete primitive types (I64, F64, Bool, String) instead of falling
/// back to FieldType::Any. Without this, `let mut a = { x: 10 }; a.y =
/// 20; a.x + a.y` types `a.y` as Any in the schema, so the binary-op
/// numeric path declines and trait dispatch fires (which has no runtime
/// handler for `int.add`).
pub(crate) hoisted_field_types:
HashMap<String, HashMap<String, shape_runtime::type_schema::FieldType>>,
/// When compiling a variable initializer, the name of the variable being assigned to.
/// Used by compile_typed_object_literal to include hoisted fields in the schema.
pub(crate) pending_variable_name: Option<String>,
/// v2 Phase 3.1: when the enclosing `let arr: Array<T> = [...]` declares
/// an explicit `Array<T>` annotation whose element type maps to a
/// [`v2_typed_emission::TypedArrayKind`], stash the kind here so
/// `compile_expr_array` can lower the literal to a v2 typed-array
/// allocation. The statement-binding code path resets this to `None`
/// before each new initializer.
pub(crate) pending_variable_typed_array_kind:
Option<crate::compiler::v2_typed_emission::TypedArrayKind>,
/// R5.4B: nested-array-literal depth.
///
/// Incremented while `compile_expr_array` compiles the elements of an
/// array literal, decremented after. When `> 0`, the compiler is inside
/// a nested array-literal context (e.g. the inner `[1.0, 2.0]` of
/// `[[1.0, 2.0], [3.0, 4.0]]`) and MUST refuse the typed-array fast
/// path (`NewTypedArrayF64`/etc.) regardless of annotation or
/// inference.
///
/// Why: the v2 typed-array opcodes store the allocation as a raw
/// native pointer on the kinded VM stack with
/// `NativeKind::Ptr(HeapKind::TypedArray)` declared on the parallel-
/// kind track (ADR-006 §2.7.7), not as a generic heap-tagged value.
/// Downstream consumers that expect a generic `Array` via
/// `slot.as_heap_value()` cannot decode a typed-array native pointer
/// back into a generic Array (the deleted `as_heap_ref()` /
/// `as_any_array()` carrier accessors are gone), so e.g.
/// `intrinsic_matmul_mat` fails with "row 0 must be an array of
/// numeric values". Refusing typed emission for inner rows forces
/// them onto the legacy `NewArray` path, which produces a generic
/// `HeapValue::Array` that round-trips correctly through a generic
/// outer `Array`.
pub(crate) nested_array_literal_depth: u32,
/// v2 Phase 3.1: per-local-slot record of which locals hold a v2
/// typed array (allocated via `NewTypedArrayF64/I64/I32/Bool` rather
/// than the legacy v1 `NewTypedArray`/`NewArray`). Populated by the
/// statement-binding code path when an `Array<T>` annotation
/// successfully picks a typed kind. Consumed by
/// `resolve_receiver_typed_array_kind` so the typed Get/Set/Push/Len
/// opcodes are only emitted for receivers that were ALSO allocated
/// as v2 typed arrays — never for legacy NaN-boxed arrays.
pub(crate) v2_typed_array_locals:
HashMap<u16, crate::compiler::v2_typed_emission::TypedArrayKind>,
/// v2 Phase 3.1: per-module-binding record of v2 typed arrays.
/// Mirrors [`v2_typed_array_locals`] for top-level bindings.
pub(crate) v2_typed_array_module_bindings:
HashMap<u16, crate::compiler::v2_typed_emission::TypedArrayKind>,
/// Phase 4b Round 6 WS-1 W16.2-C (2026-05-21) — list-comprehension
/// element-kind capture.
///
/// `compile_list_comprehension` emits the result accumulator's
/// `NewTypedArray*` allocator BEFORE the comprehension body is compiled,
/// but the element-expression's proven scalar kind is only known AFTER
/// the body compiles. `compile_comprehension_clauses` writes the proven
/// [`TypedArrayKind`] here at the innermost (clause-empty) base case,
/// reading the bytecode compiler's `last_expr_numeric_type` /
/// `last_expr_type_info` right after the element expression compiles —
/// per ADR-006 §2.7.5 the kind is proven at the producer site, never
/// fabricated. `compile_list_comprehension` then patches the recorded
/// allocator instruction with the matching typed opcode. `None` means
/// the element kind was not statically provable — a clean compile error.
pub(crate) comprehension_element_kind:
Option<crate::compiler::v2_typed_emission::TypedArrayKind>,
/// Phase 4b Round 6 WS-1 W16.2-C (2026-05-21) — instruction indices of
/// the placeholder `ArrayPush` opcodes emitted at list-comprehension
/// element-push sites. `compile_comprehension_clauses` records each
/// base-case push here; `compile_list_comprehension` patches them all
/// to the resolved `TypedArrayPush*` opcode once the element kind is
/// known — so the typed accumulator receives a typed push that the JIT
/// and VM both dispatch unambiguously (no generic-carrier path).
pub(crate) comprehension_push_sites: Vec<usize>,
/// Phase 4b Round 6 WS-1b W16.2-C residual (2026-05-21) — bare
/// empty-array accumulator deferred-kind capture.
///
/// A bare `let mut out = []` (empty array literal, no `Array<T>`
/// annotation, no elements) cannot resolve its `TypedArrayKind` at the
/// literal site — the element type is determined only by downstream
/// `out.push(x)` calls. `compile_expr_array` emits a placeholder
/// `NewArray(0)` and records its instruction index here against the
/// binding (local slot or module binding). The FIRST `arr.push(v)` on
/// that binding resolves the element kind from the compiled argument's
/// proven type (ADR-006 §2.7.5 producer-side stamp — read from the
/// type-tracker at the push site, never decoded from runtime bits, never
/// Bool-defaulted), patches the placeholder to the matching typed
/// `NewTypedArray*` allocator, and promotes the binding into
/// `v2_typed_array_locals` / `v2_typed_array_module_bindings` so every
/// subsequent push is a typed `TypedArrayPush*`. A bare empty array that
/// is never pushed to and never annotated has a genuinely un-resolvable
/// element type — `finalize_unresolved_empty_array_accumulators`
/// surface-and-stops with a clean structured compile error.
pub(crate) empty_array_accumulators: HashMap<EmptyArrayAccumulatorKey, EmptyArrayAccumulator>,
/// Phase 4b Round 6 WS-1b — instruction index of the placeholder
/// `NewArray(0)` emitted by the most recent `compile_expr_array` call for
/// a bare empty array literal. The enclosing `Statement::VariableDecl` /
/// `Item::VariableDecl` reads this immediately after the initializer
/// compiles and re-keys it into [`empty_array_accumulators`] against the
/// resolved binding. `None` when the last array literal was non-empty,
/// annotated, or otherwise resolved a kind directly.
pub(crate) pending_empty_array_alloc_idx: Option<usize>,
/// v2 Phase 3.2: when the enclosing `let m: HashMap<K, V> = HashMap()`
/// declares an explicit `HashMap<K, V>` annotation whose key/value pair
/// maps to a [`v2_typed_map_emission::TypedMapKind`], stash the kind here
/// so `compile_expr_function_call` (HashMap ctor path) can lower the
/// allocation to a v2 typed-map opcode. The statement-binding code path
/// resets this to `None` before each new initializer.
pub(crate) pending_variable_typed_map_kind:
Option<crate::compiler::v2_typed_map_emission::TypedMapKind>,
/// v2 Phase 3.2: per-local-slot record of which locals hold a v2 typed
/// HashMap (allocated via `NewTypedMap*` rather than the legacy
/// `BuiltinCall(HashMapCtor)`). Populated by the statement-binding code
/// path. Consumed by HashMap method dispatch (`m.set/.get/.has/.delete`)
/// so the typed Set/Get/Has/Delete opcodes are only emitted for receivers
/// that were ALSO allocated as v2 typed maps — never for legacy NaN-boxed
/// HashMapData.
pub(crate) v2_typed_map_locals:
HashMap<u16, crate::compiler::v2_typed_map_emission::TypedMapKind>,
/// v2 Phase 3.2: per-module-binding record of v2 typed maps. Mirrors
/// [`v2_typed_map_locals`] for top-level bindings.
pub(crate) v2_typed_map_module_bindings:
HashMap<u16, crate::compiler::v2_typed_map_emission::TypedMapKind>,
/// ADR-006 §2.7.27 / Item 4 ruling (W17-mutation-writeback, 2026-05-12):
/// per-local-slot record of locals known to hold a Copy-on-Write
/// collection (HashSet / HashMap / Deque / PriorityQueue / Array of
/// generic carrier). Populated at let-binding time when the initializer
/// is one of `Set()` / `HashMap()` / `Deque()` / `PriorityQueue()` /
/// `[…]`, or when the binding has an explicit type annotation that
/// names the container kind.
///
/// Consumed by `compile_expr_method_call`'s `&mut self` writeback
/// emission gate: for an identifier-receiver method call where
/// `(container_kind, method_name)` matches a `MUT_SELF_*` entry, the
/// compiler emits `Dup; StoreLocal recv` after `CallMethod` so the
/// new (possibly Arc-cloned) receiver Arc updates the binding slot.
pub(crate) mut_self_container_locals:
HashMap<u16, crate::compiler::mutation_writeback::ContainerKind>,
/// ADR-006 §2.7.27 / Item 4 ruling: per-module-binding record of
/// mutating-container module bindings. Mirrors
/// [`mut_self_container_locals`] for top-level bindings.
pub(crate) mut_self_container_bindings:
HashMap<u16, crate::compiler::mutation_writeback::ContainerKind>,
/// ADR-006 §2.7.27 / Item 4 ruling: signal raised by container-ctor
/// builtin call emitters (`SetCtor`, `DequeCtor`,
/// `PriorityQueueCtor`, `HashMapCtor`) so the surrounding statement-
/// binding code path can transfer the kind onto the target local
/// / module binding. Mirrors the existing
/// [`pending_variable_typed_array_kind`] convention.
pub(crate) pending_variable_container_kind:
Option<crate::compiler::mutation_writeback::ContainerKind>,
/// v2 Phase 3.2: per-AST-node side table mapping a HashMap-shaped
/// expression to its key/value `ConcreteType` pair. Populated by the
/// `let m: HashMap<K, V> = ...` annotation path AND by inference helpers
/// (`infer_hashmap_kv_from_context`).
pub(crate) map_key_value_types: HashMap<
shape_ast::ast::Span,
(shape_value::v2::ConcreteType, shape_value::v2::ConcreteType),
>,
/// v2 Phase 3.2: per-local-slot side table for HashMap key/value pairs.
pub(crate) local_map_key_value_types:
HashMap<u16, (shape_value::v2::ConcreteType, shape_value::v2::ConcreteType)>,
/// v2 Phase 3.2: per-module-binding side table for HashMap key/value pairs.
pub(crate) module_binding_map_key_value_types:
HashMap<u16, (shape_value::v2::ConcreteType, shape_value::v2::ConcreteType)>,
/// v2 Phase 3.2: per-AST-span array element type table — used by
/// monomorphization helpers and methods that produce arrays from maps.
pub(crate) array_element_types: HashMap<shape_ast::ast::Span, shape_value::v2::ConcreteType>,
/// v2 Phase 3.2: per-local-slot array element type table.
pub(crate) local_array_element_types: HashMap<u16, shape_value::v2::ConcreteType>,
/// v2 Phase 3.2: per-module-binding array element type table.
pub(crate) module_binding_array_element_types: HashMap<u16, shape_value::v2::ConcreteType>,
/// Lexical names that will later need their binding value to remain a raw reference.
/// This is only used to choose `Value` vs `PreserveRef` lowering for bindings; MIR
/// remains the sole authority for borrow legality.
pub(crate) future_reference_use_name_scopes: Vec<HashSet<String>>,
/// Known trait names (populated in the first pass so meta definitions can reference traits)
pub(crate) known_traits: std::collections::HashSet<String>,
/// Full trait definitions keyed by trait name.
/// Used to install default method implementations for impl blocks that omit them.
pub(crate) trait_defs: HashMap<String, shape_ast::ast::types::TraitDef>,
/// J-CT.2 (2026-05-23) — comptime impl blocks deferred for in-mini-VM
/// registration. The outer compiler does NOT desugar/register/compile
/// methods of `comptime impl Trait for Type { ... }` blocks into the
/// runtime program; they are skipped from runtime processing and stored
/// here so the comptime-evaluator mini-VM (`execute_comptime` in
/// `compiler/comptime.rs`) can prepend them as `Item::Impl` items, where
/// the in-comptime-mode compiler then desugars + compiles them normally.
/// Method dispatch from `instance.method()` inside a `comptime { }` block
/// then routes through the standard UFCS / `Type::method` resolution
/// path without a new dispatch shape (audit §2.D carve-out).
pub(crate) comptime_impl_blocks: Vec<shape_ast::ast::types::ImplBlock>,
/// J-CT.2 (2026-05-23) — original struct definitions captured during
/// the first pass. The outer compiler only retains field NAMES in
/// `struct_types`; the comptime-evaluator mini-VM needs full AST
/// (typed annotations, generic info, annotations) to compile
/// struct-literal constructions and field accesses inside `comptime { }`
/// blocks that interact with `comptime_impl_blocks`. Populated in the
/// first-pass `Item::StructType` arm.
pub(crate) comptime_context_struct_defs:
HashMap<String, shape_ast::ast::types::StructTypeDef>,
/// Extension registry for comptime execution
pub(crate) extension_registry: Option<Arc<Vec<shape_runtime::module_exports::ModuleExports>>>,
/// Comptime field values per type: type_name -> (field_name -> bake-time
/// constant). These are type-level constants baked at compile time
/// with zero runtime cost. Inner map releases heap-backed comptime
/// values (strings via `Arc<String>`, etc.) when a type's entry is
/// removed or the compiler is dropped.
///
/// Kinded carrier per ADR-006 §2.7 / Q7 (`KindedSlot`); the prior
/// `shape_value::ValueMap` shape was deleted by the strict-typing
/// bulldozer along with `ValueWord`. Mirrors the
/// `comptime_builtins::ComptimeDirective::SetParamValue { value:
/// KindedSlot }` migration already landed in
/// `compiler/comptime_builtins.rs`.
pub(crate) comptime_fields:
HashMap<String, HashMap<String, shape_value::KindedSlot>>,
/// Type diagnostic mode for shared analyzer diagnostics.
pub(crate) type_diagnostic_mode: TypeDiagnosticMode,
/// Expression compilation diagnostic mode.
pub(crate) compile_diagnostic_mode: CompileDiagnosticMode,
/// Whether this compiler instance is compiling code for comptime execution.
/// Enables comptime-only builtins and comptime-specific statement semantics.
pub(crate) comptime_mode: bool,
/// Functions removed by comptime annotation handlers (`remove target`).
/// These are still present in `program.functions` (registered in the first pass)
/// but must produce a clear compile-time error when called instead of jumping
/// to an invalid entry point.
pub(crate) removed_functions: HashSet<String>,
/// Internal guard for compiler-synthesized `__comptime__` helper calls.
/// User source must never access `__comptime__` directly.
pub(crate) allow_internal_comptime_namespace: bool,
/// Method table for data-driven method signature queries.
/// Used to replace hardcoded heuristics (e.g., is_type_preserving_table_method)
/// with MethodTable lookups (is_self_returning, takes_closure_with_receiver_param).
pub(crate) method_table: MethodTable,
/// Locals that are reference-typed in the current function.
pub(crate) ref_locals: HashSet<u16>,
/// Subset of ref_locals that hold exclusive (`&mut`) borrows.
/// Used to enforce the three concurrency rules at task boundaries.
pub(crate) exclusive_ref_locals: HashSet<u16>,
/// Subset of ref_locals that were INFERRED as by-reference (not explicitly declared `&`).
/// Inferred-ref params are owned values passed by reference for performance;
/// closures may capture them (the value is dereferenced at capture time).
pub(crate) inferred_ref_locals: HashSet<u16>,
/// Locals whose binding value is itself a first-class reference (`let r = &x`).
/// Reads auto-deref; writes still rebind the local.
pub(crate) reference_value_locals: HashSet<u16>,
/// Subset of reference_value_locals that hold exclusive (`&mut`) references.
pub(crate) exclusive_reference_value_locals: HashSet<u16>,
/// Local variable indices declared as `const` (immutable binding).
pub(crate) const_locals: HashSet<u16>,
/// Module binding indices declared as `const` (immutable binding).
pub(crate) const_module_bindings: HashSet<u16>,
/// Local variable indices declared as immutable `let` (not `let mut` or `var`).
pub(crate) immutable_locals: HashSet<u16>,
/// Local variable indices that are function parameters (first N locals in a function).
/// Used to avoid trusting inferred type hints for params with no explicit annotation.
pub(crate) param_locals: HashSet<u16>,
/// Module binding indices declared as immutable `let`.
pub(crate) immutable_module_bindings: HashSet<u16>,
/// Module bindings whose value is itself a first-class reference.
pub(crate) reference_value_module_bindings: HashSet<u16>,
/// Subset of reference_value_module_bindings that hold exclusive (`&mut`) references.
pub(crate) exclusive_reference_value_module_bindings: HashSet<u16>,
/// ModuleBinding-ref writebacks collected while compiling current call args.
pub(crate) call_arg_module_binding_ref_writebacks: Vec<Vec<(u16, u16)>>,
/// Inferred reference parameters for untyped params: function -> per-param flag.
pub(crate) inferred_ref_params: HashMap<String, Vec<bool>>,
/// Inferred mutating-reference params: function -> per-param flag.
pub(crate) inferred_ref_mutates: HashMap<String, Vec<bool>>,
/// Effective per-parameter pass mode (explicit + inferred), by function name.
pub(crate) inferred_param_pass_modes: HashMap<String, Vec<ParamPassMode>>,
/// Inferred parameter type hints for unannotated params.
/// Keyed by function name; each entry is a per-param optional type string.
pub(crate) inferred_param_type_hints: HashMap<String, Vec<Option<String>>>,
/// v0.3 WS-7: inference-resolved per-parameter `ConcreteType` for
/// UNANNOTATED params. Keyed by function name; each entry is a per-param
/// optional `ConcreteType` projected from the program-wide type-inference
/// engine's result. Annotated params keep `None` here (their
/// `ConcreteType` is stamped directly from the annotation in the
/// `function_local_concrete_types` per-fn seeding pass). This is the
/// proof source that lets the JIT take the v2 typed-array fast path for
/// `fn get(xs, i) { xs[i] }`-style unannotated array parameters — without
/// it the slot stays `ConcreteType::Void`, the JIT mis-classifies the v2
/// `TypedArray` pointer as a NaN-boxed v1 array, and the inline index
/// load reads garbage / SIGSEGVs.
pub(crate) inferred_param_concrete_types:
HashMap<String, Vec<Option<shape_value::v2::ConcreteType>>>,
/// WS-9b: inference-resolved per-parameter ANONYMOUS-OBJECT field
/// definitions for UNANNOTATED params. Keyed by function name; each
/// entry is a per-param optional `Vec<(field_name, FieldType)>`.
///
/// A *named* struct parameter (`type Box`) resolves through the schema
/// registry — `set_local_type_info` already stamps its `schema_id` from
/// the `"Box"` hint name. But an *anonymous* object parameter (the shape
/// `fn aabb(...) { { min_x: ..., ... } }` produces) has no named schema:
/// its inference hint is the structural string `"{min_x: number, ...}"`,
/// which matches no registered schema. `compile_function_body` consumes
/// this map to register an inline `__inline_obj_*` schema for such a
/// parameter and stamp the slot's `schema_id`, so `param.field` resolves
/// to the proven field type the same way a named-struct field does. The
/// field types are projected from inference's resolved param `Type` —
/// proven, never fabricated; an unresolved field yields `None`.
pub(crate) inferred_param_object_fields: HashMap<
String,
Vec<Option<Vec<(String, shape_runtime::type_schema::FieldType)>>>,
>,
/// WS-9c: per-function inferred RETURN type projected to a
/// `Vec<(field_name, FieldType)>` when that return type is an anonymous
/// structural object (an unannotated object-literal factory such as
/// `fn aabb(lo, hi) { {min: lo, max: hi} }`). `compile_expr_function_call`
/// consumes this to register an inline anonymous schema for the call's
/// result so `aabb(...).field` / `let a = aabb(...); a.field` resolves to
/// the proven field type — the same resolution a named-struct return type
/// already receives. Only unannotated functions appear here (annotated
/// returns resolve through the annotation path). Field types are projected
/// from inference's resolved return `Type` — proven, never fabricated.
pub(crate) inferred_return_object_fields:
HashMap<String, Vec<(String, shape_runtime::type_schema::FieldType)>>,
/// WS-9c: function name → registered inline anonymous schema id for an
/// unannotated function whose inferred return type is an anonymous
/// object. Populated once, up-front, by
/// `register_inferred_return_object_schemas`. Consulted by
/// `compile_expr_function_call` (to stamp `last_expr_schema`) and by the
/// read-only `infer_expr_type` property-access path (to resolve
/// `f(...).field` directly, with no `let` binding).
pub(crate) function_return_schema_ids: HashMap<String, u32>,
/// Stack of scopes, each containing locals that need Drop calls at scope exit.
/// Each entry is (local_index, is_async).
pub(crate) drop_locals: Vec<Vec<(u16, bool)>>,
/// Phase V1.1C: parallel scope stack tracking locals whose storage class
/// is `UniqueHeap` and therefore (when the ownership-moves flag is on)
/// need an ownership-aware `DropLocal` opcode emitted at scope exit to
/// release the owned heap allocation. Orthogonal to `drop_locals` (which
/// drives user-facing `Drop` trait calls via `DropCall`). Populated and
/// consumed only when `ownership_moves_enabled()` is true; otherwise the
/// scope stack is pushed/popped in lockstep with `drop_locals` but kept
/// empty, so the compiler's emission path is byte-identical to
/// pre-V1.1C.
pub(crate) ownership_drop_locals: Vec<Vec<u16>>,
/// Per-type drop kind: tracks whether each type has sync, async, or both drop impls.
/// Populated during the first-pass registration of impl blocks.
pub(crate) drop_type_info: HashMap<String, DropKind>,
/// Module bindings that need Drop calls at program exit.
/// Each entry is (binding_index, is_async).
pub(crate) drop_module_bindings: Vec<(u16, bool)>,
/// Mutable closure captures in the current function being compiled.
/// Maps captured variable name -> upvalue index (for LoadClosure/StoreClosure).
/// Only populated while compiling a closure body that has mutable captures.
pub(crate) mutable_closure_captures: HashMap<String, u16>,
/// Track A.1C.2: subset of `mutable_closure_captures` whose source
/// binding classifies as `CaptureKind::Shared` (a `var` binding
/// mutably captured through a closure). Maps captured variable name
/// → capture index. When the identifier lookup finds a name in this
/// map, the closure body emits `LoadSharedCapture` /
/// `StoreSharedCapture` (A.1B) instead of the legacy `LoadClosure`
/// / `StoreClosure`. Populated while compiling a closure body.
pub(crate) shared_closure_captures: HashMap<String, u16>,
/// Track A.1C.2b: subset of `mutable_closure_captures` whose source
/// binding classifies as `CaptureKind::OwnedMutable` (a `let mut`
/// binding captured by move into a single closure). Maps captured
/// variable name → capture index. When the identifier lookup finds
/// a name in this map, the closure body emits
/// `LoadOwnedMutableCapture` / `StoreOwnedMutableCapture` (A.1B)
/// instead of the legacy `LoadClosure` / `StoreClosure`. Populated
/// while compiling a closure body.
pub(crate) owned_mutable_closure_captures: HashMap<String, u16>,
/// Wave E: parallel to `owned_mutable_closure_captures`, records
/// the interior `FieldKind` of each OwnedMutable capture cell. The
/// inner kind is derived from the captured binding's resolved
/// `ConcreteType` (`concrete_type_for_expr → ConcreteType::to_field_kind`)
/// at the point of closure construction. The closure body uses
/// this map to dispatch to the typed Wave D.1 opcodes
/// (`LoadOwnedMutableCapture<Kind>` / `StoreOwnedMutableCapture<Kind>`,
/// codes 0x140-0x155) instead of the legacy untyped `0x132`/`0x133`
/// opcodes (kind-erased pre-strict-typing — ADR-006 §2.7.7).
/// Populated alongside `owned_mutable_closure_captures`,
/// saved/restored across nested closure-body compilations.
pub(crate) owned_mutable_capture_inner_kinds:
HashMap<String, shape_value::v2::struct_layout::FieldKind>,
/// A2-refined / task #17: parallel to `shared_closure_captures`,
/// records the interior `FieldKind` of each Shared (`var`) capture
/// cell. Derived from the captured binding's resolved `ConcreteType`
/// at closure-construction time, mirroring
/// `owned_mutable_capture_inner_kinds`. The closure body uses this
/// map to dispatch to the typed Wave D.2 opcodes
/// (`LoadSharedCapture<Kind>` / `StoreSharedCapture<Kind>`, codes
/// 0x156-0x16B) instead of the legacy untyped `0x134`/`0x135`
/// opcodes (kind-erased pre-strict-typing — ADR-006 §2.7.7).
/// Saved/restored across nested closure-body compilations.
pub(crate) shared_capture_inner_kinds:
HashMap<String, shape_value::v2::struct_layout::FieldKind>,
/// Variables in the current scope that have been boxed into SharedCells
/// by a mutable closure capture. When a subsequent closure captures one
/// of these variables (even immutably), it must use the SharedCell path
/// so it shares the same mutable cell.
pub(crate) boxed_locals: HashSet<String>,
/// Track A.1C.2: local slots that have been promoted to
/// `Arc<parking_lot::Mutex<u64>>` via the `AllocSharedLocal`
/// opcode (with the matching `NativeKind` declared on the cell's
/// parallel-kind track per ADR-006 §2.7.8). After promotion, every
/// outer-scope read/write of the slot
/// must go through `LoadSharedLocal` / `StoreSharedLocal` (never plain
/// `LoadLocal` / `StoreLocal`), and scope exit must emit
/// `DropSharedLocal` so the Arc strong count is released exactly once
/// per owning frame.
///
/// Keyed by the binding *name* (mirroring `boxed_locals`). Populated
/// by `compile_expr_closure` when a `var` capture escapes into a
/// closure and gets classified as `CaptureKind::Shared`.
pub(crate) shared_locals: HashSet<String>,
/// Track A.1C.3: local names that have been classified as
/// `CaptureKind::OwnedMutable` by at least one closure in the
/// current function scope. Needed because `binding_semantics_for_name`
/// can return `None` after an inner closure's `compile_function`
/// wipes the type-tracker local semantics, and we need the
/// classification to be stable across sibling closures (otherwise
/// a second closure capturing a different `let mut` local could
/// fall back to `Immutable`, nulling the layout's OwnedMutable mask
/// bit and triggering a layout mismatch in `op_make_closure`).
pub(crate) owned_mutable_locals: HashSet<String>,
/// Session 1 (Rust-move semantics for `let mut`): names of `let mut`
/// local bindings that have been **moved by value into a closure
/// capture** (i.e. classified as `CaptureKind::OwnedMutable` and
/// emitted at `op_make_closure` time as `Box::into_raw(Box::new(bits))`).
/// After the move, the outer slot holds only a stale snapshot of the
/// initial value — every subsequent outer-scope read or write of the
/// same binding is a compile error ("use-after-move").
///
/// Stored as `name → span-of-the-capturing-closure` so the diagnostic
/// can point the user at the exact capture site that consumed the
/// binding. Populated in `compile_expr_closure`, consulted in
/// `compile_expr_identifier` and `compile_expr_assign`. Saved /
/// restored across nested `compile_function` calls, mirroring the
/// `shared_locals` / `owned_mutable_locals` discipline.
pub(crate) captured_let_mut_moved: HashMap<String, Span>,
/// Track A.1C.3: module-binding slots that have been promoted to
/// `Arc<parking_lot::Mutex<u64>>` via `AllocSharedModuleBinding`
/// (with the matching `NativeKind` declared on the cell's
/// parallel-kind track per ADR-006 §2.7.8).
/// After promotion, every outer-scope read/write of the binding must
/// go through `LoadSharedModuleBinding` / `StoreSharedModuleBinding`
/// (never plain `LoadModuleBinding` / `StoreModuleBinding`). Keyed
/// by the binding's **scoped name** — the same key used by
/// `resolve_scoped_module_binding_name` and the `module_bindings`
/// index map. Populated by `compile_expr_closure` when a
/// module-scope `var` is captured mutably.
pub(crate) shared_module_bindings: HashSet<String>,
/// Track A.1C.2: per-scope stack of slot indices that need a
/// `DropSharedLocal` opcode at scope exit, mirroring the
/// `ownership_drop_locals` discipline. Push in lockstep with
/// `push_drop_scope`; pop and emit in lockstep with `pop_drop_scope`.
pub(crate) shared_drop_locals: Vec<Vec<u16>>,
/// Active permission set for capability checking.
///
/// When set, imported stdlib functions are checked against capability_tags.
/// If a function requires a permission not in this set, a compile error is
/// emitted and the function never enters bytecode.
///
/// `None` means no checking (backwards-compatible default).
pub(crate) permission_set: Option<shape_abi_v1::PermissionSet>,
// -- Content-addressed blob tracking --
/// Active blob builder (set while compiling a function body).
pub(crate) current_blob_builder: Option<FunctionBlobBuilder>,
/// Completed function blobs (finalized with content hash).
pub(crate) completed_blobs: Vec<FunctionBlob>,
/// Map from function name to content hash (populated after finalization).
pub(crate) blob_name_to_hash: HashMap<String, FunctionHash>,
/// The content-addressed program produced alongside BytecodeProgram.
pub(crate) content_addressed_program: Option<ContentAddressedProgram>,
/// Content hash per compiled function index (function_id -> blob hash).
/// This is the stable identity bridge for the flat runtime format.
pub(crate) function_hashes_by_id: Vec<Option<FunctionHash>>,
/// Optional blob-level cache for incremental compilation.
/// When set, compiled blobs are stored after finalization and looked up
/// by content hash to avoid redundant work across compilations.
pub(crate) blob_cache: Option<BlobCache>,
/// Temporary function name aliases for comptime replace body.
/// Maps alias (e.g., `__original__`) to actual function name (e.g., `__original__myFunc`).
/// Set before compiling a replacement body and cleared after.
pub(crate) function_aliases: HashMap<String, String>,
/// Parameters of the function currently being compiled.
/// Used by match exhaustiveness checking to fall back to type annotations
/// when the type inference engine cannot resolve a parameter's type.
pub(crate) current_function_params: Vec<shape_ast::ast::FunctionParameter>,
/// Legacy cache of function names collected from stdlib-loaded modules.
///
/// Internal builtin access is now gated by per-definition declaring-module
/// provenance, not by membership in this set.
pub stdlib_function_names: HashSet<String>,
/// Per-function flag: when true, `get_builtin_function` resolves `__*` names.
/// Toggled during compilation for definitions originating from `std::*`.
pub(crate) allow_internal_builtins: bool,
/// Package-scoped native library resolutions for the current host.
pub(crate) native_resolution_context:
Option<shape_runtime::native_resolution::NativeResolutionSet>,
/// Active synthetic MIR context while compiling non-function code.
pub(crate) non_function_mir_context_stack: Vec<String>,
/// MIR lowered for compiled functions and synthetic non-function contexts.
pub(crate) mir_functions: HashMap<String, crate::mir::types::MirFunction>,
/// Borrow analyses produced from lowered MIR for compiled functions and
/// synthetic non-function contexts.
pub(crate) mir_borrow_analyses: HashMap<String, crate::mir::BorrowAnalysis>,
/// Storage plans produced by the storage planning pass for each function.
/// Maps function name to the plan mapping each MIR slot to a `BindingStorageClass`.
pub(crate) mir_storage_plans: HashMap<String, crate::mir::StoragePlan>,
/// Per-function borrow summaries for interprocedural alias checking.
/// Describes which parameters conflict and must not alias at call sites.
pub(crate) function_borrow_summaries: HashMap<String, crate::mir::FunctionBorrowSummary>,
/// Per-function mapping from AST spans to MIR program points.
/// Used to bridge the bytecode compiler (which knows AST spans) to
/// MIR ownership decisions (which are keyed by `Point`).
pub(crate) mir_span_to_point:
HashMap<String, HashMap<shape_ast::ast::Span, crate::mir::types::Point>>,
/// Field-level definite-initialization and liveness analyses for compiled functions.
pub(crate) mir_field_analyses: HashMap<String, crate::mir::FieldAnalysis>,
/// Graph-compiled namespace map: local namespace name -> canonical module path.
/// Populated during graph-driven compilation to resolve qualified names.
pub(crate) graph_namespace_map: HashMap<String, String>,
/// Module dependency graph (set during graph-driven compilation).
pub(crate) module_graph: Option<std::sync::Arc<crate::module_graph::ModuleGraph>>,
/// Per-local-slot concrete type table for the function currently being compiled.
pub(crate) current_function_local_concrete_types: HashMap<u16, shape_value::v2::ConcreteType>,
/// v0.3 WS-6 — per-module-binding concrete type table, populated at
/// let-binding time from the binding's explicit `TypeAnnotation`.
///
/// Consumed by the monomorphization call-site resolver
/// (`identifier_concrete_type`) so a generic free-function call whose
/// argument is a variable with an explicit struct / enum / `Option<T>` /
/// `Result<T, E>` / `HashMap<K, V>` annotation can bind its type
/// parameter — `let n: Option<int> = ...; id(n)`. The array / map
/// element side-tables (`module_binding_array_element_types`,
/// `module_binding_map_key_value_types`) already cover the
/// container-element cases; this table covers the remaining
/// fully-annotated shapes.
pub(crate) module_binding_concrete_types: HashMap<u16, shape_value::v2::ConcreteType>,
/// Monomorphization cache for generic function specialization.
pub(crate) monomorphization_cache: monomorphization::cache::MonomorphizationCache,
/// BUG3 — cycle detector for generic method / free-function monomorphization.
///
/// Holds the set of `mono_key`s whose specialization is currently being
/// compiled further down the call stack. If `ensure_monomorphic_function`
/// is (re-)entered for a key that is already in-progress, it means the
/// specialized body is transitively trying to resolve itself before its
/// own `compile_function` has finished — without the guard this would
/// overflow the compiler stack or cache the wrong index. The entry is
/// inserted BEFORE the inner `compile_function` call and removed right
/// after, whether compilation succeeded or failed.
///
/// Note: direct self-recursion in the body is already handled by the
/// cache-insert-before-compile behaviour; this guard only fires on the
/// pathological transitive-resolution cycle.
pub(crate) monomorphization_in_progress: std::collections::HashSet<String>,
/// Monotonic counter for monomorphization specialization IDs.
pub(crate) next_monomorphization_id: u64,
/// Phase C — running count of closure-aware specializations emitted in
/// the current module. When this exceeds
/// [`monomorphization::cache::DEFAULT_CLOSURE_SPECIALIZATION_BUDGET`],
/// further closure-aware specializations bail back to the generic
/// (non-inlined) dispatch path.
pub(crate) closure_specialization_count: u32,
}
impl Default for BytecodeCompiler {
fn default() -> Self {
Self::new()
}
}
mod compiler_impl_initialization;
mod compiler_impl_reference_model;
/// Infer effective reference parameters and mutation behavior without compiling bytecode.
///
/// Returns `(inferred_ref_params, inferred_ref_mutates)` keyed by function name.
/// - `inferred_ref_params[f][i] == true` means parameter `i` of `f` is inferred/treated as ref.
/// - `inferred_ref_mutates[f][i] == true` means that reference parameter is mutating (`&mut`).
pub fn infer_reference_model(
program: &Program,
) -> (HashMap<String, Vec<bool>>, HashMap<String, Vec<bool>>) {
let (inferred_ref_params, inferred_ref_mutates, _, _, _, _, _) =
BytecodeCompiler::infer_reference_model(program);
(inferred_ref_params, inferred_ref_mutates)
}
/// Infer effective parameter pass modes (`ByValue` / `ByRefShared` / `ByRefExclusive`)
/// keyed by function name.
pub fn infer_param_pass_modes(program: &Program) -> HashMap<String, Vec<ParamPassMode>> {
let (inferred_ref_params, inferred_ref_mutates, _, _, _, _, _) =
BytecodeCompiler::infer_reference_model(program);
BytecodeCompiler::build_param_pass_mode_map(
program,
&inferred_ref_params,
&inferred_ref_mutates,
)
}
// ADR-006 §2.7.4 / §2.7.7 — Phase 2c deferral.
//
// `compiler_tests.rs` is a deep test harness that uses `eval()`-style
// helpers returning the deleted `shape_value::ValueWord`. Per playbook
// §7 REVISED #4, the correct surface for a non-migratable test site is
// `cfg(any())`-gating rather than reintroducing the §2.7.7 forbidden
// carrier. Re-enabling is Phase 2c work tracked in playbook §10's
// Wave-β B12 deferral pattern.
#[cfg(any())]
#[path = "compiler_tests.rs"]
mod compiler_deep;
pub(crate) mod v2_array_emission;
pub(crate) mod v2_map_emission;
pub(crate) mod v2_typed_emission;
pub(crate) mod v2_typed_map_emission;
// ADR-006 §2.7.27 / Item 4 ruling (W17-mutation-writeback, 2026-05-12):
// compile-time write-back emission for `&mut self` opt-in methods on
// COW container receivers (HashSet / HashMap / Array / Deque /
// PriorityQueue / TypedArray).
pub(crate) mod mutation_writeback;