fabric-rs-codegen 0.3.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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
//! 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 NOP: u8 = 0x00;
    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 FCONST_1: u8 = 0x0C;
    pub const FCONST_2: u8 = 0x0D;
    pub const DCONST_0: u8 = 0x0E;
    pub const DCONST_1: u8 = 0x0F;
    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 IALOAD: u8 = 0x2E;
    pub const LALOAD: u8 = 0x2F;
    pub const FALOAD: u8 = 0x30;
    pub const DALOAD: u8 = 0x31;
    pub const AALOAD: u8 = 0x32;
    pub const BALOAD: u8 = 0x33;
    pub const CALOAD: u8 = 0x34;
    pub const SALOAD: u8 = 0x35;
    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 ISTORE_0: u8 = 0x3B;
    pub const ISTORE_1: u8 = 0x3C;
    pub const ISTORE_2: u8 = 0x3D;
    pub const ISTORE_3: u8 = 0x3E;
    pub const LSTORE_0: u8 = 0x3F;
    pub const LSTORE_1: u8 = 0x40;
    pub const LSTORE_2: u8 = 0x41;
    pub const LSTORE_3: u8 = 0x42;
    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 DUP_X1: u8 = 0x5A;
    pub const DUP_X2: u8 = 0x5B;
    pub const DUP2: u8 = 0x5C;
    pub const SWAP: u8 = 0x5F;
    pub const IADD: u8 = 0x60;
    pub const LADD: u8 = 0x61;
    pub const ISUB: u8 = 0x64;
    pub const IMUL: u8 = 0x68;
    pub const IDIV: u8 = 0x6C;
    pub const IINC: u8 = 0x84;
    pub const I2L: u8 = 0x85;
    pub const L2I: u8 = 0x88;
    pub const LCMP: u8 = 0x94;
    pub const IFEQ: u8 = 0x99;
    pub const IFNE: u8 = 0x9A;
    pub const IFLT: u8 = 0x9B;
    pub const IFGE: u8 = 0x9C;
    pub const IFGT: u8 = 0x9D;
    pub const IFLE: u8 = 0x9E;
    pub const IF_ICMPEQ: u8 = 0x9F;
    pub const IF_ICMPNE: u8 = 0xA0;
    pub const IF_ICMPLT: u8 = 0xA1;
    pub const IF_ICMPGE: u8 = 0xA2;
    pub const IF_ICMPGT: u8 = 0xA3;
    pub const IF_ICMPLE: u8 = 0xA4;
    pub const IF_ACMPEQ: u8 = 0xA5;
    pub const IF_ACMPNE: u8 = 0xA6;
    pub const GOTO: u8 = 0xA7;
    pub const TABLESWITCH: u8 = 0xAA;
    pub const LOOKUPSWITCH: u8 = 0xAB;
    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 INVOKEDYNAMIC: u8 = 0xBA;
    pub const NEW: u8 = 0xBB;
    pub const NEWARRAY: u8 = 0xBC;
    pub const ANEWARRAY: u8 = 0xBD;
    pub const ARRAYLENGTH: u8 = 0xBE;
    pub const ATHROW: u8 = 0xBF;
    pub const CHECKCAST: u8 = 0xC0;
    pub const INSTANCEOF: u8 = 0xC1;
    pub const MONITORENTER: u8 = 0xC2;
    pub const MONITOREXIT: u8 = 0xC3;
    pub const IFNULL: u8 = 0xC6;
    pub const IFNONNULL: u8 = 0xC7;
    pub const GOTO_W: u8 = 0xC8;
}

#[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());
            }
        }
    }
}

/// `MethodHandle` reference kind tag (JVMS §4.4.8).
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MethodHandleKind {
    GetField = 1,
    GetStatic = 2,
    PutField = 3,
    PutStatic = 4,
    InvokeVirtual = 5,
    InvokeStatic = 6,
    InvokeSpecial = 7,
    NewInvokeSpecial = 8,
    InvokeInterface = 9,
}

/// Entry in the `BootstrapMethods` class attribute used by `INVOKEDYNAMIC` and `CONSTANT_Dynamic`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BootstrapMethod {
    pub bootstrap_method_ref: u16,
    pub bootstrap_arguments: Vec<u16>,
}

