fabric-rs-codegen 0.2.0

Pure-Rust JVM classfile writer, JAR SDK indexer, Rust binding emitter, and Mixin/Subclass bytecode generator for FLR v2
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
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
//! Pure-Rust JVM `.class` file builder supporting `StackMapTable`, annotations, and labels.

use std::collections::HashMap;

use fabric_rs_core::descriptor::JvmType;

#[allow(dead_code)]
pub mod opcodes {
    pub const ACONST_NULL: u8 = 0x01;
    pub const ICONST_M1: u8 = 0x02;
    pub const ICONST_0: u8 = 0x03;
    pub const ICONST_1: u8 = 0x04;
    pub const ICONST_2: u8 = 0x05;
    pub const ICONST_3: u8 = 0x06;
    pub const ICONST_4: u8 = 0x07;
    pub const ICONST_5: u8 = 0x08;
    pub const LCONST_0: u8 = 0x09;
    pub const LCONST_1: u8 = 0x0A;
    pub const FCONST_0: u8 = 0x0B;
    pub const DCONST_0: u8 = 0x0E;
    pub const BIPUSH: u8 = 0x10;
    pub const SIPUSH: u8 = 0x11;
    pub const LDC: u8 = 0x12;
    pub const LDC_W: u8 = 0x13;
    pub const LDC2_W: u8 = 0x14;
    pub const ILOAD: u8 = 0x15;
    pub const LLOAD: u8 = 0x16;
    pub const FLOAD: u8 = 0x17;
    pub const DLOAD: u8 = 0x18;
    pub const ALOAD: u8 = 0x19;
    pub const ILOAD_0: u8 = 0x1A;
    pub const ILOAD_1: u8 = 0x1B;
    pub const ILOAD_2: u8 = 0x1C;
    pub const ILOAD_3: u8 = 0x1D;
    pub const LLOAD_0: u8 = 0x1E;
    pub const LLOAD_1: u8 = 0x1F;
    pub const LLOAD_2: u8 = 0x20;
    pub const LLOAD_3: u8 = 0x21;
    pub const FLOAD_0: u8 = 0x22;
    pub const FLOAD_1: u8 = 0x23;
    pub const FLOAD_2: u8 = 0x24;
    pub const FLOAD_3: u8 = 0x25;
    pub const DLOAD_0: u8 = 0x26;
    pub const DLOAD_1: u8 = 0x27;
    pub const DLOAD_2: u8 = 0x28;
    pub const DLOAD_3: u8 = 0x29;
    pub const ALOAD_0: u8 = 0x2A;
    pub const ALOAD_1: u8 = 0x2B;
    pub const ALOAD_2: u8 = 0x2C;
    pub const ALOAD_3: u8 = 0x2D;
    pub const AALOAD: u8 = 0x32;
    pub const ISTORE: u8 = 0x36;
    pub const LSTORE: u8 = 0x37;
    pub const FSTORE: u8 = 0x38;
    pub const DSTORE: u8 = 0x39;
    pub const ASTORE: u8 = 0x3A;
    pub const ASTORE_0: u8 = 0x4B;
    pub const ASTORE_1: u8 = 0x4C;
    pub const ASTORE_2: u8 = 0x4D;
    pub const ASTORE_3: u8 = 0x4E;
    pub const AASTORE: u8 = 0x53;
    pub const POP: u8 = 0x57;
    pub const POP2: u8 = 0x58;
    pub const DUP: u8 = 0x59;
    pub const LCMP: u8 = 0x94;
    pub const IFEQ: u8 = 0x99;
    pub const IFNE: u8 = 0x9A;
    pub const GOTO: u8 = 0xA7;
    pub const IRETURN: u8 = 0xAC;
    pub const LRETURN: u8 = 0xAD;
    pub const FRETURN: u8 = 0xAE;
    pub const DRETURN: u8 = 0xAF;
    pub const ARETURN: u8 = 0xB0;
    pub const RETURN: u8 = 0xB1;
    pub const GETSTATIC: u8 = 0xB2;
    pub const PUTSTATIC: u8 = 0xB3;
    pub const GETFIELD: u8 = 0xB4;
    pub const PUTFIELD: u8 = 0xB5;
    pub const INVOKEVIRTUAL: u8 = 0xB6;
    pub const INVOKESPECIAL: u8 = 0xB7;
    pub const INVOKESTATIC: u8 = 0xB8;
    pub const INVOKEINTERFACE: u8 = 0xB9;
    pub const NEW: u8 = 0xBB;
    pub const ANEWARRAY: u8 = 0xBD;
    pub const ATHROW: u8 = 0xBF;
    pub const CHECKCAST: u8 = 0xC0;
    pub const IFNULL: u8 = 0xC6;
    pub const IFNONNULL: u8 = 0xC7;
}

