shape-vm 0.3.2

Stack-based bytecode virtual machine for the Shape programming language
Documentation
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
//! Pattern binding - binding pattern matches to variables

use crate::bytecode::{Constant, Instruction, NumericWidth, OpCode, Operand};
use crate::executor::typed_object_ops::field_type_to_tag;
use crate::type_tracking::VariableTypeInfo;
use shape_ast::ast::{Literal, Pattern, PatternConstructorFields, TypeAnnotation};
use shape_ast::error::{Result, ShapeError};

use crate::compiler::BytecodeCompiler;
use super::helpers::typed_eq_opcode_for_literal;

impl BytecodeCompiler {
    fn resolve_typed_field_operand_binding(
        &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),
                    })
            })
    }

    pub(in crate::compiler) fn compile_pattern_binding(&mut self, pattern: &Pattern) -> Result<()> {
        match pattern {
            Pattern::Identifier(name) => {
                let local_idx = self.declare_local(name)?;
                self.emit(Instruction::new(
                    OpCode::StoreLocal,
                    Some(Operand::Local(local_idx)),
                ));
                Ok(())
            }
            Pattern::Typed {
                name,
                type_annotation,
            } => {
                let value_local = self.declare_temp_local("__typed_pattern_value_")?;
                self.emit(Instruction::new(
                    OpCode::StoreLocal,
                    Some(Operand::Local(value_local)),
                ));

                self.emit(Instruction::new(
                    OpCode::LoadLocal,
                    Some(Operand::Local(value_local)),
                ));
                let type_const = self
                    .program
                    .add_constant(Constant::TypeAnnotation(type_annotation.clone()));
                self.emit(Instruction::new(
                    OpCode::TypeCheck,
                    Some(Operand::Const(type_const)),
                ));
                let ok_jump = self.emit_jump(OpCode::JumpIfTrue, 0);

                let msg = self
                    .program
                    .add_constant(Constant::String("Pattern match failed".to_string()));
                self.emit(Instruction::new(
                    OpCode::PushConst,
                    Some(Operand::Const(msg)),
                ));
                self.emit(Instruction::simple(OpCode::Throw));

                self.patch_jump(ok_jump);
                let local_idx = self.declare_local(name)?;
                self.emit(Instruction::new(
                    OpCode::LoadLocal,
                    Some(Operand::Local(value_local)),
                ));
                // Emit StoreLocalTyped for width types (i8, u8, i16, etc.)
                if let TypeAnnotation::Basic(type_name) = type_annotation {
                    if let Some(w) = shape_ast::IntWidth::from_name(type_name) {
                        self.emit(Instruction::new(
                            OpCode::StoreLocalTyped,
                            Some(Operand::TypedLocal(
                                local_idx,
                                NumericWidth::from_int_width(w),
                            )),
                        ));
                        return Ok(());
                    }
                }
                self.emit(Instruction::new(
                    OpCode::StoreLocal,
                    Some(Operand::Local(local_idx)),
                ));
                Ok(())
            }
            Pattern::Wildcard => {
                self.emit(Instruction::simple(OpCode::Pop));
                Ok(())
            }
            Pattern::Literal(lit) => {
                // Stage 2.6.4: Bool patterns desugar to direct conditional
                // jump (the scrutinee on top of stack IS the bool to test).
                if let Literal::Bool(b) = lit {
                    let jump_op = if *b {
                        OpCode::JumpIfTrue
                    } else {
                        OpCode::JumpIfFalse
                    };
                    let ok_jump = self.emit_jump(jump_op, 0);
                    let msg = self
                        .program
                        .add_constant(Constant::String("Pattern match failed".to_string()));
                    self.emit(Instruction::new(
                        OpCode::PushConst,
                        Some(Operand::Const(msg)),
                    ));
                    self.emit(Instruction::simple(OpCode::Throw));
                    self.patch_jump(ok_jump);
                    return Ok(());
                }

                self.compile_literal(lit)?;
                let eq_op = typed_eq_opcode_for_literal(lit).ok_or_else(|| {
                    ShapeError::SemanticError {
                        message: format!(
                            "Pattern matching on {} literals is not yet supported",
                            lit
                        ),
                        location: None,
                    }
                })?;
                self.emit(Instruction::simple(eq_op));
                let ok_jump = self.emit_jump(OpCode::JumpIfTrue, 0);

                let msg = self
                    .program
                    .add_constant(Constant::String("Pattern match failed".to_string()));
                self.emit(Instruction::new(
                    OpCode::PushConst,
                    Some(Operand::Const(msg)),
                ));
                self.emit(Instruction::simple(OpCode::Throw));

                self.patch_jump(ok_jump);
                Ok(())
            }
            Pattern::Array(patterns) => {
                self.emit(Instruction::simple(OpCode::Dup));
                self.emit(Instruction::simple(OpCode::Length));
                // Stage 2.6.4: Length pushes int, so use Constant::Int + LtInt.
                let min_len = self
                    .program
                    .add_constant(Constant::Int(patterns.len() as i64));
                self.emit(Instruction::new(
                    OpCode::PushConst,
                    Some(Operand::Const(min_len)),
                ));
                self.emit(Instruction::simple(OpCode::LtInt));
                let ok_jump = self.emit_jump(OpCode::JumpIfFalse, 0);

                let msg = self.program.add_constant(Constant::String(format!(
                    "Array pattern requires at least {} elements",
                    patterns.len()
                )));
                self.emit(Instruction::new(
                    OpCode::PushConst,
                    Some(Operand::Const(msg)),
                ));
                self.emit(Instruction::simple(OpCode::Throw));
                self.patch_jump(ok_jump);

                for (index, pat) in patterns.iter().enumerate() {
                    self.emit(Instruction::simple(OpCode::Dup));
                    let idx_const = self.program.add_constant(Constant::Int(index as i64));
                    self.emit(Instruction::new(
                        OpCode::PushConst,
                        Some(Operand::Const(idx_const)),
                    ));
                    self.emit(Instruction::simple(OpCode::GetProp));
                    self.compile_pattern_binding(pat)?;
                }
                self.emit(Instruction::simple(OpCode::Pop));
                Ok(())
            }
            Pattern::Object(fields) => {
                let value_local = self.declare_temp_local("__pattern_obj_value_")?;
                self.emit(Instruction::new(
                    OpCode::StoreLocal,
                    Some(Operand::Local(value_local)),
                ));
                let schema_id = self.last_expr_schema.ok_or_else(|| ShapeError::SemanticError {
                    message: "Object pattern binding requires compile-time known schema. Runtime property lookup is disabled.".to_string(),
                    location: None,
                })?;
                for (key, pat) in fields {
                    self.emit(Instruction::new(
                        OpCode::LoadLocal,
                        Some(Operand::Local(value_local)),
                    ));
                    let operand = self
                        .resolve_typed_field_operand_binding(schema_id, key)
                        .ok_or_else(|| ShapeError::SemanticError {
                            message: format!(
                                "Field '{}' is not declared in object schema for pattern binding.",
                                key
                            ),
                            location: None,
                        })?;
                    self.emit(Instruction::new(OpCode::GetFieldTyped, Some(operand)));
                    self.compile_pattern_binding(pat)?;
                }
                Ok(())
            }
            Pattern::Constructor { .. } => {
                let value_local = self.declare_temp_local("__pattern_value_")?;
                self.emit(Instruction::new(
                    OpCode::StoreLocal,
                    Some(Operand::Local(value_local)),
                ));
                if let Some(schema_id) = self.last_expr_schema {
                    self.type_tracker.set_local_type(
                        value_local,
                        VariableTypeInfo::known(schema_id, format!("__typed_obj_{}", schema_id)),
                    );
                }

                let mut fail_jumps = Vec::new();
                self.compile_pattern_check_local(pattern, value_local, &mut fail_jumps, None)?;
                let ok_jump = self.emit_jump(OpCode::Jump, 0);

                for jump in fail_jumps {
                    self.patch_jump(jump);
                }

                let msg = self
                    .program
                    .add_constant(Constant::String("Pattern match failed".to_string()));
                self.emit(Instruction::new(
                    OpCode::PushConst,
                    Some(Operand::Const(msg)),
                ));
                self.emit(Instruction::simple(OpCode::Throw));

                self.patch_jump(ok_jump);
                self.compile_match_binding_local(pattern, value_local)
            }
        }
    }

    pub(in crate::compiler) fn compile_match_binding(&mut self, pattern: &Pattern) -> Result<()> {
        let value_local = self.declare_temp_local("__match_value_")?;
        if let Some(schema_id) = self.last_expr_schema {
            self.type_tracker.set_local_type(
                value_local,
                VariableTypeInfo::known(schema_id, format!("__typed_obj_{}", schema_id)),
            );
        }
        // Propagate numeric type info from the scrutinee expression so that
        // match binding variables inherit the correct storage hint (e.g., Int64).
        self.propagate_initializer_type_to_slot(value_local, true, false);
        self.emit(Instruction::new(
            OpCode::StoreLocal,
            Some(Operand::Local(value_local)),
        ));
        self.compile_match_binding_local(pattern, value_local)?;
        self.mark_value_pattern_bindings_immutable(pattern);
        self.apply_binding_semantics_to_value_pattern_bindings(
            pattern,
            Self::owned_immutable_binding_semantics(),
        );
        Ok(())
    }

    pub(in crate::compiler) fn compile_match_binding_local(
        &mut self,
        pattern: &Pattern,
        value_local: u16,
    ) -> Result<()> {
        match pattern {
            Pattern::Identifier(name) => {
                let local_idx = self.declare_local(name)?;
                // Propagate type info from the scrutinee to the binding variable
                // so that downstream expressions (e.g., function calls) can use
                // typed opcodes when the scrutinee type is known.
                if let Some(source_info) = self.type_tracker.get_local_type(value_local).cloned() {
                    self.type_tracker.set_local_type(local_idx, source_info);
                }
                self.emit(Instruction::new(
                    OpCode::LoadLocal,
                    Some(Operand::Local(value_local)),
                ));
                self.emit(Instruction::new(
                    OpCode::StoreLocal,
                    Some(Operand::Local(local_idx)),
                ));
                Ok(())
            }
            Pattern::Typed { name, .. } => {
                let local_idx = self.declare_local(name)?;
                if let Some(source_info) = self.type_tracker.get_local_type(value_local).cloned() {
                    self.type_tracker.set_local_type(local_idx, source_info);
                }
                self.emit(Instruction::new(
                    OpCode::LoadLocal,
                    Some(Operand::Local(value_local)),
                ));
                self.emit(Instruction::new(
                    OpCode::StoreLocal,
                    Some(Operand::Local(local_idx)),
                ));
                Ok(())
            }
            Pattern::Wildcard | Pattern::Literal(_) => Ok(()),
            Pattern::Array(patterns) => {
                for (idx, pat) in patterns.iter().enumerate() {
                    self.emit(Instruction::new(
                        OpCode::LoadLocal,
                        Some(Operand::Local(value_local)),
                    ));
                    let idx_const = self.program.add_constant(Constant::Number(idx as f64));
                    self.emit(Instruction::new(
                        OpCode::PushConst,
                        Some(Operand::Const(idx_const)),
                    ));
                    self.emit(Instruction::simple(OpCode::GetProp));
                    let elem_local = self.declare_temp_local("__match_elem_")?;
                    self.emit(Instruction::new(
                        OpCode::StoreLocal,
                        Some(Operand::Local(elem_local)),
                    ));
                    self.compile_match_binding_local(pat, elem_local)?;
                }
                Ok(())
            }
            Pattern::Object(fields) => {
                let schema_id = self
                    .type_tracker
                    .get_local_type(value_local)
                    .and_then(|info| info.schema_id)
                    .ok_or_else(|| ShapeError::SemanticError {
                        message: "Object match binding requires compile-time known schema. Runtime property lookup is disabled.".to_string(),
                        location: None,
                    })?;
                for (key, pat) in fields {
                    self.emit(Instruction::new(
                        OpCode::LoadLocal,
                        Some(Operand::Local(value_local)),
                    ));
                    let operand = self.resolve_typed_field_operand_binding(schema_id, key).ok_or_else(|| {
                        ShapeError::SemanticError {
                            message: format!(
                                "Field '{}' is not declared in object schema for match binding.",
                                key
                            ),
                            location: None,
                        }
                    })?;
                    self.emit(Instruction::new(
                        OpCode::GetFieldTyped,
                        Some(operand),
                    ));
                    let field_local = self.declare_temp_local("__match_field_")?;
                    // Phase 3e: propagate the schema field's type onto the
                    // temp local so the downstream binding (Pattern::Identifier
                    // or Pattern::Typed) inherits the type info via the
                    // existing source_info copy in those arms. Without this,
                    // `match obj { { x, y } => x + y }` over a TypedObject
                    // with int fields gets x and y as Unknown, breaking
                    // strict-typing.
                    if let Some(field_def) = self
                        .type_tracker
                        .schema_registry()
                        .get_by_id(schema_id)
                        .and_then(|s| s.get_field(key))
                    {
                        let field_ty = field_def.field_type.clone();
                        let type_name_opt = match &field_ty {
                            shape_runtime::type_schema::FieldType::I64 => Some("int"),
                            shape_runtime::type_schema::FieldType::F64 => Some("number"),
                            shape_runtime::type_schema::FieldType::Bool => Some("bool"),
                            shape_runtime::type_schema::FieldType::String => Some("string"),
                            shape_runtime::type_schema::FieldType::Decimal => Some("decimal"),
                            _ => None,
                        };
                        if let Some(tn) = type_name_opt {
                            self.set_local_type_info(field_local, tn);
                        }
                    }
                    self.emit(Instruction::new(
                        OpCode::StoreLocal,
                        Some(Operand::Local(field_local)),
                    ));
                    self.compile_match_binding_local(pat, field_local)?;
                }
                Ok(())
            }
            Pattern::Constructor {
                enum_name,
                variant,
                fields,
            } => match (enum_name.as_deref(), variant.as_str()) {
                (Some("Option"), "None") | (None, "None") => Ok(()),
                (Some("Option"), "Some") | (None, "Some") => {
                    if let PatternConstructorFields::Tuple(pats) = fields {
                        if pats.len() == 1 {
                            let inner_local = self.declare_temp_local("__some_inner_")?;
                            self.emit(Instruction::new(
                                OpCode::LoadLocal,
                                Some(Operand::Local(value_local)),
                            ));
                            self.emit(Instruction::simple(OpCode::UnwrapOption));
                            self.emit(Instruction::new(
                                OpCode::StoreLocal,
                                Some(Operand::Local(inner_local)),
                            ));
                            return self.compile_match_binding_local(&pats[0], inner_local);
                        }
                    }
                    Ok(())
                }
                (Some("Result"), "Ok") | (None, "Ok") | (Some("Result"), "Err") | (None, "Err") => {
                    if let PatternConstructorFields::Tuple(pats) = fields {
                        if pats.len() != 1 {
                            return Ok(());
                        }
                        let inner_local = self.declare_temp_local("__match_inner_")?;
                        self.emit(Instruction::new(
                            OpCode::LoadLocal,
                            Some(Operand::Local(value_local)),
                        ));
                        self.emit(Instruction::simple(if variant == "Ok" {
                            OpCode::UnwrapOk
                        } else {
                            OpCode::UnwrapErr
                        }));
                        self.emit(Instruction::new(
                            OpCode::StoreLocal,
                            Some(Operand::Local(inner_local)),
                        ));
                        return self.compile_match_binding_local(&pats[0], inner_local);
                    }
                    Ok(())
                }
                (Some(enum_name), _) => {
                    // Look up enum schema - must be registered (no generic fallback)
                    let resolved_name = self.resolve_type_name(enum_name);
                    if let Some(schema) = self.type_tracker.schema_registry().get(resolved_name.as_str()) {
                        if schema.get_enum_info().is_some() {
                            let schema_id = schema.id;
                            return self.compile_typed_enum_binding(
                                value_local,
                                schema_id,
                                fields,
                                Some(&resolved_name),
                                Some(variant.as_str()),
                            );
                        }
                    }
                    Err(ShapeError::SemanticError {
                        message: format!(
                            "Enum pattern '{}' requires a registered enum schema. Generic fallback is disabled.",
                            enum_name
                        ),
                        location: None,
                    })
                }
                (None, _) => {
                    // WS-4 4c: a bare `Constructor` pattern with no
                    // enum-name (`Point { x, y }`) may name a registered
                    // *struct*/TypedObject, not an enum variant. Resolve
                    // `variant` against the schema registry; if it is a
                    // non-enum schema with a struct payload, route to the
                    // `Pattern::Object` struct-pattern codegen. The
                    // bare-enum-variant reject stays only for the genuine
                    // case (no schema, or an enum schema).
                    let resolved_name = self.resolve_type_name(variant);
                    let is_struct_schema = self
                        .type_tracker
                        .schema_registry()
                        .get(resolved_name.as_str())
                        .map(|s| !s.is_enum())
                        .unwrap_or(false);
                    if is_struct_schema {
                        if let PatternConstructorFields::Struct(field_pats) = fields {
                            return self.compile_match_binding_local(
                                &Pattern::Object(field_pats.clone()),
                                value_local,
                            );
                        }
                    }
                    Err(ShapeError::SemanticError {
                        message: "Bare enum variant patterns require type-resolved enum context. Generic fallback is disabled.".to_string(),
                        location: None,
                    })
                }
            },
        }
    }

    /// Compile enum binding for TypedObject (optimized path)
    fn compile_typed_enum_binding(
        &mut self,
        value_local: u16,
        schema_id: u32,
        fields: &PatternConstructorFields,
        enum_name: Option<&str>,
        variant_name: Option<&str>,
    ) -> Result<()> {
        match fields {
            PatternConstructorFields::Unit => Ok(()),
            PatternConstructorFields::Tuple(patterns) => {
                // R8 W7: look up the per-position payload annotations
                // (parallel to the Struct arm's
                // `enum_struct_variant_fields` flow). Without this the
                // tuple-payload binders fall through to Unknown and
                // surface as "Cannot infer types for binary operation
                // `Add`: operand types are `string` and `unknown`" when
                // a downstream binop touches them.
                let variant_tuple_tys: Option<Vec<shape_ast::ast::TypeAnnotation>> =
                    match (enum_name, variant_name) {
                        (Some(en), Some(vn)) => self
                            .enum_tuple_variant_fields
                            .get(&(en.to_string(), vn.to_string()))
                            .cloned()
                            .or_else(|| {
                                en.rsplit("::").next().and_then(|bare| {
                                    self.enum_tuple_variant_fields
                                        .get(&(bare.to_string(), vn.to_string()))
                                        .cloned()
                                })
                            }),
                        _ => None,
                    };

                // Payload fields are at __payload_0, __payload_1, etc.
                for (idx, pat) in patterns.iter().enumerate() {
                    self.emit(Instruction::new(
                        OpCode::LoadLocal,
                        Some(Operand::Local(value_local)),
                    ));
                    // GetFieldTyped for __payload_{idx} (Any type)
                    self.emit(Instruction::new(
                        OpCode::GetFieldTyped,
                        Some(Operand::TypedField {
                            type_id: schema_id as u16,
                            field_idx: (idx + 1) as u16, // field 0 is __variant
                            field_type_tag: crate::executor::typed_object_ops::FIELD_TAG_ANY,
                        }),
                    ));
                    let elem_local = self.declare_temp_local("__typed_enum_elem_")?;
                    // R8 W7: propagate the variant's positional payload
                    // type onto the temp local so the downstream
                    // Identifier/Typed binding inherits it via the
                    // existing source_info copy in those arms — same
                    // shape as the struct-arm variant_fields path.
                    if let Some(ref tys) = variant_tuple_tys {
                        if let Some(ann) = tys.get(idx) {
                            if let Some(tn) =
                                BytecodeCompiler::tracked_type_name_from_annotation(ann)
                            {
                                self.set_local_type_info(elem_local, &tn);
                            }
                        }
                    }
                    self.emit(Instruction::new(
                        OpCode::StoreLocal,
                        Some(Operand::Local(elem_local)),
                    ));
                    self.compile_match_binding_local(pat, elem_local)?;
                }
                Ok(())
            }
            PatternConstructorFields::Struct(patterns) => {
                // Sweep phase 3c.x: look up the (enum, variant) struct
                // field annotations so x and y in `m::E::V { x, y } => x + y`
                // get their declared int/number type instead of falling
                // through to Unknown. The schema only stores
                // `__payload_N: Any` for variant payloads; the named
                // field types live on the side in
                // `enum_struct_variant_fields`, populated by
                // `register_enum`.
                let variant_fields: Option<
                    Vec<(String, shape_ast::ast::TypeAnnotation)>,
                > = match (enum_name, variant_name) {
                    (Some(en), Some(vn)) => self
                        .enum_struct_variant_fields
                        .get(&(en.to_string(), vn.to_string()))
                        .cloned()
                        .or_else(|| {
                            // Fall back to bare-name lookup (e.g. inside
                            // a `mod m` block, an `E::V` pattern may
                            // resolve `enum_name` differently than the
                            // qualified key).
                            en.rsplit("::").next().and_then(|bare| {
                                self.enum_struct_variant_fields
                                    .get(&(bare.to_string(), vn.to_string()))
                                    .cloned()
                            })
                        }),
                    _ => None,
                };

                // For struct payloads, we access fields by index
                for (idx, (_key, pat)) in patterns.iter().enumerate() {
                    self.emit(Instruction::new(
                        OpCode::LoadLocal,
                        Some(Operand::Local(value_local)),
                    ));
                    // GetFieldTyped for __payload_{idx} (Any type)
                    self.emit(Instruction::new(
                        OpCode::GetFieldTyped,
                        Some(Operand::TypedField {
                            type_id: schema_id as u16,
                            field_idx: (idx + 1) as u16,
                            field_type_tag: crate::executor::typed_object_ops::FIELD_TAG_ANY,
                        }),
                    ));
                    let field_local = self.declare_temp_local("__typed_enum_field_")?;
                    // Sweep phase 3c.x: propagate the variant struct
                    // field's declared type onto the temp local so the
                    // downstream Identifier/Typed binding inherits it
                    // via the existing source_info copy in those arms.
                    if let Some(ref vf) = variant_fields {
                        if let Some((_, ann)) = vf.get(idx) {
                            if let Some(tn) =
                                BytecodeCompiler::tracked_type_name_from_annotation(ann)
                            {
                                self.set_local_type_info(field_local, &tn);
                            }
                        }
                    }
                    self.emit(Instruction::new(
                        OpCode::StoreLocal,
                        Some(Operand::Local(field_local)),
                    ));
                    self.compile_match_binding_local(pat, field_local)?;
                }
                Ok(())
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::compiler::BytecodeCompiler;
    use crate::type_tracking::{BindingOwnershipClass, BindingStorageClass};
    use shape_ast::ast::Pattern;

    #[test]
    fn test_value_pattern_bindings_get_owned_semantics_recursively() {
        let mut compiler = BytecodeCompiler::new();
        compiler.push_scope();
        let left = compiler.declare_local("left").expect("declare left");
        let right = compiler.declare_local("right").expect("declare right");
        let pattern = Pattern::Object(vec![
            ("lhs".to_string(), Pattern::Identifier("left".to_string())),
            (
                "rhs".to_string(),
                Pattern::Array(vec![Pattern::Identifier("right".to_string())]),
            ),
        ]);

        compiler.apply_binding_semantics_to_value_pattern_bindings(
            &pattern,
            BytecodeCompiler::owned_mutable_binding_semantics(),
        );

        assert_eq!(
            compiler
                .type_tracker
                .get_local_binding_semantics(left)
                .map(|semantics| semantics.ownership_class),
            Some(BindingOwnershipClass::OwnedMutable)
        );
        assert_eq!(
            compiler
                .type_tracker
                .get_local_binding_semantics(left)
                .map(|semantics| semantics.storage_class),
            Some(BindingStorageClass::Direct)
        );
        assert_eq!(
            compiler
                .type_tracker
                .get_local_binding_semantics(right)
                .map(|semantics| semantics.ownership_class),
            Some(BindingOwnershipClass::OwnedMutable)
        );
    }

    // ─── WS-4 4c: `match` struct-pattern classification ─────────────
    //
    // A bare `Constructor` pattern with no enum-name (`Point { x, y }`)
    // over a registered struct/TypedObject scrutinee must route to the
    // `Pattern::Object` codegen instead of being rejected as a bare
    // enum-variant pattern. Also covers 4c defect (i): a bare
    // struct-literal `match` scrutinee parses correctly.
    use crate::test_utils::eval;

    #[test]
    fn ws4_4c_match_struct_pattern_over_variable() {
        let result = eval(
            r#"
            type Point { x: int, y: int }
            let p = Point { x: 3, y: 4 }
            match p { Point { x, y } => x + y }
            "#,
        );
        assert_eq!(result.as_i64(), Some(7));
    }

    #[test]
    fn ws4_4c_match_struct_pattern_paren_scrutinee() {
        let result = eval(
            r#"
            type Point { x: int, y: int }
            match (Point { x: 3, y: 4 }) { Point { x, y } => x + y }
            "#,
        );
        assert_eq!(result.as_i64(), Some(7));
    }

    #[test]
    fn ws4_4c_match_struct_pattern_bare_struct_literal_scrutinee() {
        // 4c defect (i): the bare struct-literal scrutinee
        // `match Point { … } { … }` previously mis-parsed the
        // struct-literal body as the match body.
        let result = eval(
            r#"
            type Point { x: int, y: int }
            match Point { x: 3, y: 4 } { Point { x, y } => x + y }
            "#,
        );
        assert_eq!(result.as_i64(), Some(7));
    }

    #[test]
    fn ws4_4c_match_struct_pattern_in_function() {
        let result = eval(
            r#"
            type Point { x: int, y: int }
            fn f(p: Point) -> int { match p { Point { x, y } => x * y } }
            f(Point { x: 10, y: 20 })
            "#,
        );
        assert_eq!(result.as_i64(), Some(200));
    }

    #[test]
    fn ws4_4c_enum_match_still_works() {
        // The classification fix must not regress enum-variant matching:
        // a bare-name enum variant with no enum context still rejects.
        let result = eval(
            r#"
            enum E { A, B }
            let e = E::A
            match e { E::A => 1, E::B => 2 }
            "#,
        );
        assert_eq!(result.as_i64(), Some(1));
    }

    #[test]
    fn ws4_4c_bare_match_scrutinee_still_works() {
        // The `match_scrutinee_ident` fast-path must still handle a
        // bare-variable scrutinee with literal arms.
        let result = eval(
            r#"
            let v = 2
            match v { 1 => 10, 2 => 20, _ => 0 }
            "#,
        );
        assert_eq!(result.as_i64(), Some(20));
    }
}