/// Entry in the JVM `InnerClasses` attribute.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct InnerClassEntry {
    pub inner_class: String,
    pub outer_class: Option<String>,
    pub inner_name: Option<String>,
    pub access_flags: u16,
}

#[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,
    is_wide: bool,
}

#[derive(Debug, Clone)]
pub struct FrameEntry {
    pub pc: u16,
    pub locals: Vec<VerificationType>,
    pub 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>,
    pub auto_stack_map: bool,
    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(),
            auto_stack_map: false,
            labels: Vec::new(),
            jumps: Vec::new(),
            frames: Vec::new(),
        }
    }

    /// Creates a `CodeWriter` that automatically computes `max_stack`, `max_locals`,
    /// and `StackMapTable` frames via [`crate::stack_map::compute_stack_maps`].
    pub fn with_auto_frames() -> Self {
        Self {
            max_stack: 0,
            max_locals: 0,
            bytecode: Vec::new(),
            exception_table: Vec::new(),
            auto_stack_map: true,
            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,
            is_wide: false,
        });
    }

    pub fn emit_goto_w(&mut self, target: LabelId) {
        let opcode_pc = self.bytecode.len();
        self.emit_u8(opcodes::GOTO_W);
        let operand_pc = self.bytecode.len();
        self.bytecode.extend_from_slice(&0i32.to_be_bytes());
        self.jumps.push(JumpPatch {
            opcode_pc,
            operand_pc,
            target,
            is_wide: true,
        });
    }

    pub fn emit_tableswitch(
        &mut self,
        low: i32,
        high: i32,
        default: LabelId,
        targets: &[LabelId],
    ) {
        let opcode_pc = self.bytecode.len();
        self.emit_u8(opcodes::TABLESWITCH);
        while !self.bytecode.len().is_multiple_of(4) {
            self.emit_u8(0);
        }
        let def_pos = self.bytecode.len();
        self.bytecode.extend_from_slice(&0i32.to_be_bytes());
        self.jumps.push(JumpPatch {
            opcode_pc,
            operand_pc: def_pos,
            target: default,
            is_wide: true,
        });
        self.bytecode.extend_from_slice(&low.to_be_bytes());
        self.bytecode.extend_from_slice(&high.to_be_bytes());
        for tgt in targets {
            let pos = self.bytecode.len();
            self.bytecode.extend_from_slice(&0i32.to_be_bytes());
            self.jumps.push(JumpPatch {
                opcode_pc,
                operand_pc: pos,
                target: *tgt,
                is_wide: true,
            });
        }
    }

    pub fn emit_lookupswitch(&mut self, default: LabelId, pairs: &[(i32, LabelId)]) {
        let opcode_pc = self.bytecode.len();
        self.emit_u8(opcodes::LOOKUPSWITCH);
        while !self.bytecode.len().is_multiple_of(4) {
            self.emit_u8(0);
        }
        let def_pos = self.bytecode.len();
        self.bytecode.extend_from_slice(&0i32.to_be_bytes());
        self.jumps.push(JumpPatch {
            opcode_pc,
            operand_pc: def_pos,
            target: default,
            is_wide: true,
        });
        self.bytecode
            .extend_from_slice(&(pairs.len() as i32).to_be_bytes());
        for (key, tgt) in pairs {
            self.bytecode.extend_from_slice(&key.to_be_bytes());
            let pos = self.bytecode.len();
            self.bytecode.extend_from_slice(&0i32.to_be_bytes());
            self.jumps.push(JumpPatch {
                opcode_pc,
                operand_pc: pos,
                target: *tgt,
                is_wide: true,
            });
        }
    }

    /// Emits `INVOKEDYNAMIC` (`0xBA`, 2-byte constant pool index, `0x00`, `0x00`).
    pub fn emit_invokedynamic(&mut self, invoke_dynamic_cp_idx: u16) {
        self.emit_u8(opcodes::INVOKEDYNAMIC);
        self.emit_u16(invoke_dynamic_cp_idx);
        self.emit_u8(0);
        self.emit_u8(0);
    }

    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);
            if j.is_wide {
                let bytes = rel.to_be_bytes();
                self.bytecode[j.operand_pc..j.operand_pc + 4].copy_from_slice(&bytes);
            } else {
                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),
    Float(u32),
    Long(i64),
    Double(u64),
    Class(u16),
    String(u16),
    NameAndType(u16, u16),
    Fieldref(u16, u16),
    Methodref(u16, u16),
    InterfaceMethodref(u16, u16),
    MethodHandle(u8, u16),
    MethodType(u16),
    Dynamic(u16, u16),
    InvokeDynamic(u16, u16),
}