#[allow(dead_code)]
pub mod access_flags {
    pub const ACC_PUBLIC: u16 = 0x0001;
    pub const ACC_PRIVATE: u16 = 0x0002;
    pub const ACC_PROTECTED: u16 = 0x0004;
    pub const ACC_STATIC: u16 = 0x0008;
    pub const ACC_FINAL: u16 = 0x0010;
    pub const ACC_SUPER: u16 = 0x0020;
    pub const ACC_SYNCHRONIZED: u16 = 0x0020;
    pub const ACC_VOLATILE: u16 = 0x0040;
    pub const ACC_BRIDGE: u16 = 0x0040;
    pub const ACC_VARARGS: u16 = 0x0080;
    pub const ACC_NATIVE: u16 = 0x0100;
    pub const ACC_INTERFACE: u16 = 0x0200;
    pub const ACC_ABSTRACT: u16 = 0x0400;
    pub const ACC_SYNTHETIC: u16 = 0x1000;
    pub const ACC_ANNOTATION: u16 = 0x2000;
    pub const ACC_ENUM: u16 = 0x4000;
}

#[allow(dead_code)]
#[derive(Debug, Clone)]
pub enum ElementValue {
    String(String),
    Class(String),
    Int(i32),
    Boolean(bool),
    Enum { type_descriptor: String, const_name: String },
    Array(Vec<ElementValue>),
    Annotation(Annotation),
}

#[derive(Debug, Clone)]
pub struct Annotation {
    pub type_descriptor: String,
    pub element_value_pairs: Vec<(String, ElementValue)>,
}

/// JVM StackMapTable verification type item.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerificationType {
    Top,
    Integer,
    Float,
    Double,
    Long,
    Null,
    UninitializedThis,
    Object(u16), // ConstantPool Class index
    Uninitialized(u16),
}

impl VerificationType {
    pub fn from_jvm_type(ty: &JvmType, cp: &mut ConstantPool) -> Self {
        match ty {
            JvmType::Boolean | JvmType::Byte | JvmType::Char | JvmType::Short | JvmType::Int => {
                VerificationType::Integer
            }
            JvmType::Float => VerificationType::Float,
            JvmType::Long => VerificationType::Long,
            JvmType::Double => VerificationType::Double,
            JvmType::Object(internal) => VerificationType::Object(cp.add_class(internal)),
            JvmType::Array(_) => VerificationType::Object(cp.add_class(&ty.to_descriptor())),
            JvmType::Void => VerificationType::Top,
        }
    }

