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
//! Destructure patterns - extracting values from compound structures
use crate::bytecode::{Constant, Instruction, OpCode, Operand};
use crate::executor::typed_object_ops::field_type_to_tag;
use crate::type_tracking::VariableTypeInfo;
use shape_ast::ast::{DecompositionBinding, TypeAnnotation};
use shape_ast::error::{Result, ShapeError};
use crate::compiler::BytecodeCompiler;
impl BytecodeCompiler {
fn schema_from_last_expr_type_info(&self) -> Option<u32> {
self.last_expr_type_info
.as_ref()
.and_then(|info| info.schema_id)
}
fn resolve_object_destructure_schema(
&mut self,
fields: &[shape_ast::ast::ObjectPatternField],
) -> Option<u32> {
if let Some(schema_id) = self.last_expr_schema {
return Some(schema_id);
}
if let Some(schema_id) = self.schema_from_last_expr_type_info() {
return Some(schema_id);
}
let explicit_fields: Vec<&str> = fields
.iter()
.filter_map(|field| match field.pattern {
shape_ast::ast::DestructurePattern::Rest(_) => None,
_ => Some(field.key.as_str()),
})
.collect();
// W17.2-C §4.D.5 migration: destructure-pattern field types are
// unavailable here (we're inferring schema FROM the pattern);
// route through typed variant with FieldType::Any per field.
// Verification-pass safety net catches via `__inline_obj_*`.
let typed_fields: Vec<(&str, shape_runtime::type_schema::FieldType)> = explicit_fields
.iter()
.map(|n| (*n, shape_runtime::type_schema::FieldType::Any))
.collect();
Some(
self.type_tracker
.register_inline_object_schema_typed(&typed_fields),
)
}
fn resolve_decomposition_source_schema(
&mut self,
resolved_bindings: &[(Vec<String>, u32)],
) -> Option<u32> {
if let Some(schema_id) = self.last_expr_schema {
return Some(schema_id);
}
if let Some(schema_id) = self.schema_from_last_expr_type_info() {
return Some(schema_id);
}
let mut ordered_fields: Vec<&str> = Vec::new();
let mut seen = std::collections::HashSet::new();
for (fields, _) in resolved_bindings {
for field in fields {
if seen.insert(field.as_str()) {
ordered_fields.push(field.as_str());
}
}
}
// W17.2-C §4.D.5 migration: decomposition-source schema is
// inferred from the destructure bindings; no per-field types
// available. Route through typed variant with FieldType::Any.
let typed_fields: Vec<(&str, shape_runtime::type_schema::FieldType)> = ordered_fields
.iter()
.map(|n| (*n, shape_runtime::type_schema::FieldType::Any))
.collect();
Some(
self.type_tracker
.register_inline_object_schema_typed(&typed_fields),
)
}
fn resolve_typed_field_operand_destructure(
&self,
schema_id: u32,
field_name: &str,
) -> Option<Operand> {
if schema_id > u16::MAX as u32 {
return None;
}
self.type_tracker
.schema_registry()
.get_by_id(schema_id)
.and_then(|schema| {
schema
.get_field(field_name)
.map(|field| Operand::TypedField {
type_id: schema_id as u16,
field_idx: field.index as u16,
field_type_tag: field_type_to_tag(&field.field_type),
})
})
}
/// Map a schema `FieldType` to a tracked-type-name (`int`, `number`,
/// `bool`, `string`, `decimal`) for destructured-binding type
/// propagation. Mirrors the match-path mapping at
/// `compiler/patterns/binding.rs` (`Pattern::Object` arm). Returns
/// `None` for non-scalar field types (the binding then carries no
/// scalar hint — a nested struct field is handled separately via
/// `last_expr_schema`).
fn destructure_field_scalar_type_name(
field_type: &shape_runtime::type_schema::FieldType,
) -> Option<&'static str> {
use shape_runtime::type_schema::FieldType;
match field_type {
FieldType::I64 => Some("int"),
FieldType::F64 => Some("number"),
FieldType::Bool => Some("bool"),
FieldType::String => Some("string"),
FieldType::Decimal => Some("decimal"),
FieldType::I8 => Some("i8"),
FieldType::U8 => Some("u8"),
FieldType::I16 => Some("i16"),
FieldType::U16 => Some("u16"),
FieldType::I32 => Some("i32"),
FieldType::U32 => Some("u32"),
FieldType::U64 => Some("u64"),
_ => None,
}
}
/// WS-4 4b: propagate the schema field's type onto the
/// `last_expr_*` tracker state BEFORE the recursive
/// `compile_destructure_pattern*` call, so the destructured binding
/// inherits a proven compile-time kind. Without this, `let { x, y }
/// = p` over a `Point { x: int, y: int }` leaves `x` and `y` with
/// no proven kind and `x + y` fails `prove_native_kind()`.
///
/// The match-path enum/struct codegen (`binding.rs`) already does
/// this; this is the destructure-path twin. Sets `last_expr_schema`
/// for nested `Object`-typed fields so a nested `let { a: { b } }`
/// destructure resolves the inner schema; sets
/// `last_expr_numeric_type` / `last_expr_type_info` for scalar
/// fields so `let_decl_storage_hint()` emits a typed `StoreLocal`.
fn seed_destructure_field_type(&mut self, schema_id: u32, field_key: &str) {
use shape_runtime::type_schema::FieldType;
// Default: clear — the extracted value is a scalar, not the
// parent TypedObject. Overridden below when the field type is
// recognised.
self.last_expr_schema = None;
self.last_expr_type_info = None;
self.last_expr_numeric_type = None;
let Some(field_type) = self
.type_tracker
.schema_registry()
.get_by_id(schema_id)
.and_then(|schema| schema.get_field(field_key))
.map(|field| field.field_type.clone())
else {
return;
};
match &field_type {
FieldType::Object(type_name) => {
// Nested struct field — propagate the inner schema so a
// nested object destructure (`let { p: { x } } = …`)
// resolves the inner field operands.
if let Some(nested) =
self.type_tracker.schema_registry().get(type_name.as_str())
{
self.last_expr_schema = Some(nested.id);
self.last_expr_type_info = Some(VariableTypeInfo::known(
nested.id,
type_name.clone(),
));
}
}
// W17.3-4.2 — per-container destructure narrowing. When the
// schema field is a typed container (`Array<T>`, `HashMap<K,
// V>`, `Set<T>`), the destructured binding inherits the
// container's surface type-info for downstream inference.
// Per audit §4.B.2 + close-gate signal §5.B "pattern
// destructuring on HashMap/Set extracts key/value/element
// types correctly".
//
// The bidirectional-narrowing call site in
// `compile_destructure_pattern` consumes
// `last_expr_type_info` for typed-receiver dispatch; setting
// it to the container's outer-shape name lets the downstream
// `.iter()` / `.entries()` / `.get(k)` calls resolve to the
// correct PHF method registry without falling back to a
// dynamic dispatch path. The element/key/value `FieldType`s
// remain accessible via the schema-registry lookup at the
// consumer site (no separate parallel discriminator — ADR-005
// §1 single-discriminator preserved; the container variants
// carry the inner FieldTypes inline).
FieldType::Array(_) => {
self.last_expr_type_info =
Some(VariableTypeInfo::named("array".to_string()));
}
FieldType::HashMap { .. } => {
self.last_expr_type_info =
Some(VariableTypeInfo::named("hashmap".to_string()));
}
FieldType::Set(_) => {
self.last_expr_type_info =
Some(VariableTypeInfo::named("set".to_string()));
}
_ => {
if let Some(tn) = Self::destructure_field_scalar_type_name(&field_type) {
let info = VariableTypeInfo::named(tn.to_string());
match &field_type {
FieldType::I64 => {
self.last_expr_numeric_type =
Some(crate::type_tracking::NumericType::Int);
}
FieldType::F64 => {
self.last_expr_numeric_type =
Some(crate::type_tracking::NumericType::Number);
}
FieldType::Decimal => {
self.last_expr_numeric_type =
Some(crate::type_tracking::NumericType::Decimal);
}
FieldType::I8 => {
self.last_expr_numeric_type = Some(
crate::type_tracking::NumericType::IntWidth(
shape_ast::IntWidth::I8,
),
);
}
FieldType::U8 => {
self.last_expr_numeric_type = Some(
crate::type_tracking::NumericType::IntWidth(
shape_ast::IntWidth::U8,
),
);
}
FieldType::I16 => {
self.last_expr_numeric_type = Some(
crate::type_tracking::NumericType::IntWidth(
shape_ast::IntWidth::I16,
),
);
}
FieldType::U16 => {
self.last_expr_numeric_type = Some(
crate::type_tracking::NumericType::IntWidth(
shape_ast::IntWidth::U16,
),
);
}
FieldType::I32 => {
self.last_expr_numeric_type = Some(
crate::type_tracking::NumericType::IntWidth(
shape_ast::IntWidth::I32,
),
);
}
FieldType::U32 => {
self.last_expr_numeric_type = Some(
crate::type_tracking::NumericType::IntWidth(
shape_ast::IntWidth::U32,
),
);
}
FieldType::U64 => {
self.last_expr_numeric_type = Some(
crate::type_tracking::NumericType::IntWidth(
shape_ast::IntWidth::U64,
),
);
}
_ => {}
}
self.last_expr_type_info = Some(info);
}
}
}
}
/// WS-4 4b: after the recursive destructure call has declared a
/// binding for a plain `Identifier` field pattern, stamp the schema
/// field's type onto that binding's tracker entry. The `Identifier`
/// arm only records type info when `last_expr_schema` is set
/// (nested-object fields); scalar fields need this explicit fixup so
/// `get_local_type()` / `get_binding_type()` resolves for the
/// downstream `x + y`.
///
/// `is_global` selects the module-binding tracker
/// (`set_module_binding_type_info`) for the top-level
/// `compile_destructure_pattern_global` path, or the local tracker
/// (`set_local_type_info`) for the function-scope path.
fn stamp_destructure_binding_type(
&mut self,
field_pattern: &shape_ast::ast::DestructurePattern,
schema_id: u32,
field_key: &str,
is_global: bool,
) {
use shape_ast::ast::DestructurePattern;
let DestructurePattern::Identifier(name, _) = field_pattern else {
return;
};
let Some(field_type) = self
.type_tracker
.schema_registry()
.get_by_id(schema_id)
.and_then(|schema| schema.get_field(field_key))
.map(|field| field.field_type.clone())
else {
return;
};
let type_name: Option<String> = match &field_type {
shape_runtime::type_schema::FieldType::Object(tn) => Some(tn.clone()),
other => {
Self::destructure_field_scalar_type_name(other).map(|s| s.to_string())
}
};
let Some(tn) = type_name else {
return;
};
if is_global {
if let Some(slot) = self.module_bindings.get(name).copied() {
self.set_module_binding_type_info(slot, &tn);
}
} else if let Some(local_idx) = self.resolve_local(name) {
self.set_local_type_info(local_idx, &tn);
}
}
/// Compile destructuring pattern for value on stack
/// Assumes value is already on the stack
pub(in crate::compiler) fn compile_destructure_pattern(
&mut self,
pattern: &shape_ast::ast::DestructurePattern,
) -> Result<()> {
use shape_ast::ast::DestructurePattern;
match pattern {
DestructurePattern::Identifier(name, _) => {
// Simple case - store in local
let local_idx = self.declare_local(name)?;
// E+5.5 Unit C step 1: emit typed `StoreLocal<Kind>` for
// proven Int / Bool / F64 / sub-i64-width slots so the
// post-Unit-A native producer (PushConst Int / typed
// arithmetic result) round-trips through the slot
// without NaN-tag injection. Polymorphic fallback for
// unproven hints.
//
// Per ADR-006 §2.7.5.1, `let_decl_storage_hint` returns
// `Option<StorageHint>` (no `Unknown` sentinel). On `None`
// emit the polymorphic legacy `StoreLocal`.
match self.let_decl_storage_hint() {
Some(hint) => self.emit_store_local_for_hint(local_idx, hint),
None => {
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(local_idx)),
));
}
}
// Track schema for typed merge optimization
if let Some(schema_id) = self.last_expr_schema {
self.type_tracker.set_local_type(
local_idx,
VariableTypeInfo::known(schema_id, format!("__typed_obj_{}", schema_id)),
);
}
Ok(())
}
DestructurePattern::Array(patterns) => {
// WS-3: the array rest-pattern `let [a, ...rest] = xs` is
// v0.4-out-of-scope as a feature. At HEAD the `Rest`
// sub-pattern compiled a `SliceAccess` path that, on the
// common runtime shape, surfaced the internal-jargon
// uncaught-exception dump. Reject it CLEANLY at compile
// time instead — a compile-time `SemanticError` never
// reaches `handle_exception`.
if patterns
.iter()
.any(|p| matches!(p, DestructurePattern::Rest(_)))
{
return Err(ShapeError::SemanticError {
message: "array rest-pattern (`[a, ...rest]`) is not supported"
.to_string(),
location: None,
});
}
let value_local = self.declare_temp_local("__destructure_array_")?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(value_local)),
));
self.emit_destructure_type_check(
value_local,
"array",
"Cannot destructure non-array value as array",
)?;
for (index, pat) in patterns.iter().enumerate() {
if let DestructurePattern::Rest(inner) = pat {
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
let idx_const = self.program.add_constant(Constant::Number(index as f64));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(idx_const)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
self.emit(Instruction::simple(OpCode::Length));
self.emit(Instruction::simple(OpCode::SliceAccess));
self.compile_destructure_pattern(inner)?;
break;
}
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
let idx_const = self.program.add_constant(Constant::Number(index as f64));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(idx_const)),
));
self.emit(Instruction::simple(OpCode::GetProp));
self.compile_destructure_pattern(pat)?;
}
Ok(())
}
DestructurePattern::Object(fields) => {
let value_local = self.declare_temp_local("__destructure_object_")?;
let object_schema = self.resolve_object_destructure_schema(fields);
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(value_local)),
));
self.emit_destructure_type_check(
value_local,
"object",
"Cannot destructure non-object value as object",
)?;
let mut rest_pattern: Option<&DestructurePattern> = None;
let mut rest_excluded = Vec::new();
let schema_id = object_schema.ok_or_else(|| ShapeError::SemanticError {
message: "Object destructuring requires a compile-time known schema. Runtime property lookup is disabled.".to_string(),
location: None,
})?;
for field in fields {
if let DestructurePattern::Rest(inner) = &field.pattern {
rest_pattern = Some(inner.as_ref());
continue;
}
rest_excluded.push(field.key.clone());
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
let operand = self
.resolve_typed_field_operand_destructure(schema_id, &field.key)
.ok_or_else(|| ShapeError::SemanticError {
message: format!(
"Field '{}' is not declared in object schema for destructuring.",
field.key
),
location: None,
})?;
self.emit(Instruction::new(OpCode::GetFieldTyped, Some(operand)));
// WS-4 4b: propagate the schema field's type onto the
// tracker state so the destructured binding inherits a
// proven compile-time kind (mirrors the match-path
// propagation in `binding.rs`). Replaces the old
// unconditional `last_expr_*` clear that left `x`/`y`
// with an unknown kind.
self.seed_destructure_field_type(schema_id, &field.key);
self.compile_destructure_pattern(&field.pattern)?;
self.stamp_destructure_binding_type(
&field.pattern,
schema_id,
&field.key,
false,
);
}
if let Some(rest) = rest_pattern {
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
self.emit_object_rest(&rest_excluded, object_schema)?;
self.compile_destructure_pattern(rest)?;
}
Ok(())
}
DestructurePattern::Rest(_) => {
// Rest patterns not yet supported in VM
Err(ShapeError::RuntimeError {
message: "Rest pattern cannot be used at top level".to_string(),
location: None,
})
}
DestructurePattern::Decomposition(bindings) => {
// Decomposition extracts component types from intersection (A+B)
// Splits the intersection value into separate objects by type
let value_local = self.declare_temp_local("__decomposition_")?;
let mut resolved_bindings = Vec::with_capacity(bindings.len());
for binding in bindings {
let (fields, schema_id) = self.resolve_decomposition_binding(binding)?;
resolved_bindings.push((binding.name.clone(), fields, schema_id));
}
let source_schema_id = self
.resolve_decomposition_source_schema(
&resolved_bindings
.iter()
.map(|(_, fields, schema_id)| (fields.clone(), *schema_id))
.collect::<Vec<_>>(),
)
.ok_or_else(|| ShapeError::SemanticError {
message: "Decomposition requires compile-time known source schema. Runtime property lookup is disabled.".to_string(),
location: None,
})?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(value_local)),
));
for (binding_name, fields, schema_id) in resolved_bindings {
for field_name in &fields {
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
let operand = self
.resolve_typed_field_operand_destructure(source_schema_id, field_name)
.ok_or_else(|| ShapeError::SemanticError {
message: format!(
"Field '{}' is not declared in decomposition source schema.",
field_name
),
location: None,
})?;
self.emit(Instruction::new(OpCode::GetFieldTyped, Some(operand)));
}
self.emit(Instruction::new(
OpCode::NewTypedObject,
Some(Operand::TypedObjectAlloc {
schema_id: schema_id as u16,
field_count: fields.len() as u16,
}),
));
let local_idx = self.declare_local(&binding_name)?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(local_idx)),
));
let schema_name = self
.type_tracker
.schema_registry()
.get_by_id(schema_id)
.map(|s| s.name.clone())
.unwrap_or_else(|| format!("__typed_obj_{}", schema_id));
self.type_tracker
.set_local_type(local_idx, VariableTypeInfo::known(schema_id, schema_name));
}
Ok(())
}
}
}
pub(in crate::compiler) fn compile_destructure_pattern_global(
&mut self,
pattern: &shape_ast::ast::DestructurePattern,
) -> Result<()> {
use shape_ast::ast::DestructurePattern;
match pattern {
DestructurePattern::Identifier(name, _) => {
let binding_idx = self.get_or_create_module_binding(name);
self.emit(Instruction::new(
OpCode::StoreModuleBinding,
Some(Operand::ModuleBinding(binding_idx)),
));
// Track schema for typed merge optimization
if let Some(schema_id) = self.last_expr_schema {
self.type_tracker.set_binding_type(
binding_idx,
VariableTypeInfo::known(schema_id, format!("__typed_obj_{}", schema_id)),
);
}
Ok(())
}
DestructurePattern::Array(patterns) => {
// WS-3: the array rest-pattern `let [a, ...rest] = xs` is
// v0.4-out-of-scope as a feature. At HEAD the `Rest`
// sub-pattern compiled a `SliceAccess` path that, on the
// common runtime shape, surfaced the internal-jargon
// uncaught-exception dump. Reject it CLEANLY at compile
// time instead — a compile-time `SemanticError` never
// reaches `handle_exception`.
if patterns
.iter()
.any(|p| matches!(p, DestructurePattern::Rest(_)))
{
return Err(ShapeError::SemanticError {
message: "array rest-pattern (`[a, ...rest]`) is not supported"
.to_string(),
location: None,
});
}
let value_local = self.declare_temp_local("__destructure_array_")?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(value_local)),
));
self.emit_destructure_type_check(
value_local,
"array",
"Cannot destructure non-array value as array",
)?;
for (index, pat) in patterns.iter().enumerate() {
if let DestructurePattern::Rest(inner) = pat {
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
let idx_const = self.program.add_constant(Constant::Number(index as f64));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(idx_const)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
self.emit(Instruction::simple(OpCode::Length));
self.emit(Instruction::simple(OpCode::SliceAccess));
self.compile_destructure_pattern_global(inner)?;
break;
}
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
let idx_const = self.program.add_constant(Constant::Number(index as f64));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(idx_const)),
));
self.emit(Instruction::simple(OpCode::GetProp));
self.compile_destructure_pattern_global(pat)?;
}
Ok(())
}
DestructurePattern::Object(fields) => {
let value_local = self.declare_temp_local("__destructure_object_")?;
let object_schema = self.resolve_object_destructure_schema(fields);
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(value_local)),
));
self.emit_destructure_type_check(
value_local,
"object",
"Cannot destructure non-object value as object",
)?;
let mut rest_pattern: Option<&DestructurePattern> = None;
let mut rest_excluded = Vec::new();
let schema_id = object_schema.ok_or_else(|| ShapeError::SemanticError {
message: "Object destructuring requires a compile-time known schema. Runtime property lookup is disabled.".to_string(),
location: None,
})?;
for field in fields {
if let DestructurePattern::Rest(inner) = &field.pattern {
rest_pattern = Some(inner.as_ref());
continue;
}
rest_excluded.push(field.key.clone());
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
let operand = self
.resolve_typed_field_operand_destructure(schema_id, &field.key)
.ok_or_else(|| ShapeError::SemanticError {
message: format!(
"Field '{}' is not declared in object schema for destructuring.",
field.key
),
location: None,
})?;
self.emit(Instruction::new(OpCode::GetFieldTyped, Some(operand)));
// WS-4 4b: propagate the schema field's type onto the
// tracker state so the destructured binding inherits a
// proven compile-time kind (mirrors the match-path
// propagation in `binding.rs`). Replaces the old
// unconditional `last_expr_*` clear that left `x`/`y`
// with an unknown kind.
self.seed_destructure_field_type(schema_id, &field.key);
self.compile_destructure_pattern_global(&field.pattern)?;
self.stamp_destructure_binding_type(
&field.pattern,
schema_id,
&field.key,
true,
);
}
if let Some(rest) = rest_pattern {
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
self.emit_object_rest(&rest_excluded, object_schema)?;
self.compile_destructure_pattern_global(rest)?;
}
Ok(())
}
DestructurePattern::Rest(_) => Err(ShapeError::RuntimeError {
message: "Rest pattern cannot be used at top level".to_string(),
location: None,
}),
DestructurePattern::Decomposition(bindings) => {
// Decomposition extracts component types from intersection (module_binding version)
let value_local = self.declare_temp_local("__decomposition_")?;
let mut resolved_bindings = Vec::with_capacity(bindings.len());
for binding in bindings {
let (fields, schema_id) = self.resolve_decomposition_binding(binding)?;
resolved_bindings.push((binding.name.clone(), fields, schema_id));
}
let source_schema_id = self
.resolve_decomposition_source_schema(
&resolved_bindings
.iter()
.map(|(_, fields, schema_id)| (fields.clone(), *schema_id))
.collect::<Vec<_>>(),
)
.ok_or_else(|| ShapeError::SemanticError {
message: "Decomposition requires compile-time known source schema. Runtime property lookup is disabled.".to_string(),
location: None,
})?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(value_local)),
));
for (binding_name, fields, schema_id) in resolved_bindings {
for field_name in &fields {
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
let operand = self
.resolve_typed_field_operand_destructure(source_schema_id, field_name)
.ok_or_else(|| ShapeError::SemanticError {
message: format!(
"Field '{}' is not declared in decomposition source schema.",
field_name
),
location: None,
})?;
self.emit(Instruction::new(OpCode::GetFieldTyped, Some(operand)));
}
self.emit(Instruction::new(
OpCode::NewTypedObject,
Some(Operand::TypedObjectAlloc {
schema_id: schema_id as u16,
field_count: fields.len() as u16,
}),
));
let binding_idx = self.get_or_create_module_binding(&binding_name);
self.emit(Instruction::new(
OpCode::StoreModuleBinding,
Some(Operand::ModuleBinding(binding_idx)),
));
let schema_name = self
.type_tracker
.schema_registry()
.get_by_id(schema_id)
.map(|s| s.name.clone())
.unwrap_or_else(|| format!("__typed_obj_{}", schema_id));
self.type_tracker.set_binding_type(
binding_idx,
VariableTypeInfo::known(schema_id, schema_name),
);
}
Ok(())
}
}
}
pub(in crate::compiler) fn compile_destructure_assignment(
&mut self,
pattern: &shape_ast::ast::DestructurePattern,
) -> Result<()> {
use shape_ast::ast::DestructurePattern;
match pattern {
DestructurePattern::Identifier(name, _) => self.emit_store_identifier(name),
DestructurePattern::Array(patterns) => {
// WS-3: the array rest-pattern `[a, ...rest] = xs` is
// v0.4-out-of-scope as a feature. At HEAD the `Rest`
// sub-pattern compiled a `SliceAccess` path that, on the
// common runtime shape, surfaced the internal-jargon
// uncaught-exception dump. Reject it CLEANLY at compile
// time instead — a compile-time `SemanticError` never
// reaches `handle_exception`.
if patterns
.iter()
.any(|p| matches!(p, DestructurePattern::Rest(_)))
{
return Err(ShapeError::SemanticError {
message: "array rest-pattern (`[a, ...rest]`) is not supported"
.to_string(),
location: None,
});
}
let value_local = self.declare_temp_local("__assign_array_")?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(value_local)),
));
self.emit_destructure_type_check(
value_local,
"array",
"Cannot destructure non-array value as array",
)?;
for (index, pat) in patterns.iter().enumerate() {
if let DestructurePattern::Rest(inner) = pat {
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
let idx_const = self.program.add_constant(Constant::Number(index as f64));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(idx_const)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
self.emit(Instruction::simple(OpCode::Length));
self.emit(Instruction::simple(OpCode::SliceAccess));
self.compile_destructure_assignment(inner)?;
break;
}
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
let idx_const = self.program.add_constant(Constant::Number(index as f64));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(idx_const)),
));
self.emit(Instruction::simple(OpCode::GetProp));
self.compile_destructure_assignment(pat)?;
}
Ok(())
}
DestructurePattern::Object(fields) => {
let value_local = self.declare_temp_local("__assign_object_")?;
let object_schema = self.last_expr_schema;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(value_local)),
));
self.emit_destructure_type_check(
value_local,
"object",
"Cannot destructure non-object value as object",
)?;
let mut rest_pattern: Option<&DestructurePattern> = None;
let mut rest_excluded = Vec::new();
let schema_id = object_schema.ok_or_else(|| ShapeError::SemanticError {
message: "Object destructuring assignment requires a compile-time known schema. Runtime property lookup is disabled.".to_string(),
location: None,
})?;
for field in fields {
if let DestructurePattern::Rest(inner) = &field.pattern {
rest_pattern = Some(inner.as_ref());
continue;
}
rest_excluded.push(field.key.clone());
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
let operand = self.resolve_typed_field_operand_destructure(schema_id, &field.key).ok_or_else(|| ShapeError::SemanticError {
message: format!(
"Field '{}' is not declared in object schema for destructuring assignment.",
field.key
),
location: None,
})?;
self.emit(Instruction::new(OpCode::GetFieldTyped, Some(operand)));
self.compile_destructure_assignment(&field.pattern)?;
}
if let Some(rest) = rest_pattern {
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
self.emit_object_rest(&rest_excluded, object_schema)?;
self.compile_destructure_assignment(rest)?;
}
Ok(())
}
DestructurePattern::Rest(_) => Err(ShapeError::RuntimeError {
message: "Rest pattern cannot be used at top level".to_string(),
location: None,
}),
DestructurePattern::Decomposition(bindings) => {
// Decomposition extracts component types from intersection (assignment version)
let value_local = self.declare_temp_local("__decomposition_")?;
let source_schema_id = self.last_expr_schema.ok_or_else(|| {
ShapeError::SemanticError {
message: "Decomposition assignment requires compile-time known source schema. Runtime property lookup is disabled.".to_string(),
location: None,
}
})?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(value_local)),
));
for binding in bindings {
let (fields, schema_id) = self.resolve_decomposition_binding(binding)?;
for field_name in &fields {
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(value_local)),
));
let operand = self
.resolve_typed_field_operand_destructure(source_schema_id, field_name)
.ok_or_else(|| ShapeError::SemanticError {
message: format!(
"Field '{}' is not declared in decomposition source schema.",
field_name
),
location: None,
})?;
self.emit(Instruction::new(OpCode::GetFieldTyped, Some(operand)));
}
self.emit(Instruction::new(
OpCode::NewTypedObject,
Some(Operand::TypedObjectAlloc {
schema_id: schema_id as u16,
field_count: fields.len() as u16,
}),
));
self.emit_store_identifier(&binding.name)?;
}
Ok(())
}
}
}
/// Resolve a decomposition binding's type annotation into field names and a schema ID.
/// Handles both named types (e.g. `TypeA`) and inline object types (e.g. `{x, y}`).
fn resolve_decomposition_binding(
&mut self,
binding: &DecompositionBinding,
) -> Result<(Vec<String>, u32)> {
match &binding.type_annotation {
TypeAnnotation::Object(obj_fields) => {
// Inline object type: {x, y, z} or {x: int, y: string}
// W17.2-C §4.D.5 migration: route through typed-with-Any
// (NOT per-field lowering; schema layout changes from
// Any-uniform break downstream consumers that assume
// the legacy layout — same disposition as
// `extract_object_schema_id_from_annotation` +
// function-param Object case at `functions.rs`). Per-
// field-typed schema layout migration is v0.4 W17.3+
// territory.
let fields: Vec<String> = obj_fields.iter().map(|f| f.name.clone()).collect();
let typed_fields: Vec<(&str, shape_runtime::type_schema::FieldType)> = obj_fields
.iter()
.map(|f| (f.name.as_str(), shape_runtime::type_schema::FieldType::Any))
.collect();
let schema_id = self
.type_tracker
.register_inline_object_schema_typed(&typed_fields);
Ok((fields, schema_id))
}
_ => {
// Named type: look up from struct registry
let type_name = binding.type_annotation.as_simple_name().ok_or_else(|| {
ShapeError::SemanticError {
message: "Decomposition binding requires a named type or object field set"
.to_string(),
location: Some(self.span_to_source_location(binding.span)),
}
})?;
let fields = self
.struct_types
.get(type_name)
.map(|(f, _)| f.clone())
.unwrap_or_default();
let schema_id = self
.type_tracker
.schema_registry()
.get(type_name)
.map(|s| s.id)
.unwrap_or_else(|| {
// W17.2-C §4.D.5 migration: registry miss falls
// back to typed-with-Any (no upstream field-type
// info available); verification-pass safety net.
let typed_fields: Vec<(&str, shape_runtime::type_schema::FieldType)> =
fields
.iter()
.map(|n| {
(
n.as_str(),
shape_runtime::type_schema::FieldType::Any,
)
})
.collect();
self.type_tracker
.register_inline_object_schema_typed(&typed_fields)
});
Ok((fields, schema_id))
}
}
}
}
#[cfg(test)]
mod ws3_array_rest_tests {
//! WS-3: the array rest-pattern `[a, ...rest]` is v0.4-out-of-scope.
//!
//! At HEAD the `Rest` sub-pattern compiled a `SliceAccess` path that,
//! on the common runtime shape, surfaced the internal-jargon
//! uncaught-exception dump. It must now reject CLEANLY at compile
//! time with a plain `SemanticError`.
use crate::compiler::BytecodeCompiler;
use shape_ast::parser::parse_program;
#[test]
fn ws3_array_rest_pattern_errors_cleanly() {
let code = r#"
fn run() {
let xs = [1, 2, 3, 4]
let [a, ...rest] = xs
print(a)
}
"#;
let program = parse_program(code).expect("Failed to parse");
let result = BytecodeCompiler::new().compile(&program);
assert!(
result.is_err(),
"array rest-pattern must be rejected at compile time"
);
let msg = format!("{}", result.unwrap_err());
assert!(
msg.contains("array rest-pattern") && msg.contains("not supported"),
"expected a clean array rest-pattern error, got: {}",
msg
);
// The clean error must NOT carry internal jargon.
assert!(
!msg.contains("phase-2c") && !msg.contains("ADR-006"),
"array rest-pattern error must not dump internal jargon: {}",
msg
);
}
#[test]
fn ws3_non_rest_array_destructure_compiles() {
// The non-rest `let [a, b, c] = xs` form must still compile —
// it was collateral damage of the missing `type_check_kinded`
// `"array"` Basic-name arm before the WS-3 fix.
let code = r#"
fn run() {
let xs = [10, 20, 30]
let [a, b, c] = xs
print(b)
}
"#;
let program = parse_program(code).expect("Failed to parse");
let result = BytecodeCompiler::new().compile(&program);
assert!(
result.is_ok(),
"non-rest array destructure must compile: {:?}",
result.err()
);
}
}
#[cfg(test)]
mod ws4_destructure_tests {
//! WS-4 — object-destructuring regression tests (v0.3, 2026-05-21).
//!
//! Covers 4a (VM `let { … } = obj` no longer throws) and 4b
//! (destructured binding types are propagated so `x + y` proves a
//! native kind). The 4c match struct-pattern classification tests
//! live in `compiler/patterns/binding.rs`.
use crate::test_utils::{eval, eval_result};
// ─── 4a: `let { … } = obj` runs in the VM ───────────────────────
#[test]
fn ws4_4a_global_object_destructure_runs() {
// Pre-fix: the VM `emit_destructure_type_check("object")` guard
// threw because `type_check_kinded` had no `"object"` arm.
let result = eval(
r#"
type Point { x: int, y: int }
let p = Point { x: 1, y: 2 }
let { x, y } = p
x
"#,
);
assert_eq!(result.as_i64(), Some(1));
}
#[test]
fn ws4_4a_global_object_destructure_second_field() {
let result = eval(
r#"
type Point { x: int, y: int }
let p = Point { x: 1, y: 2 }
let { x, y } = p
y
"#,
);
assert_eq!(result.as_i64(), Some(2));
}
#[test]
fn ws4_4a_function_scope_object_destructure_runs() {
let result = eval(
r#"
type Point { x: int, y: int }
fn first(p: Point) -> int { let { x, y } = p; x }
first(Point { x: 7, y: 9 })
"#,
);
assert_eq!(result.as_i64(), Some(7));
}
// ─── 4b: destructured binding types are propagated ──────────────
#[test]
fn ws4_4b_function_scope_destructured_int_add() {
// Pre-fix: `x + y` failed `prove_native_kind()` — the
// destructure path cleared `last_expr_*` and never propagated
// the schema field's `FieldType` onto the bindings.
let result = eval(
r#"
type Point { x: int, y: int }
fn sum(p: Point) -> int { let { x, y } = p; x + y }
sum(Point { x: 6, y: 8 })
"#,
);
assert_eq!(result.as_i64(), Some(14));
}
#[test]
fn ws4_4b_global_scope_destructured_int_add() {
let result = eval(
r#"
type Point { x: int, y: int }
let p = Point { x: 6, y: 8 }
let { x, y } = p
x + y
"#,
);
assert_eq!(result.as_i64(), Some(14));
}
#[test]
fn ws4_4b_destructured_number_field_add() {
let result = eval(
r#"
type P { x: number, y: number }
fn sum(p: P) -> number { let { x, y } = p; x + y }
sum(P { x: 1.5, y: 2.5 })
"#,
);
assert_eq!(result.as_f64(), Some(4.0));
}
#[test]
fn ws4_4b_nested_object_destructure() {
// The nested struct field's schema must be propagated so the
// inner `let { v } = inner` resolves its field operand and the
// inner binding inherits the `int` kind.
let result = eval(
r#"
type Inner { v: int }
type Outer { inner: Inner, k: int }
fn f(o: Outer) -> int {
let { inner, k } = o
let { v } = inner
v + k
}
f(Outer { inner: Inner { v: 5 }, k: 7 })
"#,
);
assert_eq!(result.as_i64(), Some(12));
}
#[test]
fn ws4_4b_destructured_string_field() {
// String field destructure must not fail compilation; the
// binding carries the `string` type.
let result = eval_result(
r#"
type Name { first: string, last: string }
let n = Name { first: "Ada", last: "Lovelace" }
let { first, last } = n
first
"#,
);
assert!(result.is_ok(), "string-field destructure failed: {result:?}");
}
}