#[derive(Debug, Clone)]
enum CpMeta {
    Utf8,
    Integer,
    Float,
    Long,
    Double,
    Class(String),
    String,
    NameAndType,
    MemberRef(String, String, String),
    MethodHandle,
    MethodType,
    Dynamic(String),
    InvokeDynamic(String, String),
}

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

impl ConstantPool {
    pub fn new() -> Self {
        Self {
            entries: vec![Vec::new()], // index 0 unused in JVM
            metas: vec![None],
            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.metas.push(Some(CpMeta::Utf8));
        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.metas.push(Some(CpMeta::Integer));
        self.index.insert(key, idx);
        idx
    }

    pub fn add_float(&mut self, val: f32) -> u16 {
        let bits = val.to_bits();
        let key = CpKey::Float(bits);
        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(4);
        entry.extend_from_slice(&bits.to_be_bytes());
        self.entries.push(entry);
        self.metas.push(Some(CpMeta::Float));
        self.index.insert(key, idx);
        idx
    }

    pub fn add_long(&mut self, val: i64) -> u16 {
        let key = CpKey::Long(val);
        if let Some(&idx) = self.index.get(&key) {
            return idx;
        }
        let idx = self.entries.len() as u16;
        let mut entry = Vec::with_capacity(9);
        entry.push(5);
        entry.extend_from_slice(&val.to_be_bytes());
        self.entries.push(entry);
        self.metas.push(Some(CpMeta::Long));
        // Long occupies two constant pool entries per JVMS §4.4.5.
        self.entries.push(Vec::new());
        self.metas.push(None);
        self.index.insert(key, idx);
        idx
    }

    pub fn add_double(&mut self, val: f64) -> u16 {
        let bits = val.to_bits();
        let key = CpKey::Double(bits);
        if let Some(&idx) = self.index.get(&key) {
            return idx;
        }
        let idx = self.entries.len() as u16;
        let mut entry = Vec::with_capacity(9);
        entry.push(6);
        entry.extend_from_slice(&bits.to_be_bytes());
        self.entries.push(entry);
        self.metas.push(Some(CpMeta::Double));
        // Double occupies two constant pool entries per JVMS §4.4.5.
        self.entries.push(Vec::new());
        self.metas.push(None);
        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.metas.push(Some(CpMeta::Class(norm)));
        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.metas.push(Some(CpMeta::String));
        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.metas.push(Some(CpMeta::NameAndType));
        self.index.insert(key, idx);
        idx
    }

    fn add_member_ref_raw(&mut self, tag: u8, owner: &str, name: &str, desc: &str) -> u16 {
        let norm_owner = owner.replace('.', "/");
        let cls_idx = self.add_class(&norm_owner);
        let nat_idx = self.add_name_and_type(name, desc);
        let key = match tag {
            9 => CpKey::Fieldref(cls_idx, nat_idx),
            10 => CpKey::Methodref(cls_idx, nat_idx),
            _ => 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(tag);
        entry.extend_from_slice(&cls_idx.to_be_bytes());
        entry.extend_from_slice(&nat_idx.to_be_bytes());
        self.entries.push(entry);
        self.metas.push(Some(CpMeta::MemberRef(
            norm_owner,
            name.to_string(),
            desc.to_string(),
        )));
        self.index.insert(key, idx);
        idx
    }

    pub fn add_fieldref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
        self.add_member_ref_raw(9, owner, name, desc)
    }

    pub fn add_methodref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
        self.add_member_ref_raw(10, owner, name, desc)
    }