    fn write(&self, buf: &mut Vec<u8>) {
        match self {
            VerificationType::Top => buf.push(0),
            VerificationType::Integer => buf.push(1),
            VerificationType::Float => buf.push(2),
            VerificationType::Double => buf.push(3),
            VerificationType::Long => buf.push(4),
            VerificationType::Null => buf.push(5),
            VerificationType::UninitializedThis => buf.push(6),
            VerificationType::Object(cp_idx) => {
                buf.push(7);
                buf.extend_from_slice(&cp_idx.to_be_bytes());
            }
            VerificationType::Uninitialized(offset) => {
                buf.push(8);
                buf.extend_from_slice(&offset.to_be_bytes());
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct LabelId(pub usize);

#[derive(Debug, Clone)]
struct JumpPatch {
    opcode_pc: usize,
    operand_pc: usize,
    target: LabelId,
}

#[derive(Debug, Clone)]
struct FrameEntry {
    pc: u16,
    locals: Vec<VerificationType>,
    stack: Vec<VerificationType>,
}

#[derive(Debug, Clone)]
pub struct ExceptionHandler {
    pub start_pc: u16,
    pub end_pc: u16,
    pub handler_pc: u16,
    pub catch_type: u16, // 0 for catch-all (`finally`)
}

#[derive(Debug, Clone)]
pub struct FieldWriter {
    pub access_flags: u16,
    pub name: String,
    pub descriptor: String,
}

#[derive(Debug, Clone)]
pub struct CodeWriter {
    pub max_stack: u16,
    pub max_locals: u16,
    pub bytecode: Vec<u8>,
    pub exception_table: Vec<ExceptionHandler>,
    labels: Vec<Option<u16>>,
    jumps: Vec<JumpPatch>,
    frames: Vec<FrameEntry>,
}

impl CodeWriter {
    pub fn new(max_stack: u16, max_locals: u16) -> Self {
        Self {
            max_stack,
            max_locals,
            bytecode: Vec::new(),
            exception_table: Vec::new(),
            labels: Vec::new(),
            jumps: Vec::new(),
            frames: Vec::new(),
        }
    }

    pub fn current_pc(&self) -> u16 {
        self.bytecode.len() as u16
    }

    pub fn new_label(&mut self) -> LabelId {
        let id = LabelId(self.labels.len());
        self.labels.push(None);
        id
    }

    pub fn bind_label(&mut self, label: LabelId) {
        self.labels[label.0] = Some(self.current_pc());
    }

    /// Binds a label and records an explicit `StackMapTable` FullFrame at this PC.
    pub fn bind_label_with_frame(
        &mut self,
        label: LabelId,
        locals: Vec<VerificationType>,
        stack: Vec<VerificationType>,
    ) {
        let pc = self.current_pc();
        self.labels[label.0] = Some(pc);
        self.frames.push(FrameEntry { pc, locals, stack });
    }

    pub fn emit_u8(&mut self, b: u8) {
        self.bytecode.push(b);
    }

    pub fn emit_u16(&mut self, val: u16) {
        self.bytecode.extend_from_slice(&val.to_be_bytes());
    }

    pub fn emit_i16(&mut self, val: i16) {
        self.bytecode.extend_from_slice(&val.to_be_bytes());
    }

    pub fn emit_jump(&mut self, opcode: u8, target: LabelId) {
        let opcode_pc = self.bytecode.len();
        self.emit_u8(opcode);
        let operand_pc = self.bytecode.len();
        self.emit_i16(0);
        self.jumps.push(JumpPatch {
            opcode_pc,
            operand_pc,
            target,
        });
    }

    pub fn emit_int_const(&mut self, value: i32) {
        match value {
            -1 => self.emit_u8(opcodes::ICONST_M1),
            0 => self.emit_u8(opcodes::ICONST_0),
            1 => self.emit_u8(opcodes::ICONST_1),
            2 => self.emit_u8(opcodes::ICONST_2),
            3 => self.emit_u8(opcodes::ICONST_3),
            4 => self.emit_u8(opcodes::ICONST_4),
            5 => self.emit_u8(opcodes::ICONST_5),
            -128..=127 => {
                self.emit_u8(opcodes::BIPUSH);
                self.emit_u8(value as i8 as u8);
            }
            -32768..=32767 => {
                self.emit_u8(opcodes::SIPUSH);
                self.emit_i16(value as i16);
            }
            _ => panic!("emit_int_const out of i16 range: use LDC with cp.add_integer"),
        }
    }

    pub fn emit_ldc(&mut self, cp_idx: u16) {
        if cp_idx <= 255 {
            self.emit_u8(opcodes::LDC);
            self.emit_u8(cp_idx as u8);
        } else {
            self.emit_u8(opcodes::LDC_W);
            self.emit_u16(cp_idx);
        }
    }

    pub fn emit_load(&mut self, ty: &JvmType, slot: u16) {
        match ty {
            JvmType::Boolean
            | JvmType::Byte
            | JvmType::Char
            | JvmType::Short
            | JvmType::Int => match slot {
                0 => self.emit_u8(opcodes::ILOAD_0),
                1 => self.emit_u8(opcodes::ILOAD_1),
                2 => self.emit_u8(opcodes::ILOAD_2),
                3 => self.emit_u8(opcodes::ILOAD_3),
                _ => {
                    self.emit_u8(opcodes::ILOAD);
                    self.emit_u8(slot as u8);
                }
            },
            JvmType::Long => match slot {
                0 => self.emit_u8(opcodes::LLOAD_0),
                1 => self.emit_u8(opcodes::LLOAD_1),
                2 => self.emit_u8(opcodes::LLOAD_2),
                3 => self.emit_u8(opcodes::LLOAD_3),
                _ => {
                    self.emit_u8(opcodes::LLOAD);
                    self.emit_u8(slot as u8);
                }
            },
            JvmType::Float => match slot {
                0 => self.emit_u8(opcodes::FLOAD_0),
                1 => self.emit_u8(opcodes::FLOAD_1),
                2 => self.emit_u8(opcodes::FLOAD_2),
                3 => self.emit_u8(opcodes::FLOAD_3),
                _ => {
                    self.emit_u8(opcodes::FLOAD);
                    self.emit_u8(slot as u8);
                }
            },
            JvmType::Double => match slot {
                0 => self.emit_u8(opcodes::DLOAD_0),
                1 => self.emit_u8(opcodes::DLOAD_1),
                2 => self.emit_u8(opcodes::DLOAD_2),
                3 => self.emit_u8(opcodes::DLOAD_3),
                _ => {
                    self.emit_u8(opcodes::DLOAD);
                    self.emit_u8(slot as u8);
                }
            },
            JvmType::Object(_) | JvmType::Array(_) => match slot {
                0 => self.emit_u8(opcodes::ALOAD_0),
                1 => self.emit_u8(opcodes::ALOAD_1),
                2 => self.emit_u8(opcodes::ALOAD_2),
                3 => self.emit_u8(opcodes::ALOAD_3),
                _ => {
                    self.emit_u8(opcodes::ALOAD);
                    self.emit_u8(slot as u8);
                }
            },
            JvmType::Void => {}
        }
    }

    pub fn emit_aload(&mut self, slot: u16) {
        self.emit_load(&JvmType::Object("java/lang/Object".to_string()), slot);
    }

    pub fn emit_astore(&mut self, slot: u16) {
        match slot {
            0 => self.emit_u8(opcodes::ASTORE_0),
            1 => self.emit_u8(opcodes::ASTORE_1),
            2 => self.emit_u8(opcodes::ASTORE_2),
            3 => self.emit_u8(opcodes::ASTORE_3),
            _ => {
                self.emit_u8(opcodes::ASTORE);
                self.emit_u8(slot as u8);
            }
        }
    }

    pub fn emit_return(&mut self, ty: &JvmType) {
        match ty {
            JvmType::Void => self.emit_u8(opcodes::RETURN),
            JvmType::Boolean
            | JvmType::Byte
            | JvmType::Char
            | JvmType::Short
            | JvmType::Int => self.emit_u8(opcodes::IRETURN),
            JvmType::Long => self.emit_u8(opcodes::LRETURN),
            JvmType::Float => self.emit_u8(opcodes::FRETURN),
            JvmType::Double => self.emit_u8(opcodes::DRETURN),
            JvmType::Object(_) | JvmType::Array(_) => self.emit_u8(opcodes::ARETURN),
        }
    }

    /// Boxes a primitive value on the top of the operand stack into its `java.lang.*` wrapper.
    pub fn emit_box_if_primitive(&mut self, cp: &mut ConstantPool, ty: &JvmType) {
        let (box_cls, desc) = match ty {
            JvmType::Boolean => ("java/lang/Boolean", "(Z)Ljava/lang/Boolean;"),
            JvmType::Byte => ("java/lang/Byte", "(B)Ljava/lang/Byte;"),
            JvmType::Char => ("java/lang/Character", "(C)Ljava/lang/Character;"),
            JvmType::Short => ("java/lang/Short", "(S)Ljava/lang/Short;"),
            JvmType::Int => ("java/lang/Integer", "(I)Ljava/lang/Integer;"),
            JvmType::Long => ("java/lang/Long", "(J)Ljava/lang/Long;"),
            JvmType::Float => ("java/lang/Float", "(F)Ljava/lang/Float;"),
            JvmType::Double => ("java/lang/Double", "(D)Ljava/lang/Double;"),
            JvmType::Void | JvmType::Object(_) | JvmType::Array(_) => return,
        };
        let mref = cp.add_methodref(box_cls, "valueOf", desc);
        self.emit_u8(opcodes::INVOKESTATIC);
        self.emit_u16(mref);
    }

    /// Casts or unboxes `java/lang/Object` on top of the stack to the expected `JvmType`.
    pub fn emit_unbox_or_cast(&mut self, cp: &mut ConstantPool, ty: &JvmType) {
        match ty {
            JvmType::Void => {
                self.emit_u8(opcodes::POP);
            }
            JvmType::Boolean => {
                let c = cp.add_class("java/lang/Boolean");
                let m = cp.add_methodref("java/lang/Boolean", "booleanValue", "()Z");
                self.emit_u8(opcodes::CHECKCAST);
                self.emit_u16(c);
                self.emit_u8(opcodes::INVOKEVIRTUAL);
                self.emit_u16(m);
            }
            JvmType::Byte => {
                let c = cp.add_class("java/lang/Number");
                let m = cp.add_methodref("java/lang/Number", "byteValue", "()B");
                self.emit_u8(opcodes::CHECKCAST);
                self.emit_u16(c);
                self.emit_u8(opcodes::INVOKEVIRTUAL);
                self.emit_u16(m);
            }
            JvmType::Short => {
                let c = cp.add_class("java/lang/Number");
                let m = cp.add_methodref("java/lang/Number", "shortValue", "()S");
                self.emit_u8(opcodes::CHECKCAST);
                self.emit_u16(c);
                self.emit_u8(opcodes::INVOKEVIRTUAL);
                self.emit_u16(m);
            }
            JvmType::Char => {
                let c = cp.add_class("java/lang/Character");
                let m = cp.add_methodref("java/lang/Character", "charValue", "()C");
                self.emit_u8(opcodes::CHECKCAST);
                self.emit_u16(c);
                self.emit_u8(opcodes::INVOKEVIRTUAL);
                self.emit_u16(m);
            }
            JvmType::Int => {
                let c = cp.add_class("java/lang/Number");
                let m = cp.add_methodref("java/lang/Number", "intValue", "()I");
                self.emit_u8(opcodes::CHECKCAST);
                self.emit_u16(c);
                self.emit_u8(opcodes::INVOKEVIRTUAL);
                self.emit_u16(m);
            }
            JvmType::Long => {
                let c = cp.add_class("java/lang/Number");
                let m = cp.add_methodref("java/lang/Number", "longValue", "()J");
                self.emit_u8(opcodes::CHECKCAST);
                self.emit_u16(c);
                self.emit_u8(opcodes::INVOKEVIRTUAL);
                self.emit_u16(m);
            }
            JvmType::Float => {
                let c = cp.add_class("java/lang/Number");
                let m = cp.add_methodref("java/lang/Number", "floatValue", "()F");
                self.emit_u8(opcodes::CHECKCAST);
                self.emit_u16(c);
                self.emit_u8(opcodes::INVOKEVIRTUAL);
                self.emit_u16(m);
            }
            JvmType::Double => {
                let c = cp.add_class("java/lang/Number");
                let m = cp.add_methodref("java/lang/Number", "doubleValue", "()D");
                self.emit_u8(opcodes::CHECKCAST);
                self.emit_u16(c);
                self.emit_u8(opcodes::INVOKEVIRTUAL);
                self.emit_u16(m);
            }
            JvmType::Object(internal) => {
                if internal != "java/lang/Object" {
                    let c = cp.add_class(internal);
                    self.emit_u8(opcodes::CHECKCAST);
                    self.emit_u16(c);
                }
            }
            JvmType::Array(_) => {
                let c = cp.add_class(&ty.to_descriptor());
                self.emit_u8(opcodes::CHECKCAST);
                self.emit_u16(c);
            }
        }
    }

    pub fn finalize_jumps(&mut self) -> Result<(), String> {
        for j in &self.jumps {
            let target_pc = self.labels[j.target.0]
                .ok_or_else(|| format!("Unbound jump label {:?}", j.target))?;
            let rel = (target_pc as i32) - (j.opcode_pc as i32);
            let rel16 = i16::try_from(rel).map_err(|_| "Jump offset overflow".to_string())?;
            let bytes = rel16.to_be_bytes();
            self.bytecode[j.operand_pc] = bytes[0];
            self.bytecode[j.operand_pc + 1] = bytes[1];
        }
        Ok(())
    }

    fn encode_stack_map_table(&self) -> Option<Vec<u8>> {
        if self.frames.is_empty() {
            return None;
        }
        let mut sorted = self.frames.clone();
        sorted.sort_by_key(|f| f.pc);
        sorted.dedup_by_key(|f| f.pc);

        let mut buf = Vec::new();
        buf.extend_from_slice(&(sorted.len() as u16).to_be_bytes());
        let mut prev_pc: Option<u16> = None;

        for frame in sorted {
            let offset_delta = match prev_pc {
                None => frame.pc,
                Some(p) => frame.pc - p - 1,
            };
            prev_pc = Some(frame.pc);

            // FullFrame (tag 255) is universally valid across all locals/stack transitions.
            buf.push(255);
            buf.extend_from_slice(&offset_delta.to_be_bytes());
            buf.extend_from_slice(&(frame.locals.len() as u16).to_be_bytes());
            for loc in &frame.locals {
                loc.write(&mut buf);
            }
            buf.extend_from_slice(&(frame.stack.len() as u16).to_be_bytes());
            for st in &frame.stack {
                st.write(&mut buf);
            }
        }
        Some(buf)
    }
}

#[derive(Debug, Clone)]
pub struct MethodWriter {
    pub access_flags: u16,
    pub name: String,
    pub descriptor: String,
    pub code: Option<CodeWriter>,
    pub annotations: Vec<Annotation>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum CpKey {
    Utf8(String),
    Integer(i32),
    Class(u16),
    String(u16),
    NameAndType(u16, u16),
    Fieldref(u16, u16),
    Methodref(u16, u16),
    InterfaceMethodref(u16, u16),
}

pub struct ConstantPool {
    entries: Vec<Vec<u8>>,
    index: HashMap<CpKey, u16>,
}

impl ConstantPool {
    pub fn new() -> Self {
        Self {
            entries: vec![Vec::new()], // index 0 unused in JVM
            index: HashMap::new(),
        }
    }

    pub fn add_utf8(&mut self, s: &str) -> u16 {
        let key = CpKey::Utf8(s.to_string());
        if let Some(&idx) = self.index.get(&key) {
            return idx;
        }
        let idx = self.entries.len() as u16;
        let bytes = s.as_bytes();
        let mut entry = Vec::with_capacity(3 + bytes.len());
        entry.push(1);
        entry.extend_from_slice(&(bytes.len() as u16).to_be_bytes());
        entry.extend_from_slice(bytes);
        self.entries.push(entry);
        self.index.insert(key, idx);
        idx
    }

    pub fn add_integer(&mut self, val: i32) -> u16 {
        let key = CpKey::Integer(val);
        if let Some(&idx) = self.index.get(&key) {
            return idx;
        }
        let idx = self.entries.len() as u16;
        let mut entry = Vec::with_capacity(5);
        entry.push(3);
        entry.extend_from_slice(&val.to_be_bytes());
        self.entries.push(entry);
        self.index.insert(key, idx);
        idx
    }

    pub fn add_class(&mut self, internal_name: &str) -> u16 {
        let norm = internal_name.replace('.', "/");
        let name_idx = self.add_utf8(&norm);
        let key = CpKey::Class(name_idx);
        if let Some(&idx) = self.index.get(&key) {
            return idx;
        }
        let idx = self.entries.len() as u16;
        let mut entry = Vec::with_capacity(3);
        entry.push(7);
        entry.extend_from_slice(&name_idx.to_be_bytes());
        self.entries.push(entry);
        self.index.insert(key, idx);
        idx
    }

    pub fn add_string(&mut self, s: &str) -> u16 {
        let utf8_idx = self.add_utf8(s);
        let key = CpKey::String(utf8_idx);
        if let Some(&idx) = self.index.get(&key) {
            return idx;
        }
        let idx = self.entries.len() as u16;
        let mut entry = Vec::with_capacity(3);
        entry.push(8);
        entry.extend_from_slice(&utf8_idx.to_be_bytes());
        self.entries.push(entry);
        self.index.insert(key, idx);
        idx
    }

    pub fn add_name_and_type(&mut self, name: &str, desc: &str) -> u16 {
        let name_idx = self.add_utf8(name);
        let desc_idx = self.add_utf8(desc);
        let key = CpKey::NameAndType(name_idx, desc_idx);
        if let Some(&idx) = self.index.get(&key) {
            return idx;
        }
        let idx = self.entries.len() as u16;
        let mut entry = Vec::with_capacity(5);
        entry.push(12);
        entry.extend_from_slice(&name_idx.to_be_bytes());
        entry.extend_from_slice(&desc_idx.to_be_bytes());
        self.entries.push(entry);
        self.index.insert(key, idx);
        idx
    }

    pub fn add_fieldref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
        let cls_idx = self.add_class(owner);
        let nat_idx = self.add_name_and_type(name, desc);
        let key = CpKey::Fieldref(cls_idx, nat_idx);
        if let Some(&idx) = self.index.get(&key) {
            return idx;
        }
        let idx = self.entries.len() as u16;
        let mut entry = Vec::with_capacity(5);
        entry.push(9);
        entry.extend_from_slice(&cls_idx.to_be_bytes());
        entry.extend_from_slice(&nat_idx.to_be_bytes());
        self.entries.push(entry);
        self.index.insert(key, idx);
        idx
    }

    pub fn add_methodref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
        let cls_idx = self.add_class(owner);
        let nat_idx = self.add_name_and_type(name, desc);
        let key = CpKey::Methodref(cls_idx, nat_idx);
        if let Some(&idx) = self.index.get(&key) {
            return idx;
        }
        let idx = self.entries.len() as u16;
        let mut entry = Vec::with_capacity(5);
        entry.push(10);
        entry.extend_from_slice(&cls_idx.to_be_bytes());
        entry.extend_from_slice(&nat_idx.to_be_bytes());
        self.entries.push(entry);
        self.index.insert(key, idx);
        idx
    }

    pub fn add_interface_methodref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
        let cls_idx = self.add_class(owner);
        let nat_idx = self.add_name_and_type(name, desc);
        let key = CpKey::InterfaceMethodref(cls_idx, nat_idx);
        if let Some(&idx) = self.index.get(&key) {
            return idx;
        }
        let idx = self.entries.len() as u16;
        let mut entry = Vec::with_capacity(5);
        entry.push(11);
        entry.extend_from_slice(&cls_idx.to_be_bytes());
        entry.extend_from_slice(&nat_idx.to_be_bytes());
        self.entries.push(entry);
        self.index.insert(key, idx);
        idx
    }

    fn write(&self, out: &mut Vec<u8>) {
        out.extend_from_slice(&(self.entries.len() as u16).to_be_bytes());
        for entry in self.entries.iter().skip(1) {
            out.extend_from_slice(entry);
        }
    }
}

/// Pure-Rust JVM `.class` file builder supporting Java 8/17/21/25, annotations, and `StackMapTable`.
pub struct ClassWriter {
    pub major_version: u16,
    pub access_flags: u16,
    pub this_class_name: String,
    pub cp: ConstantPool,
    this_class: u16,
    super_class: u16,
    interfaces: Vec<u16>,
    fields: Vec<FieldWriter>,
    methods: Vec<MethodWriter>,
    annotations: Vec<Annotation>,
    invisible_annotations: Vec<Annotation>,
}

impl ClassWriter {
    pub fn new(
        this_class: &str,
        super_class: &str,
        access_flags: u16,
        java_version: u16,
    ) -> Self {
        let mut cp = ConstantPool::new();
        let this_idx = cp.add_class(this_class);
        let super_idx = cp.add_class(super_class);
        let major_version = match java_version {
            8 => 52,
            16 => 60,
            17 => 61,
            21 => 65,
            25 => 69,
            v if v >= 45 => v,
            _ => 65,
        };
        Self {
            major_version,
            access_flags,
            this_class_name: this_class.replace('.', "/"),
            cp,
            this_class: this_idx,
            super_class: super_idx,
            interfaces: Vec::new(),
            fields: Vec::new(),
            methods: Vec::new(),
            annotations: Vec::new(),
            invisible_annotations: Vec::new(),
        }
    }

    pub fn add_interface(&mut self, iface: &str) {
        let idx = self.cp.add_class(iface);
        if !self.interfaces.contains(&idx) {
            self.interfaces.push(idx);
        }
    }

    pub fn add_annotation(&mut self, ann: Annotation) {
        self.annotations.push(ann);
    }

    pub fn add_invisible_annotation(&mut self, ann: Annotation) {
        self.invisible_annotations.push(ann);
    }

    pub fn add_field(&mut self, field: FieldWriter) {
        self.fields.push(field);
    }

    pub fn add_method(&mut self, method: MethodWriter) {
        self.methods.push(method);
    }

    fn write_element_value(cp: &mut ConstantPool, ev: &ElementValue, out: &mut Vec<u8>) {
        match ev {
            ElementValue::String(s) => {
                out.push(b's');
                out.extend_from_slice(&cp.add_utf8(s).to_be_bytes());
            }
            ElementValue::Class(desc) => {
                out.push(b'c');
                out.extend_from_slice(&cp.add_utf8(desc).to_be_bytes());
            }
            ElementValue::Int(v) => {
                out.push(b'I');
                out.extend_from_slice(&cp.add_integer(*v).to_be_bytes());
            }
            ElementValue::Boolean(b) => {
                out.push(b'Z');
                out.extend_from_slice(&cp.add_integer(if *b { 1 } else { 0 }).to_be_bytes());
            }
            ElementValue::Enum {
                type_descriptor,
                const_name,
            } => {
                out.push(b'e');
                out.extend_from_slice(&cp.add_utf8(type_descriptor).to_be_bytes());
                out.extend_from_slice(&cp.add_utf8(const_name).to_be_bytes());
            }
            ElementValue::Array(items) => {
                out.push(b'[');
                out.extend_from_slice(&(items.len() as u16).to_be_bytes());
                for item in items {
                    Self::write_element_value(cp, item, out);
                }
            }
            ElementValue::Annotation(ann) => {
                out.push(b'@');
                Self::write_annotation(cp, ann, out);
            }
        }
    }

    fn write_annotation(cp: &mut ConstantPool, ann: &Annotation, out: &mut Vec<u8>) {
        let type_idx = cp.add_utf8(&ann.type_descriptor);
        out.extend_from_slice(&type_idx.to_be_bytes());
        out.extend_from_slice(&(ann.element_value_pairs.len() as u16).to_be_bytes());
        for (name, val) in &ann.element_value_pairs {
            let name_idx = cp.add_utf8(name);
            out.extend_from_slice(&name_idx.to_be_bytes());
            Self::write_element_value(cp, val, out);
        }
    }

    fn encode_annotations_attr(cp: &mut ConstantPool, anns: &[Annotation]) -> Vec<u8> {
        let mut attr = Vec::new();
        attr.extend_from_slice(&(anns.len() as u16).to_be_bytes());
        for ann in anns {
            Self::write_annotation(cp, ann, &mut attr);
        }
        attr
    }

    pub fn finish(mut self) -> Result<Vec<u8>, String> {
        let mut cp = self.cp;

        let mut field_bytes = Vec::new();
        field_bytes.extend_from_slice(&(self.fields.len() as u16).to_be_bytes());
        for f in &self.fields {
            field_bytes.extend_from_slice(&f.access_flags.to_be_bytes());
            field_bytes.extend_from_slice(&cp.add_utf8(&f.name).to_be_bytes());
            field_bytes.extend_from_slice(&cp.add_utf8(&f.descriptor).to_be_bytes());
            field_bytes.extend_from_slice(&0u16.to_be_bytes()); // attributes_count
        }

        let mut method_bytes = Vec::new();
        method_bytes.extend_from_slice(&(self.methods.len() as u16).to_be_bytes());
        for m in &mut self.methods {
            method_bytes.extend_from_slice(&m.access_flags.to_be_bytes());
            method_bytes.extend_from_slice(&cp.add_utf8(&m.name).to_be_bytes());
            method_bytes.extend_from_slice(&cp.add_utf8(&m.descriptor).to_be_bytes());

            let mut attrs: Vec<(u16, Vec<u8>)> = Vec::new();
            if let Some(code) = m.code.as_mut() {
                code.finalize_jumps()?;
                let code_attr_name = cp.add_utf8("Code");
                let mut code_body = Vec::new();
                code_body.extend_from_slice(&code.max_stack.to_be_bytes());
                code_body.extend_from_slice(&code.max_locals.to_be_bytes());
                code_body.extend_from_slice(&(code.bytecode.len() as u32).to_be_bytes());
                code_body.extend_from_slice(&code.bytecode);

                code_body.extend_from_slice(&(code.exception_table.len() as u16).to_be_bytes());
                for ex in &code.exception_table {
                    code_body.extend_from_slice(&ex.start_pc.to_be_bytes());
                    code_body.extend_from_slice(&ex.end_pc.to_be_bytes());
                    code_body.extend_from_slice(&ex.handler_pc.to_be_bytes());
                    code_body.extend_from_slice(&ex.catch_type.to_be_bytes());
                }

                if let Some(smt) = code.encode_stack_map_table() {
                    let smt_name = cp.add_utf8("StackMapTable");
                    code_body.extend_from_slice(&1u16.to_be_bytes());
                    code_body.extend_from_slice(&smt_name.to_be_bytes());
                    code_body.extend_from_slice(&(smt.len() as u32).to_be_bytes());
                    code_body.extend_from_slice(&smt);
                } else {
                    code_body.extend_from_slice(&0u16.to_be_bytes());
                }
                attrs.push((code_attr_name, code_body));
            }

            if !m.annotations.is_empty() {
                let rva_name = cp.add_utf8("RuntimeVisibleAnnotations");
                let rva_body = Self::encode_annotations_attr(&mut cp, &m.annotations);
                attrs.push((rva_name, rva_body));
            }

            method_bytes.extend_from_slice(&(attrs.len() as u16).to_be_bytes());
            for (name_idx, body) in attrs {
                method_bytes.extend_from_slice(&name_idx.to_be_bytes());
                method_bytes.extend_from_slice(&(body.len() as u32).to_be_bytes());
                method_bytes.extend_from_slice(&body);
            }
        }

        let mut class_attrs: Vec<(u16, Vec<u8>)> = Vec::new();
        if !self.annotations.is_empty() {
            let rva_name = cp.add_utf8("RuntimeVisibleAnnotations");
            let rva_body = Self::encode_annotations_attr(&mut cp, &self.annotations);
            class_attrs.push((rva_name, rva_body));
        }
        if !self.invisible_annotations.is_empty() {
            let ria_name = cp.add_utf8("RuntimeInvisibleAnnotations");
            let ria_body = Self::encode_annotations_attr(&mut cp, &self.invisible_annotations);
            class_attrs.push((ria_name, ria_body));
        }

        let mut out = Vec::with_capacity(512);
        out.extend_from_slice(&0xCAFEBABEu32.to_be_bytes());
        out.extend_from_slice(&0u16.to_be_bytes());
        out.extend_from_slice(&self.major_version.to_be_bytes());
        cp.write(&mut out);
        out.extend_from_slice(&self.access_flags.to_be_bytes());
        out.extend_from_slice(&self.this_class.to_be_bytes());
        out.extend_from_slice(&self.super_class.to_be_bytes());
        out.extend_from_slice(&(self.interfaces.len() as u16).to_be_bytes());
        for iface in &self.interfaces {
            out.extend_from_slice(&iface.to_be_bytes());
        }
        out.extend_from_slice(&field_bytes);
        out.extend_from_slice(&method_bytes);
        out.extend_from_slice(&(class_attrs.len() as u16).to_be_bytes());
        for (name_idx, body) in class_attrs {
            out.extend_from_slice(&name_idx.to_be_bytes());
            out.extend_from_slice(&(body.len() as u32).to_be_bytes());
            out.extend_from_slice(&body);
        }

        Ok(out)
    }
}