    pub fn add_interface_methodref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
        self.add_member_ref_raw(11, owner, name, desc)
    }

    /// Adds a `CONSTANT_MethodHandle_info` entry (tag 15).
    pub fn add_method_handle(&mut self, kind: MethodHandleKind, reference_index: u16) -> u16 {
        let kind_u8 = kind as u8;
        let key = CpKey::MethodHandle(kind_u8, reference_index);
        if let Some(&idx) = self.index.get(&key) {
            return idx;
        }
        let idx = self.entries.len() as u16;
        let mut entry = Vec::with_capacity(4);
        entry.push(15);
        entry.push(kind_u8);
        entry.extend_from_slice(&reference_index.to_be_bytes());
        self.entries.push(entry);
        self.metas.push(Some(CpMeta::MethodHandle));
        self.index.insert(key, idx);
        idx
    }

    /// Adds a `CONSTANT_MethodType_info` entry (tag 16).
    pub fn add_method_type(&mut self, descriptor: &str) -> u16 {
        let desc_idx = self.add_utf8(descriptor);
        let key = CpKey::MethodType(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(3);
        entry.push(16);
        entry.extend_from_slice(&desc_idx.to_be_bytes());
        self.entries.push(entry);
        self.metas.push(Some(CpMeta::MethodType));
        self.index.insert(key, idx);
        idx
    }

    /// Adds a `CONSTANT_Dynamic_info` entry (tag 17).
    pub fn add_dynamic(&mut self, bsm_attr_idx: u16, name: &str, descriptor: &str) -> u16 {
        let nat_idx = self.add_name_and_type(name, descriptor);
        let key = CpKey::Dynamic(bsm_attr_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(17);
        entry.extend_from_slice(&bsm_attr_idx.to_be_bytes());
        entry.extend_from_slice(&nat_idx.to_be_bytes());
        self.entries.push(entry);
        self.metas
            .push(Some(CpMeta::Dynamic(descriptor.to_string())));
        self.index.insert(key, idx);
        idx
    }

    /// Adds a `CONSTANT_InvokeDynamic_info` entry (tag 18).
    pub fn add_invoke_dynamic(&mut self, bsm_attr_idx: u16, name: &str, descriptor: &str) -> u16 {
        let nat_idx = self.add_name_and_type(name, descriptor);
        let key = CpKey::InvokeDynamic(bsm_attr_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(18);
        entry.extend_from_slice(&bsm_attr_idx.to_be_bytes());
        entry.extend_from_slice(&nat_idx.to_be_bytes());
        self.entries.push(entry);
        self.metas.push(Some(CpMeta::InvokeDynamic(
            name.to_string(),
            descriptor.to_string(),
        )));
        self.index.insert(key, idx);
        idx
    }

    pub(crate) fn get_class_name(&self, cp_idx: u16) -> Option<String> {
        match self.metas.get(cp_idx as usize).and_then(|o| o.as_ref()) {
            Some(CpMeta::Class(name)) => Some(name.clone()),
            _ => None,
        }
    }

    pub(crate) fn get_member_ref(&self, cp_idx: u16) -> Option<(String, String, String)> {
        match self.metas.get(cp_idx as usize).and_then(|o| o.as_ref()) {
            Some(CpMeta::MemberRef(o, n, d)) => Some((o.clone(), n.clone(), d.clone())),
            _ => None,
        }
    }

    pub(crate) fn get_invoke_dynamic(&self, cp_idx: u16) -> Option<(String, String)> {
        match self.metas.get(cp_idx as usize).and_then(|o| o.as_ref()) {
            Some(CpMeta::InvokeDynamic(n, d)) => Some((n.clone(), d.clone())),
            _ => None,
        }
    }

    pub(crate) fn ldc_verification_type(
        &mut self,
        cp_idx: u16,
        str_class_idx: u16,
        cls_class_idx: u16,
    ) -> Option<VerificationType> {
        let meta = self.metas.get(cp_idx as usize).and_then(|o| o.clone())?;
        match meta {
            CpMeta::Integer => Some(VerificationType::Integer),
            CpMeta::Float => Some(VerificationType::Float),
            CpMeta::Long => Some(VerificationType::Long),
            CpMeta::Double => Some(VerificationType::Double),
            CpMeta::String => Some(VerificationType::Object(str_class_idx)),
            CpMeta::Class(_) => Some(VerificationType::Object(cls_class_idx)),
            CpMeta::MethodHandle => Some(VerificationType::Object(
                self.add_class("java/lang/invoke/MethodHandle"),
            )),
            CpMeta::MethodType => Some(VerificationType::Object(
                self.add_class("java/lang/invoke/MethodType"),
            )),
            CpMeta::Dynamic(desc) => JvmType::parse(&desc)
                .ok()
                .map(|t| VerificationType::from_jvm_type(&t, self)),
            _ => None,
        }
    }

    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) {
            if !entry.is_empty() {
                out.extend_from_slice(entry);
            }
        }
    }
}

impl Default for ConstantPool {
    fn default() -> Self {
        Self::new()
    }
}

/// Pure-Rust JVM `.class` file builder supporting Java 8/17/21/25, annotations, `INVOKEDYNAMIC`,
/// generics `Signature`, `InnerClasses`/`NestHost`/`NestMembers`, and CFG `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>,
    field_signatures: HashMap<usize, String>,
    methods: Vec<MethodWriter>,
    method_signatures: HashMap<usize, String>,
    annotations: Vec<Annotation>,
    invisible_annotations: Vec<Annotation>,
    signature: Option<String>,
    bootstrap_methods: Vec<BootstrapMethod>,
    inner_classes: Vec<InnerClassEntry>,
    nest_host: Option<String>,
    nest_members: Vec<String>,
}

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(),
            field_signatures: HashMap::new(),
            methods: Vec::new(),
            method_signatures: HashMap::new(),
            annotations: Vec::new(),
            invisible_annotations: Vec::new(),
            signature: None,
            bootstrap_methods: Vec::new(),
            inner_classes: Vec::new(),
            nest_host: None,
            nest_members: 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 set_signature(&mut self, signature: impl Into<String>) {
        self.signature = Some(signature.into());
    }

    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_field_with_signature(&mut self, field: FieldWriter, signature: impl Into<String>) {
        let idx = self.fields.len();
        self.fields.push(field);
        self.field_signatures.insert(idx, signature.into());
    }

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

    pub fn add_method_with_signature(&mut self, method: MethodWriter, signature: impl Into<String>) {
        let idx = self.methods.len();
        self.methods.push(method);
        self.method_signatures.insert(idx, signature.into());
    }

    pub fn add_bootstrap_method(&mut self, bootstrap_method_ref: u16, bootstrap_arguments: Vec<u16>) -> u16 {
        let entry = BootstrapMethod {
            bootstrap_method_ref,
            bootstrap_arguments,
        };
        if let Some(pos) = self.bootstrap_methods.iter().position(|b| b == &entry) {
            return pos as u16;
        }
        let idx = self.bootstrap_methods.len() as u16;
        self.bootstrap_methods.push(entry);
        idx
    }

    /// Registers a `java.lang.invoke.LambdaMetafactory.metafactory` bootstrap method and returns
    /// its bootstrap method table index for `add_invoke_dynamic` + `emit_invokedynamic`.
    #[allow(clippy::too_many_arguments)]
    pub fn add_lambda_metafactory_bsm(
        &mut self,
        sam_desc: &str,
        impl_kind: MethodHandleKind,
        impl_owner: &str,
        impl_name: &str,
        impl_desc: &str,
        impl_is_iface: bool,
        instantiated_desc: &str,
    ) -> u16 {
        let bsm_mref = self.cp.add_methodref(
            "java/lang/invoke/LambdaMetafactory",
            "metafactory",
            "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;",
        );
        let bsm_handle = self
            .cp
            .add_method_handle(MethodHandleKind::InvokeStatic, bsm_mref);
        let sam_mt = self.cp.add_method_type(sam_desc);
        let impl_ref = if impl_is_iface {
            self.cp.add_interface_methodref(impl_owner, impl_name, impl_desc)
        } else {
            self.cp.add_methodref(impl_owner, impl_name, impl_desc)
        };
        let impl_handle = self.cp.add_method_handle(impl_kind, impl_ref);
        let inst_mt = self.cp.add_method_type(instantiated_desc);
        self.add_bootstrap_method(bsm_handle, vec![sam_mt, impl_handle, inst_mt])
    }

    pub fn add_inner_class(&mut self, entry: InnerClassEntry) {
        if !self.inner_classes.contains(&entry) {
            self.inner_classes.push(entry);
        }
    }

    pub fn set_nest_host(&mut self, host_internal: impl Into<String>) {
        self.nest_host = Some(host_internal.into().replace('.', "/"));
    }

    pub fn add_nest_member(&mut self, member_internal: impl Into<String>) {
        let norm = member_internal.into().replace('.', "/");
        if !self.nest_members.contains(&norm) {
            self.nest_members.push(norm);
        }
    }

    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 (idx, f) in self.fields.iter().enumerate() {
            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());
            if let Some(sig) = self.field_signatures.get(&idx) {
                let sig_attr = cp.add_utf8("Signature");
                let sig_idx = cp.add_utf8(sig);
                field_bytes.extend_from_slice(&1u16.to_be_bytes());
                field_bytes.extend_from_slice(&sig_attr.to_be_bytes());
                field_bytes.extend_from_slice(&2u32.to_be_bytes());
                field_bytes.extend_from_slice(&sig_idx.to_be_bytes());
            } else {
                field_bytes.extend_from_slice(&0u16.to_be_bytes());
            }
        }

        let mut method_bytes = Vec::new();
        method_bytes.extend_from_slice(&(self.methods.len() as u16).to_be_bytes());
        for (idx, m) in self.methods.iter_mut().enumerate() {
            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()?;
                if code.auto_stack_map {
                    let is_static = (m.access_flags & access_flags::ACC_STATIC) != 0;
                    let (max_stack, max_locals, frames) = crate::stack_map::compute_stack_maps(
                        &self.this_class_name,
                        &m.name,
                        &m.descriptor,
                        is_static,
                        &code.bytecode,
                        &code.exception_table,
                        &mut cp,
                    )?;
                    code.max_stack = code.max_stack.max(max_stack);
                    code.max_locals = code.max_locals.max(max_locals);
                    code.frames = frames;
                }
                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 let Some(sig) = self.method_signatures.get(&idx) {
                let sig_name = cp.add_utf8("Signature");
                let sig_idx = cp.add_utf8(sig);
                attrs.push((sig_name, sig_idx.to_be_bytes().to_vec()));
            }

            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 let Some(sig) = &self.signature {
            let sig_name = cp.add_utf8("Signature");
            let sig_idx = cp.add_utf8(sig);
            class_attrs.push((sig_name, sig_idx.to_be_bytes().to_vec()));
        }
        if !self.inner_classes.is_empty() {
            let ic_name = cp.add_utf8("InnerClasses");
            let mut ic_body = Vec::new();
            ic_body.extend_from_slice(&(self.inner_classes.len() as u16).to_be_bytes());
            for ic in &self.inner_classes {
                let inner_idx = cp.add_class(&ic.inner_class);
                let outer_idx = ic
                    .outer_class
                    .as_deref()
                    .map(|s| cp.add_class(s))
                    .unwrap_or(0);
                let name_idx = ic
                    .inner_name
                    .as_deref()
                    .map(|s| cp.add_utf8(s))
                    .unwrap_or(0);
                ic_body.extend_from_slice(&inner_idx.to_be_bytes());
                ic_body.extend_from_slice(&outer_idx.to_be_bytes());
                ic_body.extend_from_slice(&name_idx.to_be_bytes());
                ic_body.extend_from_slice(&ic.access_flags.to_be_bytes());
            }
            class_attrs.push((ic_name, ic_body));
        }
        if let Some(host) = &self.nest_host {
            let nh_name = cp.add_utf8("NestHost");
            let host_idx = cp.add_class(host);
            class_attrs.push((nh_name, host_idx.to_be_bytes().to_vec()));
        }
        if !self.nest_members.is_empty() {
            let nm_name = cp.add_utf8("NestMembers");
            let mut nm_body = Vec::new();
            nm_body.extend_from_slice(&(self.nest_members.len() as u16).to_be_bytes());
            for m in &self.nest_members {
                let m_idx = cp.add_class(m);
                nm_body.extend_from_slice(&m_idx.to_be_bytes());
            }
            class_attrs.push((nm_name, nm_body));
        }
        if !self.bootstrap_methods.is_empty() {
            let bsm_name = cp.add_utf8("BootstrapMethods");
            let mut bsm_body = Vec::new();
            bsm_body.extend_from_slice(&(self.bootstrap_methods.len() as u16).to_be_bytes());
            for bsm in &self.bootstrap_methods {
                bsm_body.extend_from_slice(&bsm.bootstrap_method_ref.to_be_bytes());
                bsm_body.extend_from_slice(&(bsm.bootstrap_arguments.len() as u16).to_be_bytes());
                for &arg in &bsm.bootstrap_arguments {
                    bsm_body.extend_from_slice(&arg.to_be_bytes());
                }
            }
            class_attrs.push((bsm_name, bsm_body));
        }
        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)
    }
}