Skip to main content

fabric_rs_codegen/
jvm_writer.rs

1//! Pure-Rust JVM `.class` file builder supporting `StackMapTable`, annotations, and labels.
2
3use std::collections::HashMap;
4
5use fabric_rs_core::descriptor::JvmType;
6
7#[allow(dead_code)]
8pub mod opcodes {
9    pub const NOP: u8 = 0x00;
10    pub const ACONST_NULL: u8 = 0x01;
11    pub const ICONST_M1: u8 = 0x02;
12    pub const ICONST_0: u8 = 0x03;
13    pub const ICONST_1: u8 = 0x04;
14    pub const ICONST_2: u8 = 0x05;
15    pub const ICONST_3: u8 = 0x06;
16    pub const ICONST_4: u8 = 0x07;
17    pub const ICONST_5: u8 = 0x08;
18    pub const LCONST_0: u8 = 0x09;
19    pub const LCONST_1: u8 = 0x0A;
20    pub const FCONST_0: u8 = 0x0B;
21    pub const FCONST_1: u8 = 0x0C;
22    pub const FCONST_2: u8 = 0x0D;
23    pub const DCONST_0: u8 = 0x0E;
24    pub const DCONST_1: u8 = 0x0F;
25    pub const BIPUSH: u8 = 0x10;
26    pub const SIPUSH: u8 = 0x11;
27    pub const LDC: u8 = 0x12;
28    pub const LDC_W: u8 = 0x13;
29    pub const LDC2_W: u8 = 0x14;
30    pub const ILOAD: u8 = 0x15;
31    pub const LLOAD: u8 = 0x16;
32    pub const FLOAD: u8 = 0x17;
33    pub const DLOAD: u8 = 0x18;
34    pub const ALOAD: u8 = 0x19;
35    pub const ILOAD_0: u8 = 0x1A;
36    pub const ILOAD_1: u8 = 0x1B;
37    pub const ILOAD_2: u8 = 0x1C;
38    pub const ILOAD_3: u8 = 0x1D;
39    pub const LLOAD_0: u8 = 0x1E;
40    pub const LLOAD_1: u8 = 0x1F;
41    pub const LLOAD_2: u8 = 0x20;
42    pub const LLOAD_3: u8 = 0x21;
43    pub const FLOAD_0: u8 = 0x22;
44    pub const FLOAD_1: u8 = 0x23;
45    pub const FLOAD_2: u8 = 0x24;
46    pub const FLOAD_3: u8 = 0x25;
47    pub const DLOAD_0: u8 = 0x26;
48    pub const DLOAD_1: u8 = 0x27;
49    pub const DLOAD_2: u8 = 0x28;
50    pub const DLOAD_3: u8 = 0x29;
51    pub const ALOAD_0: u8 = 0x2A;
52    pub const ALOAD_1: u8 = 0x2B;
53    pub const ALOAD_2: u8 = 0x2C;
54    pub const ALOAD_3: u8 = 0x2D;
55    pub const IALOAD: u8 = 0x2E;
56    pub const LALOAD: u8 = 0x2F;
57    pub const FALOAD: u8 = 0x30;
58    pub const DALOAD: u8 = 0x31;
59    pub const AALOAD: u8 = 0x32;
60    pub const BALOAD: u8 = 0x33;
61    pub const CALOAD: u8 = 0x34;
62    pub const SALOAD: u8 = 0x35;
63    pub const ISTORE: u8 = 0x36;
64    pub const LSTORE: u8 = 0x37;
65    pub const FSTORE: u8 = 0x38;
66    pub const DSTORE: u8 = 0x39;
67    pub const ASTORE: u8 = 0x3A;
68    pub const ISTORE_0: u8 = 0x3B;
69    pub const ISTORE_1: u8 = 0x3C;
70    pub const ISTORE_2: u8 = 0x3D;
71    pub const ISTORE_3: u8 = 0x3E;
72    pub const LSTORE_0: u8 = 0x3F;
73    pub const LSTORE_1: u8 = 0x40;
74    pub const LSTORE_2: u8 = 0x41;
75    pub const LSTORE_3: u8 = 0x42;
76    pub const ASTORE_0: u8 = 0x4B;
77    pub const ASTORE_1: u8 = 0x4C;
78    pub const ASTORE_2: u8 = 0x4D;
79    pub const ASTORE_3: u8 = 0x4E;
80    pub const AASTORE: u8 = 0x53;
81    pub const POP: u8 = 0x57;
82    pub const POP2: u8 = 0x58;
83    pub const DUP: u8 = 0x59;
84    pub const DUP_X1: u8 = 0x5A;
85    pub const DUP_X2: u8 = 0x5B;
86    pub const DUP2: u8 = 0x5C;
87    pub const SWAP: u8 = 0x5F;
88    pub const IADD: u8 = 0x60;
89    pub const LADD: u8 = 0x61;
90    pub const ISUB: u8 = 0x64;
91    pub const IMUL: u8 = 0x68;
92    pub const IDIV: u8 = 0x6C;
93    pub const IINC: u8 = 0x84;
94    pub const I2L: u8 = 0x85;
95    pub const L2I: u8 = 0x88;
96    pub const LCMP: u8 = 0x94;
97    pub const IFEQ: u8 = 0x99;
98    pub const IFNE: u8 = 0x9A;
99    pub const IFLT: u8 = 0x9B;
100    pub const IFGE: u8 = 0x9C;
101    pub const IFGT: u8 = 0x9D;
102    pub const IFLE: u8 = 0x9E;
103    pub const IF_ICMPEQ: u8 = 0x9F;
104    pub const IF_ICMPNE: u8 = 0xA0;
105    pub const IF_ICMPLT: u8 = 0xA1;
106    pub const IF_ICMPGE: u8 = 0xA2;
107    pub const IF_ICMPGT: u8 = 0xA3;
108    pub const IF_ICMPLE: u8 = 0xA4;
109    pub const IF_ACMPEQ: u8 = 0xA5;
110    pub const IF_ACMPNE: u8 = 0xA6;
111    pub const GOTO: u8 = 0xA7;
112    pub const TABLESWITCH: u8 = 0xAA;
113    pub const LOOKUPSWITCH: u8 = 0xAB;
114    pub const IRETURN: u8 = 0xAC;
115    pub const LRETURN: u8 = 0xAD;
116    pub const FRETURN: u8 = 0xAE;
117    pub const DRETURN: u8 = 0xAF;
118    pub const ARETURN: u8 = 0xB0;
119    pub const RETURN: u8 = 0xB1;
120    pub const GETSTATIC: u8 = 0xB2;
121    pub const PUTSTATIC: u8 = 0xB3;
122    pub const GETFIELD: u8 = 0xB4;
123    pub const PUTFIELD: u8 = 0xB5;
124    pub const INVOKEVIRTUAL: u8 = 0xB6;
125    pub const INVOKESPECIAL: u8 = 0xB7;
126    pub const INVOKESTATIC: u8 = 0xB8;
127    pub const INVOKEINTERFACE: u8 = 0xB9;
128    pub const INVOKEDYNAMIC: u8 = 0xBA;
129    pub const NEW: u8 = 0xBB;
130    pub const NEWARRAY: u8 = 0xBC;
131    pub const ANEWARRAY: u8 = 0xBD;
132    pub const ARRAYLENGTH: u8 = 0xBE;
133    pub const ATHROW: u8 = 0xBF;
134    pub const CHECKCAST: u8 = 0xC0;
135    pub const INSTANCEOF: u8 = 0xC1;
136    pub const MONITORENTER: u8 = 0xC2;
137    pub const MONITOREXIT: u8 = 0xC3;
138    pub const IFNULL: u8 = 0xC6;
139    pub const IFNONNULL: u8 = 0xC7;
140    pub const GOTO_W: u8 = 0xC8;
141}
142
143#[allow(dead_code)]
144pub mod access_flags {
145    pub const ACC_PUBLIC: u16 = 0x0001;
146    pub const ACC_PRIVATE: u16 = 0x0002;
147    pub const ACC_PROTECTED: u16 = 0x0004;
148    pub const ACC_STATIC: u16 = 0x0008;
149    pub const ACC_FINAL: u16 = 0x0010;
150    pub const ACC_SUPER: u16 = 0x0020;
151    pub const ACC_SYNCHRONIZED: u16 = 0x0020;
152    pub const ACC_VOLATILE: u16 = 0x0040;
153    pub const ACC_BRIDGE: u16 = 0x0040;
154    pub const ACC_VARARGS: u16 = 0x0080;
155    pub const ACC_NATIVE: u16 = 0x0100;
156    pub const ACC_INTERFACE: u16 = 0x0200;
157    pub const ACC_ABSTRACT: u16 = 0x0400;
158    pub const ACC_SYNTHETIC: u16 = 0x1000;
159    pub const ACC_ANNOTATION: u16 = 0x2000;
160    pub const ACC_ENUM: u16 = 0x4000;
161}
162
163#[allow(dead_code)]
164#[derive(Debug, Clone)]
165pub enum ElementValue {
166    String(String),
167    Class(String),
168    Int(i32),
169    Boolean(bool),
170    Enum { type_descriptor: String, const_name: String },
171    Array(Vec<ElementValue>),
172    Annotation(Annotation),
173}
174
175#[derive(Debug, Clone)]
176pub struct Annotation {
177    pub type_descriptor: String,
178    pub element_value_pairs: Vec<(String, ElementValue)>,
179}
180
181/// JVM StackMapTable verification type item.
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub enum VerificationType {
184    Top,
185    Integer,
186    Float,
187    Double,
188    Long,
189    Null,
190    UninitializedThis,
191    Object(u16), // ConstantPool Class index
192    Uninitialized(u16),
193}
194
195impl VerificationType {
196    pub fn from_jvm_type(ty: &JvmType, cp: &mut ConstantPool) -> Self {
197        match ty {
198            JvmType::Boolean | JvmType::Byte | JvmType::Char | JvmType::Short | JvmType::Int => {
199                VerificationType::Integer
200            }
201            JvmType::Float => VerificationType::Float,
202            JvmType::Long => VerificationType::Long,
203            JvmType::Double => VerificationType::Double,
204            JvmType::Object(internal) => VerificationType::Object(cp.add_class(internal)),
205            JvmType::Array(_) => VerificationType::Object(cp.add_class(&ty.to_descriptor())),
206            JvmType::Void => VerificationType::Top,
207        }
208    }
209
210    fn write(&self, buf: &mut Vec<u8>) {
211        match self {
212            VerificationType::Top => buf.push(0),
213            VerificationType::Integer => buf.push(1),
214            VerificationType::Float => buf.push(2),
215            VerificationType::Double => buf.push(3),
216            VerificationType::Long => buf.push(4),
217            VerificationType::Null => buf.push(5),
218            VerificationType::UninitializedThis => buf.push(6),
219            VerificationType::Object(cp_idx) => {
220                buf.push(7);
221                buf.extend_from_slice(&cp_idx.to_be_bytes());
222            }
223            VerificationType::Uninitialized(offset) => {
224                buf.push(8);
225                buf.extend_from_slice(&offset.to_be_bytes());
226            }
227        }
228    }
229}
230
231/// `MethodHandle` reference kind tag (JVMS ยง4.4.8).
232#[repr(u8)]
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
234pub enum MethodHandleKind {
235    GetField = 1,
236    GetStatic = 2,
237    PutField = 3,
238    PutStatic = 4,
239    InvokeVirtual = 5,
240    InvokeStatic = 6,
241    InvokeSpecial = 7,
242    NewInvokeSpecial = 8,
243    InvokeInterface = 9,
244}
245
246/// Entry in the `BootstrapMethods` class attribute used by `INVOKEDYNAMIC` and `CONSTANT_Dynamic`.
247#[derive(Debug, Clone, PartialEq, Eq, Hash)]
248pub struct BootstrapMethod {
249    pub bootstrap_method_ref: u16,
250    pub bootstrap_arguments: Vec<u16>,
251}
252
253/// Entry in the JVM `InnerClasses` attribute.
254#[derive(Debug, Clone, PartialEq, Eq, Hash)]
255pub struct InnerClassEntry {
256    pub inner_class: String,
257    pub outer_class: Option<String>,
258    pub inner_name: Option<String>,
259    pub access_flags: u16,
260}
261
262#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
263pub struct LabelId(pub usize);
264
265#[derive(Debug, Clone)]
266struct JumpPatch {
267    opcode_pc: usize,
268    operand_pc: usize,
269    target: LabelId,
270    is_wide: bool,
271}
272
273#[derive(Debug, Clone)]
274pub struct FrameEntry {
275    pub pc: u16,
276    pub locals: Vec<VerificationType>,
277    pub stack: Vec<VerificationType>,
278}
279
280#[derive(Debug, Clone)]
281pub struct ExceptionHandler {
282    pub start_pc: u16,
283    pub end_pc: u16,
284    pub handler_pc: u16,
285    pub catch_type: u16, // 0 for catch-all (`finally`)
286}
287
288#[derive(Debug, Clone)]
289pub struct FieldWriter {
290    pub access_flags: u16,
291    pub name: String,
292    pub descriptor: String,
293}
294
295#[derive(Debug, Clone)]
296pub struct CodeWriter {
297    pub max_stack: u16,
298    pub max_locals: u16,
299    pub bytecode: Vec<u8>,
300    pub exception_table: Vec<ExceptionHandler>,
301    pub auto_stack_map: bool,
302    labels: Vec<Option<u16>>,
303    jumps: Vec<JumpPatch>,
304    frames: Vec<FrameEntry>,
305}
306
307impl CodeWriter {
308    pub fn new(max_stack: u16, max_locals: u16) -> Self {
309        Self {
310            max_stack,
311            max_locals,
312            bytecode: Vec::new(),
313            exception_table: Vec::new(),
314            auto_stack_map: false,
315            labels: Vec::new(),
316            jumps: Vec::new(),
317            frames: Vec::new(),
318        }
319    }
320
321    /// Creates a `CodeWriter` that automatically computes `max_stack`, `max_locals`,
322    /// and `StackMapTable` frames via [`crate::stack_map::compute_stack_maps`].
323    pub fn with_auto_frames() -> Self {
324        Self {
325            max_stack: 0,
326            max_locals: 0,
327            bytecode: Vec::new(),
328            exception_table: Vec::new(),
329            auto_stack_map: true,
330            labels: Vec::new(),
331            jumps: Vec::new(),
332            frames: Vec::new(),
333        }
334    }
335
336    pub fn current_pc(&self) -> u16 {
337        self.bytecode.len() as u16
338    }
339
340    pub fn new_label(&mut self) -> LabelId {
341        let id = LabelId(self.labels.len());
342        self.labels.push(None);
343        id
344    }
345
346    pub fn bind_label(&mut self, label: LabelId) {
347        self.labels[label.0] = Some(self.current_pc());
348    }
349
350    /// Binds a label and records an explicit `StackMapTable` FullFrame at this PC.
351    pub fn bind_label_with_frame(
352        &mut self,
353        label: LabelId,
354        locals: Vec<VerificationType>,
355        stack: Vec<VerificationType>,
356    ) {
357        let pc = self.current_pc();
358        self.labels[label.0] = Some(pc);
359        self.frames.push(FrameEntry { pc, locals, stack });
360    }
361
362    pub fn emit_u8(&mut self, b: u8) {
363        self.bytecode.push(b);
364    }
365
366    pub fn emit_u16(&mut self, val: u16) {
367        self.bytecode.extend_from_slice(&val.to_be_bytes());
368    }
369
370    pub fn emit_i16(&mut self, val: i16) {
371        self.bytecode.extend_from_slice(&val.to_be_bytes());
372    }
373
374    pub fn emit_jump(&mut self, opcode: u8, target: LabelId) {
375        let opcode_pc = self.bytecode.len();
376        self.emit_u8(opcode);
377        let operand_pc = self.bytecode.len();
378        self.emit_i16(0);
379        self.jumps.push(JumpPatch {
380            opcode_pc,
381            operand_pc,
382            target,
383            is_wide: false,
384        });
385    }
386
387    pub fn emit_goto_w(&mut self, target: LabelId) {
388        let opcode_pc = self.bytecode.len();
389        self.emit_u8(opcodes::GOTO_W);
390        let operand_pc = self.bytecode.len();
391        self.bytecode.extend_from_slice(&0i32.to_be_bytes());
392        self.jumps.push(JumpPatch {
393            opcode_pc,
394            operand_pc,
395            target,
396            is_wide: true,
397        });
398    }
399
400    pub fn emit_tableswitch(
401        &mut self,
402        low: i32,
403        high: i32,
404        default: LabelId,
405        targets: &[LabelId],
406    ) {
407        let opcode_pc = self.bytecode.len();
408        self.emit_u8(opcodes::TABLESWITCH);
409        while !self.bytecode.len().is_multiple_of(4) {
410            self.emit_u8(0);
411        }
412        let def_pos = self.bytecode.len();
413        self.bytecode.extend_from_slice(&0i32.to_be_bytes());
414        self.jumps.push(JumpPatch {
415            opcode_pc,
416            operand_pc: def_pos,
417            target: default,
418            is_wide: true,
419        });
420        self.bytecode.extend_from_slice(&low.to_be_bytes());
421        self.bytecode.extend_from_slice(&high.to_be_bytes());
422        for tgt in targets {
423            let pos = self.bytecode.len();
424            self.bytecode.extend_from_slice(&0i32.to_be_bytes());
425            self.jumps.push(JumpPatch {
426                opcode_pc,
427                operand_pc: pos,
428                target: *tgt,
429                is_wide: true,
430            });
431        }
432    }
433
434    pub fn emit_lookupswitch(&mut self, default: LabelId, pairs: &[(i32, LabelId)]) {
435        let opcode_pc = self.bytecode.len();
436        self.emit_u8(opcodes::LOOKUPSWITCH);
437        while !self.bytecode.len().is_multiple_of(4) {
438            self.emit_u8(0);
439        }
440        let def_pos = self.bytecode.len();
441        self.bytecode.extend_from_slice(&0i32.to_be_bytes());
442        self.jumps.push(JumpPatch {
443            opcode_pc,
444            operand_pc: def_pos,
445            target: default,
446            is_wide: true,
447        });
448        self.bytecode
449            .extend_from_slice(&(pairs.len() as i32).to_be_bytes());
450        for (key, tgt) in pairs {
451            self.bytecode.extend_from_slice(&key.to_be_bytes());
452            let pos = self.bytecode.len();
453            self.bytecode.extend_from_slice(&0i32.to_be_bytes());
454            self.jumps.push(JumpPatch {
455                opcode_pc,
456                operand_pc: pos,
457                target: *tgt,
458                is_wide: true,
459            });
460        }
461    }
462
463    /// Emits `INVOKEDYNAMIC` (`0xBA`, 2-byte constant pool index, `0x00`, `0x00`).
464    pub fn emit_invokedynamic(&mut self, invoke_dynamic_cp_idx: u16) {
465        self.emit_u8(opcodes::INVOKEDYNAMIC);
466        self.emit_u16(invoke_dynamic_cp_idx);
467        self.emit_u8(0);
468        self.emit_u8(0);
469    }
470
471    pub fn emit_int_const(&mut self, value: i32) {
472        match value {
473            -1 => self.emit_u8(opcodes::ICONST_M1),
474            0 => self.emit_u8(opcodes::ICONST_0),
475            1 => self.emit_u8(opcodes::ICONST_1),
476            2 => self.emit_u8(opcodes::ICONST_2),
477            3 => self.emit_u8(opcodes::ICONST_3),
478            4 => self.emit_u8(opcodes::ICONST_4),
479            5 => self.emit_u8(opcodes::ICONST_5),
480            -128..=127 => {
481                self.emit_u8(opcodes::BIPUSH);
482                self.emit_u8(value as i8 as u8);
483            }
484            -32768..=32767 => {
485                self.emit_u8(opcodes::SIPUSH);
486                self.emit_i16(value as i16);
487            }
488            _ => panic!("emit_int_const out of i16 range: use LDC with cp.add_integer"),
489        }
490    }
491
492    pub fn emit_ldc(&mut self, cp_idx: u16) {
493        if cp_idx <= 255 {
494            self.emit_u8(opcodes::LDC);
495            self.emit_u8(cp_idx as u8);
496        } else {
497            self.emit_u8(opcodes::LDC_W);
498            self.emit_u16(cp_idx);
499        }
500    }
501
502    pub fn emit_load(&mut self, ty: &JvmType, slot: u16) {
503        match ty {
504            JvmType::Boolean
505            | JvmType::Byte
506            | JvmType::Char
507            | JvmType::Short
508            | JvmType::Int => match slot {
509                0 => self.emit_u8(opcodes::ILOAD_0),
510                1 => self.emit_u8(opcodes::ILOAD_1),
511                2 => self.emit_u8(opcodes::ILOAD_2),
512                3 => self.emit_u8(opcodes::ILOAD_3),
513                _ => {
514                    self.emit_u8(opcodes::ILOAD);
515                    self.emit_u8(slot as u8);
516                }
517            },
518            JvmType::Long => match slot {
519                0 => self.emit_u8(opcodes::LLOAD_0),
520                1 => self.emit_u8(opcodes::LLOAD_1),
521                2 => self.emit_u8(opcodes::LLOAD_2),
522                3 => self.emit_u8(opcodes::LLOAD_3),
523                _ => {
524                    self.emit_u8(opcodes::LLOAD);
525                    self.emit_u8(slot as u8);
526                }
527            },
528            JvmType::Float => match slot {
529                0 => self.emit_u8(opcodes::FLOAD_0),
530                1 => self.emit_u8(opcodes::FLOAD_1),
531                2 => self.emit_u8(opcodes::FLOAD_2),
532                3 => self.emit_u8(opcodes::FLOAD_3),
533                _ => {
534                    self.emit_u8(opcodes::FLOAD);
535                    self.emit_u8(slot as u8);
536                }
537            },
538            JvmType::Double => match slot {
539                0 => self.emit_u8(opcodes::DLOAD_0),
540                1 => self.emit_u8(opcodes::DLOAD_1),
541                2 => self.emit_u8(opcodes::DLOAD_2),
542                3 => self.emit_u8(opcodes::DLOAD_3),
543                _ => {
544                    self.emit_u8(opcodes::DLOAD);
545                    self.emit_u8(slot as u8);
546                }
547            },
548            JvmType::Object(_) | JvmType::Array(_) => match slot {
549                0 => self.emit_u8(opcodes::ALOAD_0),
550                1 => self.emit_u8(opcodes::ALOAD_1),
551                2 => self.emit_u8(opcodes::ALOAD_2),
552                3 => self.emit_u8(opcodes::ALOAD_3),
553                _ => {
554                    self.emit_u8(opcodes::ALOAD);
555                    self.emit_u8(slot as u8);
556                }
557            },
558            JvmType::Void => {}
559        }
560    }
561
562    pub fn emit_aload(&mut self, slot: u16) {
563        self.emit_load(&JvmType::Object("java/lang/Object".to_string()), slot);
564    }
565
566    pub fn emit_astore(&mut self, slot: u16) {
567        match slot {
568            0 => self.emit_u8(opcodes::ASTORE_0),
569            1 => self.emit_u8(opcodes::ASTORE_1),
570            2 => self.emit_u8(opcodes::ASTORE_2),
571            3 => self.emit_u8(opcodes::ASTORE_3),
572            _ => {
573                self.emit_u8(opcodes::ASTORE);
574                self.emit_u8(slot as u8);
575            }
576        }
577    }
578
579    pub fn emit_return(&mut self, ty: &JvmType) {
580        match ty {
581            JvmType::Void => self.emit_u8(opcodes::RETURN),
582            JvmType::Boolean
583            | JvmType::Byte
584            | JvmType::Char
585            | JvmType::Short
586            | JvmType::Int => self.emit_u8(opcodes::IRETURN),
587            JvmType::Long => self.emit_u8(opcodes::LRETURN),
588            JvmType::Float => self.emit_u8(opcodes::FRETURN),
589            JvmType::Double => self.emit_u8(opcodes::DRETURN),
590            JvmType::Object(_) | JvmType::Array(_) => self.emit_u8(opcodes::ARETURN),
591        }
592    }
593
594    /// Boxes a primitive value on the top of the operand stack into its `java.lang.*` wrapper.
595    pub fn emit_box_if_primitive(&mut self, cp: &mut ConstantPool, ty: &JvmType) {
596        let (box_cls, desc) = match ty {
597            JvmType::Boolean => ("java/lang/Boolean", "(Z)Ljava/lang/Boolean;"),
598            JvmType::Byte => ("java/lang/Byte", "(B)Ljava/lang/Byte;"),
599            JvmType::Char => ("java/lang/Character", "(C)Ljava/lang/Character;"),
600            JvmType::Short => ("java/lang/Short", "(S)Ljava/lang/Short;"),
601            JvmType::Int => ("java/lang/Integer", "(I)Ljava/lang/Integer;"),
602            JvmType::Long => ("java/lang/Long", "(J)Ljava/lang/Long;"),
603            JvmType::Float => ("java/lang/Float", "(F)Ljava/lang/Float;"),
604            JvmType::Double => ("java/lang/Double", "(D)Ljava/lang/Double;"),
605            JvmType::Void | JvmType::Object(_) | JvmType::Array(_) => return,
606        };
607        let mref = cp.add_methodref(box_cls, "valueOf", desc);
608        self.emit_u8(opcodes::INVOKESTATIC);
609        self.emit_u16(mref);
610    }
611
612    /// Casts or unboxes `java/lang/Object` on top of the stack to the expected `JvmType`.
613    pub fn emit_unbox_or_cast(&mut self, cp: &mut ConstantPool, ty: &JvmType) {
614        match ty {
615            JvmType::Void => {
616                self.emit_u8(opcodes::POP);
617            }
618            JvmType::Boolean => {
619                let c = cp.add_class("java/lang/Boolean");
620                let m = cp.add_methodref("java/lang/Boolean", "booleanValue", "()Z");
621                self.emit_u8(opcodes::CHECKCAST);
622                self.emit_u16(c);
623                self.emit_u8(opcodes::INVOKEVIRTUAL);
624                self.emit_u16(m);
625            }
626            JvmType::Byte => {
627                let c = cp.add_class("java/lang/Number");
628                let m = cp.add_methodref("java/lang/Number", "byteValue", "()B");
629                self.emit_u8(opcodes::CHECKCAST);
630                self.emit_u16(c);
631                self.emit_u8(opcodes::INVOKEVIRTUAL);
632                self.emit_u16(m);
633            }
634            JvmType::Short => {
635                let c = cp.add_class("java/lang/Number");
636                let m = cp.add_methodref("java/lang/Number", "shortValue", "()S");
637                self.emit_u8(opcodes::CHECKCAST);
638                self.emit_u16(c);
639                self.emit_u8(opcodes::INVOKEVIRTUAL);
640                self.emit_u16(m);
641            }
642            JvmType::Char => {
643                let c = cp.add_class("java/lang/Character");
644                let m = cp.add_methodref("java/lang/Character", "charValue", "()C");
645                self.emit_u8(opcodes::CHECKCAST);
646                self.emit_u16(c);
647                self.emit_u8(opcodes::INVOKEVIRTUAL);
648                self.emit_u16(m);
649            }
650            JvmType::Int => {
651                let c = cp.add_class("java/lang/Number");
652                let m = cp.add_methodref("java/lang/Number", "intValue", "()I");
653                self.emit_u8(opcodes::CHECKCAST);
654                self.emit_u16(c);
655                self.emit_u8(opcodes::INVOKEVIRTUAL);
656                self.emit_u16(m);
657            }
658            JvmType::Long => {
659                let c = cp.add_class("java/lang/Number");
660                let m = cp.add_methodref("java/lang/Number", "longValue", "()J");
661                self.emit_u8(opcodes::CHECKCAST);
662                self.emit_u16(c);
663                self.emit_u8(opcodes::INVOKEVIRTUAL);
664                self.emit_u16(m);
665            }
666            JvmType::Float => {
667                let c = cp.add_class("java/lang/Number");
668                let m = cp.add_methodref("java/lang/Number", "floatValue", "()F");
669                self.emit_u8(opcodes::CHECKCAST);
670                self.emit_u16(c);
671                self.emit_u8(opcodes::INVOKEVIRTUAL);
672                self.emit_u16(m);
673            }
674            JvmType::Double => {
675                let c = cp.add_class("java/lang/Number");
676                let m = cp.add_methodref("java/lang/Number", "doubleValue", "()D");
677                self.emit_u8(opcodes::CHECKCAST);
678                self.emit_u16(c);
679                self.emit_u8(opcodes::INVOKEVIRTUAL);
680                self.emit_u16(m);
681            }
682            JvmType::Object(internal) => {
683                if internal != "java/lang/Object" {
684                    let c = cp.add_class(internal);
685                    self.emit_u8(opcodes::CHECKCAST);
686                    self.emit_u16(c);
687                }
688            }
689            JvmType::Array(_) => {
690                let c = cp.add_class(&ty.to_descriptor());
691                self.emit_u8(opcodes::CHECKCAST);
692                self.emit_u16(c);
693            }
694        }
695    }
696
697    pub fn finalize_jumps(&mut self) -> Result<(), String> {
698        for j in &self.jumps {
699            let target_pc = self.labels[j.target.0]
700                .ok_or_else(|| format!("Unbound jump label {:?}", j.target))?;
701            let rel = (target_pc as i32) - (j.opcode_pc as i32);
702            if j.is_wide {
703                let bytes = rel.to_be_bytes();
704                self.bytecode[j.operand_pc..j.operand_pc + 4].copy_from_slice(&bytes);
705            } else {
706                let rel16 = i16::try_from(rel).map_err(|_| "Jump offset overflow".to_string())?;
707                let bytes = rel16.to_be_bytes();
708                self.bytecode[j.operand_pc] = bytes[0];
709                self.bytecode[j.operand_pc + 1] = bytes[1];
710            }
711        }
712        Ok(())
713    }
714
715    fn encode_stack_map_table(&self) -> Option<Vec<u8>> {
716        if self.frames.is_empty() {
717            return None;
718        }
719        let mut sorted = self.frames.clone();
720        sorted.sort_by_key(|f| f.pc);
721        sorted.dedup_by_key(|f| f.pc);
722
723        let mut buf = Vec::new();
724        buf.extend_from_slice(&(sorted.len() as u16).to_be_bytes());
725        let mut prev_pc: Option<u16> = None;
726
727        for frame in sorted {
728            let offset_delta = match prev_pc {
729                None => frame.pc,
730                Some(p) => frame.pc - p - 1,
731            };
732            prev_pc = Some(frame.pc);
733
734            // FullFrame (tag 255) is universally valid across all locals/stack transitions.
735            buf.push(255);
736            buf.extend_from_slice(&offset_delta.to_be_bytes());
737            buf.extend_from_slice(&(frame.locals.len() as u16).to_be_bytes());
738            for loc in &frame.locals {
739                loc.write(&mut buf);
740            }
741            buf.extend_from_slice(&(frame.stack.len() as u16).to_be_bytes());
742            for st in &frame.stack {
743                st.write(&mut buf);
744            }
745        }
746        Some(buf)
747    }
748}
749
750#[derive(Debug, Clone)]
751pub struct MethodWriter {
752    pub access_flags: u16,
753    pub name: String,
754    pub descriptor: String,
755    pub code: Option<CodeWriter>,
756    pub annotations: Vec<Annotation>,
757}
758
759#[derive(Debug, Clone, PartialEq, Eq, Hash)]
760enum CpKey {
761    Utf8(String),
762    Integer(i32),
763    Float(u32),
764    Long(i64),
765    Double(u64),
766    Class(u16),
767    String(u16),
768    NameAndType(u16, u16),
769    Fieldref(u16, u16),
770    Methodref(u16, u16),
771    InterfaceMethodref(u16, u16),
772    MethodHandle(u8, u16),
773    MethodType(u16),
774    Dynamic(u16, u16),
775    InvokeDynamic(u16, u16),
776}
777
778#[derive(Debug, Clone)]
779enum CpMeta {
780    Utf8,
781    Integer,
782    Float,
783    Long,
784    Double,
785    Class(String),
786    String,
787    NameAndType,
788    MemberRef(String, String, String),
789    MethodHandle,
790    MethodType,
791    Dynamic(String),
792    InvokeDynamic(String, String),
793}
794
795pub struct ConstantPool {
796    entries: Vec<Vec<u8>>,
797    metas: Vec<Option<CpMeta>>,
798    index: HashMap<CpKey, u16>,
799}
800
801impl ConstantPool {
802    pub fn new() -> Self {
803        Self {
804            entries: vec![Vec::new()], // index 0 unused in JVM
805            metas: vec![None],
806            index: HashMap::new(),
807        }
808    }
809
810    pub fn add_utf8(&mut self, s: &str) -> u16 {
811        let key = CpKey::Utf8(s.to_string());
812        if let Some(&idx) = self.index.get(&key) {
813            return idx;
814        }
815        let idx = self.entries.len() as u16;
816        let bytes = s.as_bytes();
817        let mut entry = Vec::with_capacity(3 + bytes.len());
818        entry.push(1);
819        entry.extend_from_slice(&(bytes.len() as u16).to_be_bytes());
820        entry.extend_from_slice(bytes);
821        self.entries.push(entry);
822        self.metas.push(Some(CpMeta::Utf8));
823        self.index.insert(key, idx);
824        idx
825    }
826
827    pub fn add_integer(&mut self, val: i32) -> u16 {
828        let key = CpKey::Integer(val);
829        if let Some(&idx) = self.index.get(&key) {
830            return idx;
831        }
832        let idx = self.entries.len() as u16;
833        let mut entry = Vec::with_capacity(5);
834        entry.push(3);
835        entry.extend_from_slice(&val.to_be_bytes());
836        self.entries.push(entry);
837        self.metas.push(Some(CpMeta::Integer));
838        self.index.insert(key, idx);
839        idx
840    }
841
842    pub fn add_float(&mut self, val: f32) -> u16 {
843        let bits = val.to_bits();
844        let key = CpKey::Float(bits);
845        if let Some(&idx) = self.index.get(&key) {
846            return idx;
847        }
848        let idx = self.entries.len() as u16;
849        let mut entry = Vec::with_capacity(5);
850        entry.push(4);
851        entry.extend_from_slice(&bits.to_be_bytes());
852        self.entries.push(entry);
853        self.metas.push(Some(CpMeta::Float));
854        self.index.insert(key, idx);
855        idx
856    }
857
858    pub fn add_long(&mut self, val: i64) -> u16 {
859        let key = CpKey::Long(val);
860        if let Some(&idx) = self.index.get(&key) {
861            return idx;
862        }
863        let idx = self.entries.len() as u16;
864        let mut entry = Vec::with_capacity(9);
865        entry.push(5);
866        entry.extend_from_slice(&val.to_be_bytes());
867        self.entries.push(entry);
868        self.metas.push(Some(CpMeta::Long));
869        // Long occupies two constant pool entries per JVMS ยง4.4.5.
870        self.entries.push(Vec::new());
871        self.metas.push(None);
872        self.index.insert(key, idx);
873        idx
874    }
875
876    pub fn add_double(&mut self, val: f64) -> u16 {
877        let bits = val.to_bits();
878        let key = CpKey::Double(bits);
879        if let Some(&idx) = self.index.get(&key) {
880            return idx;
881        }
882        let idx = self.entries.len() as u16;
883        let mut entry = Vec::with_capacity(9);
884        entry.push(6);
885        entry.extend_from_slice(&bits.to_be_bytes());
886        self.entries.push(entry);
887        self.metas.push(Some(CpMeta::Double));
888        // Double occupies two constant pool entries per JVMS ยง4.4.5.
889        self.entries.push(Vec::new());
890        self.metas.push(None);
891        self.index.insert(key, idx);
892        idx
893    }
894
895    pub fn add_class(&mut self, internal_name: &str) -> u16 {
896        let norm = internal_name.replace('.', "/");
897        let name_idx = self.add_utf8(&norm);
898        let key = CpKey::Class(name_idx);
899        if let Some(&idx) = self.index.get(&key) {
900            return idx;
901        }
902        let idx = self.entries.len() as u16;
903        let mut entry = Vec::with_capacity(3);
904        entry.push(7);
905        entry.extend_from_slice(&name_idx.to_be_bytes());
906        self.entries.push(entry);
907        self.metas.push(Some(CpMeta::Class(norm)));
908        self.index.insert(key, idx);
909        idx
910    }
911
912    pub fn add_string(&mut self, s: &str) -> u16 {
913        let utf8_idx = self.add_utf8(s);
914        let key = CpKey::String(utf8_idx);
915        if let Some(&idx) = self.index.get(&key) {
916            return idx;
917        }
918        let idx = self.entries.len() as u16;
919        let mut entry = Vec::with_capacity(3);
920        entry.push(8);
921        entry.extend_from_slice(&utf8_idx.to_be_bytes());
922        self.entries.push(entry);
923        self.metas.push(Some(CpMeta::String));
924        self.index.insert(key, idx);
925        idx
926    }
927
928    pub fn add_name_and_type(&mut self, name: &str, desc: &str) -> u16 {
929        let name_idx = self.add_utf8(name);
930        let desc_idx = self.add_utf8(desc);
931        let key = CpKey::NameAndType(name_idx, desc_idx);
932        if let Some(&idx) = self.index.get(&key) {
933            return idx;
934        }
935        let idx = self.entries.len() as u16;
936        let mut entry = Vec::with_capacity(5);
937        entry.push(12);
938        entry.extend_from_slice(&name_idx.to_be_bytes());
939        entry.extend_from_slice(&desc_idx.to_be_bytes());
940        self.entries.push(entry);
941        self.metas.push(Some(CpMeta::NameAndType));
942        self.index.insert(key, idx);
943        idx
944    }
945
946    fn add_member_ref_raw(&mut self, tag: u8, owner: &str, name: &str, desc: &str) -> u16 {
947        let norm_owner = owner.replace('.', "/");
948        let cls_idx = self.add_class(&norm_owner);
949        let nat_idx = self.add_name_and_type(name, desc);
950        let key = match tag {
951            9 => CpKey::Fieldref(cls_idx, nat_idx),
952            10 => CpKey::Methodref(cls_idx, nat_idx),
953            _ => CpKey::InterfaceMethodref(cls_idx, nat_idx),
954        };
955        if let Some(&idx) = self.index.get(&key) {
956            return idx;
957        }
958        let idx = self.entries.len() as u16;
959        let mut entry = Vec::with_capacity(5);
960        entry.push(tag);
961        entry.extend_from_slice(&cls_idx.to_be_bytes());
962        entry.extend_from_slice(&nat_idx.to_be_bytes());
963        self.entries.push(entry);
964        self.metas.push(Some(CpMeta::MemberRef(
965            norm_owner,
966            name.to_string(),
967            desc.to_string(),
968        )));
969        self.index.insert(key, idx);
970        idx
971    }
972
973    pub fn add_fieldref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
974        self.add_member_ref_raw(9, owner, name, desc)
975    }
976
977    pub fn add_methodref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
978        self.add_member_ref_raw(10, owner, name, desc)
979    }
980
981    pub fn add_interface_methodref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
982        self.add_member_ref_raw(11, owner, name, desc)
983    }
984
985    /// Adds a `CONSTANT_MethodHandle_info` entry (tag 15).
986    pub fn add_method_handle(&mut self, kind: MethodHandleKind, reference_index: u16) -> u16 {
987        let kind_u8 = kind as u8;
988        let key = CpKey::MethodHandle(kind_u8, reference_index);
989        if let Some(&idx) = self.index.get(&key) {
990            return idx;
991        }
992        let idx = self.entries.len() as u16;
993        let mut entry = Vec::with_capacity(4);
994        entry.push(15);
995        entry.push(kind_u8);
996        entry.extend_from_slice(&reference_index.to_be_bytes());
997        self.entries.push(entry);
998        self.metas.push(Some(CpMeta::MethodHandle));
999        self.index.insert(key, idx);
1000        idx
1001    }
1002
1003    /// Adds a `CONSTANT_MethodType_info` entry (tag 16).
1004    pub fn add_method_type(&mut self, descriptor: &str) -> u16 {
1005        let desc_idx = self.add_utf8(descriptor);
1006        let key = CpKey::MethodType(desc_idx);
1007        if let Some(&idx) = self.index.get(&key) {
1008            return idx;
1009        }
1010        let idx = self.entries.len() as u16;
1011        let mut entry = Vec::with_capacity(3);
1012        entry.push(16);
1013        entry.extend_from_slice(&desc_idx.to_be_bytes());
1014        self.entries.push(entry);
1015        self.metas.push(Some(CpMeta::MethodType));
1016        self.index.insert(key, idx);
1017        idx
1018    }
1019
1020    /// Adds a `CONSTANT_Dynamic_info` entry (tag 17).
1021    pub fn add_dynamic(&mut self, bsm_attr_idx: u16, name: &str, descriptor: &str) -> u16 {
1022        let nat_idx = self.add_name_and_type(name, descriptor);
1023        let key = CpKey::Dynamic(bsm_attr_idx, nat_idx);
1024        if let Some(&idx) = self.index.get(&key) {
1025            return idx;
1026        }
1027        let idx = self.entries.len() as u16;
1028        let mut entry = Vec::with_capacity(5);
1029        entry.push(17);
1030        entry.extend_from_slice(&bsm_attr_idx.to_be_bytes());
1031        entry.extend_from_slice(&nat_idx.to_be_bytes());
1032        self.entries.push(entry);
1033        self.metas
1034            .push(Some(CpMeta::Dynamic(descriptor.to_string())));
1035        self.index.insert(key, idx);
1036        idx
1037    }
1038
1039    /// Adds a `CONSTANT_InvokeDynamic_info` entry (tag 18).
1040    pub fn add_invoke_dynamic(&mut self, bsm_attr_idx: u16, name: &str, descriptor: &str) -> u16 {
1041        let nat_idx = self.add_name_and_type(name, descriptor);
1042        let key = CpKey::InvokeDynamic(bsm_attr_idx, nat_idx);
1043        if let Some(&idx) = self.index.get(&key) {
1044            return idx;
1045        }
1046        let idx = self.entries.len() as u16;
1047        let mut entry = Vec::with_capacity(5);
1048        entry.push(18);
1049        entry.extend_from_slice(&bsm_attr_idx.to_be_bytes());
1050        entry.extend_from_slice(&nat_idx.to_be_bytes());
1051        self.entries.push(entry);
1052        self.metas.push(Some(CpMeta::InvokeDynamic(
1053            name.to_string(),
1054            descriptor.to_string(),
1055        )));
1056        self.index.insert(key, idx);
1057        idx
1058    }
1059
1060    pub(crate) fn get_class_name(&self, cp_idx: u16) -> Option<String> {
1061        match self.metas.get(cp_idx as usize).and_then(|o| o.as_ref()) {
1062            Some(CpMeta::Class(name)) => Some(name.clone()),
1063            _ => None,
1064        }
1065    }
1066
1067    pub(crate) fn get_member_ref(&self, cp_idx: u16) -> Option<(String, String, String)> {
1068        match self.metas.get(cp_idx as usize).and_then(|o| o.as_ref()) {
1069            Some(CpMeta::MemberRef(o, n, d)) => Some((o.clone(), n.clone(), d.clone())),
1070            _ => None,
1071        }
1072    }
1073
1074    pub(crate) fn get_invoke_dynamic(&self, cp_idx: u16) -> Option<(String, String)> {
1075        match self.metas.get(cp_idx as usize).and_then(|o| o.as_ref()) {
1076            Some(CpMeta::InvokeDynamic(n, d)) => Some((n.clone(), d.clone())),
1077            _ => None,
1078        }
1079    }
1080
1081    pub(crate) fn ldc_verification_type(
1082        &mut self,
1083        cp_idx: u16,
1084        str_class_idx: u16,
1085        cls_class_idx: u16,
1086    ) -> Option<VerificationType> {
1087        let meta = self.metas.get(cp_idx as usize).and_then(|o| o.clone())?;
1088        match meta {
1089            CpMeta::Integer => Some(VerificationType::Integer),
1090            CpMeta::Float => Some(VerificationType::Float),
1091            CpMeta::Long => Some(VerificationType::Long),
1092            CpMeta::Double => Some(VerificationType::Double),
1093            CpMeta::String => Some(VerificationType::Object(str_class_idx)),
1094            CpMeta::Class(_) => Some(VerificationType::Object(cls_class_idx)),
1095            CpMeta::MethodHandle => Some(VerificationType::Object(
1096                self.add_class("java/lang/invoke/MethodHandle"),
1097            )),
1098            CpMeta::MethodType => Some(VerificationType::Object(
1099                self.add_class("java/lang/invoke/MethodType"),
1100            )),
1101            CpMeta::Dynamic(desc) => JvmType::parse(&desc)
1102                .ok()
1103                .map(|t| VerificationType::from_jvm_type(&t, self)),
1104            _ => None,
1105        }
1106    }
1107
1108    fn write(&self, out: &mut Vec<u8>) {
1109        out.extend_from_slice(&(self.entries.len() as u16).to_be_bytes());
1110        for entry in self.entries.iter().skip(1) {
1111            if !entry.is_empty() {
1112                out.extend_from_slice(entry);
1113            }
1114        }
1115    }
1116}
1117
1118impl Default for ConstantPool {
1119    fn default() -> Self {
1120        Self::new()
1121    }
1122}
1123
1124/// Pure-Rust JVM `.class` file builder supporting Java 8/17/21/25, annotations, `INVOKEDYNAMIC`,
1125/// generics `Signature`, `InnerClasses`/`NestHost`/`NestMembers`, and CFG `StackMapTable`.
1126pub struct ClassWriter {
1127    pub major_version: u16,
1128    pub access_flags: u16,
1129    pub this_class_name: String,
1130    pub cp: ConstantPool,
1131    this_class: u16,
1132    super_class: u16,
1133    interfaces: Vec<u16>,
1134    fields: Vec<FieldWriter>,
1135    field_signatures: HashMap<usize, String>,
1136    methods: Vec<MethodWriter>,
1137    method_signatures: HashMap<usize, String>,
1138    annotations: Vec<Annotation>,
1139    invisible_annotations: Vec<Annotation>,
1140    signature: Option<String>,
1141    bootstrap_methods: Vec<BootstrapMethod>,
1142    inner_classes: Vec<InnerClassEntry>,
1143    nest_host: Option<String>,
1144    nest_members: Vec<String>,
1145}
1146
1147impl ClassWriter {
1148    pub fn new(
1149        this_class: &str,
1150        super_class: &str,
1151        access_flags: u16,
1152        java_version: u16,
1153    ) -> Self {
1154        let mut cp = ConstantPool::new();
1155        let this_idx = cp.add_class(this_class);
1156        let super_idx = cp.add_class(super_class);
1157        let major_version = match java_version {
1158            8 => 52,
1159            16 => 60,
1160            17 => 61,
1161            21 => 65,
1162            25 => 69,
1163            v if v >= 45 => v,
1164            _ => 65,
1165        };
1166        Self {
1167            major_version,
1168            access_flags,
1169            this_class_name: this_class.replace('.', "/"),
1170            cp,
1171            this_class: this_idx,
1172            super_class: super_idx,
1173            interfaces: Vec::new(),
1174            fields: Vec::new(),
1175            field_signatures: HashMap::new(),
1176            methods: Vec::new(),
1177            method_signatures: HashMap::new(),
1178            annotations: Vec::new(),
1179            invisible_annotations: Vec::new(),
1180            signature: None,
1181            bootstrap_methods: Vec::new(),
1182            inner_classes: Vec::new(),
1183            nest_host: None,
1184            nest_members: Vec::new(),
1185        }
1186    }
1187
1188    pub fn add_interface(&mut self, iface: &str) {
1189        let idx = self.cp.add_class(iface);
1190        if !self.interfaces.contains(&idx) {
1191            self.interfaces.push(idx);
1192        }
1193    }
1194
1195    pub fn set_signature(&mut self, signature: impl Into<String>) {
1196        self.signature = Some(signature.into());
1197    }
1198
1199    pub fn add_annotation(&mut self, ann: Annotation) {
1200        self.annotations.push(ann);
1201    }
1202
1203    pub fn add_invisible_annotation(&mut self, ann: Annotation) {
1204        self.invisible_annotations.push(ann);
1205    }
1206
1207    pub fn add_field(&mut self, field: FieldWriter) {
1208        self.fields.push(field);
1209    }
1210
1211    pub fn add_field_with_signature(&mut self, field: FieldWriter, signature: impl Into<String>) {
1212        let idx = self.fields.len();
1213        self.fields.push(field);
1214        self.field_signatures.insert(idx, signature.into());
1215    }
1216
1217    pub fn add_method(&mut self, method: MethodWriter) {
1218        self.methods.push(method);
1219    }
1220
1221    pub fn add_method_with_signature(&mut self, method: MethodWriter, signature: impl Into<String>) {
1222        let idx = self.methods.len();
1223        self.methods.push(method);
1224        self.method_signatures.insert(idx, signature.into());
1225    }
1226
1227    pub fn add_bootstrap_method(&mut self, bootstrap_method_ref: u16, bootstrap_arguments: Vec<u16>) -> u16 {
1228        let entry = BootstrapMethod {
1229            bootstrap_method_ref,
1230            bootstrap_arguments,
1231        };
1232        if let Some(pos) = self.bootstrap_methods.iter().position(|b| b == &entry) {
1233            return pos as u16;
1234        }
1235        let idx = self.bootstrap_methods.len() as u16;
1236        self.bootstrap_methods.push(entry);
1237        idx
1238    }
1239
1240    /// Registers a `java.lang.invoke.LambdaMetafactory.metafactory` bootstrap method and returns
1241    /// its bootstrap method table index for `add_invoke_dynamic` + `emit_invokedynamic`.
1242    #[allow(clippy::too_many_arguments)]
1243    pub fn add_lambda_metafactory_bsm(
1244        &mut self,
1245        sam_desc: &str,
1246        impl_kind: MethodHandleKind,
1247        impl_owner: &str,
1248        impl_name: &str,
1249        impl_desc: &str,
1250        impl_is_iface: bool,
1251        instantiated_desc: &str,
1252    ) -> u16 {
1253        let bsm_mref = self.cp.add_methodref(
1254            "java/lang/invoke/LambdaMetafactory",
1255            "metafactory",
1256            "(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;",
1257        );
1258        let bsm_handle = self
1259            .cp
1260            .add_method_handle(MethodHandleKind::InvokeStatic, bsm_mref);
1261        let sam_mt = self.cp.add_method_type(sam_desc);
1262        let impl_ref = if impl_is_iface {
1263            self.cp.add_interface_methodref(impl_owner, impl_name, impl_desc)
1264        } else {
1265            self.cp.add_methodref(impl_owner, impl_name, impl_desc)
1266        };
1267        let impl_handle = self.cp.add_method_handle(impl_kind, impl_ref);
1268        let inst_mt = self.cp.add_method_type(instantiated_desc);
1269        self.add_bootstrap_method(bsm_handle, vec![sam_mt, impl_handle, inst_mt])
1270    }
1271
1272    pub fn add_inner_class(&mut self, entry: InnerClassEntry) {
1273        if !self.inner_classes.contains(&entry) {
1274            self.inner_classes.push(entry);
1275        }
1276    }
1277
1278    pub fn set_nest_host(&mut self, host_internal: impl Into<String>) {
1279        self.nest_host = Some(host_internal.into().replace('.', "/"));
1280    }
1281
1282    pub fn add_nest_member(&mut self, member_internal: impl Into<String>) {
1283        let norm = member_internal.into().replace('.', "/");
1284        if !self.nest_members.contains(&norm) {
1285            self.nest_members.push(norm);
1286        }
1287    }
1288
1289    fn write_element_value(cp: &mut ConstantPool, ev: &ElementValue, out: &mut Vec<u8>) {
1290        match ev {
1291            ElementValue::String(s) => {
1292                out.push(b's');
1293                out.extend_from_slice(&cp.add_utf8(s).to_be_bytes());
1294            }
1295            ElementValue::Class(desc) => {
1296                out.push(b'c');
1297                out.extend_from_slice(&cp.add_utf8(desc).to_be_bytes());
1298            }
1299            ElementValue::Int(v) => {
1300                out.push(b'I');
1301                out.extend_from_slice(&cp.add_integer(*v).to_be_bytes());
1302            }
1303            ElementValue::Boolean(b) => {
1304                out.push(b'Z');
1305                out.extend_from_slice(&cp.add_integer(if *b { 1 } else { 0 }).to_be_bytes());
1306            }
1307            ElementValue::Enum {
1308                type_descriptor,
1309                const_name,
1310            } => {
1311                out.push(b'e');
1312                out.extend_from_slice(&cp.add_utf8(type_descriptor).to_be_bytes());
1313                out.extend_from_slice(&cp.add_utf8(const_name).to_be_bytes());
1314            }
1315            ElementValue::Array(items) => {
1316                out.push(b'[');
1317                out.extend_from_slice(&(items.len() as u16).to_be_bytes());
1318                for item in items {
1319                    Self::write_element_value(cp, item, out);
1320                }
1321            }
1322            ElementValue::Annotation(ann) => {
1323                out.push(b'@');
1324                Self::write_annotation(cp, ann, out);
1325            }
1326        }
1327    }
1328
1329    fn write_annotation(cp: &mut ConstantPool, ann: &Annotation, out: &mut Vec<u8>) {
1330        let type_idx = cp.add_utf8(&ann.type_descriptor);
1331        out.extend_from_slice(&type_idx.to_be_bytes());
1332        out.extend_from_slice(&(ann.element_value_pairs.len() as u16).to_be_bytes());
1333        for (name, val) in &ann.element_value_pairs {
1334            let name_idx = cp.add_utf8(name);
1335            out.extend_from_slice(&name_idx.to_be_bytes());
1336            Self::write_element_value(cp, val, out);
1337        }
1338    }
1339
1340    fn encode_annotations_attr(cp: &mut ConstantPool, anns: &[Annotation]) -> Vec<u8> {
1341        let mut attr = Vec::new();
1342        attr.extend_from_slice(&(anns.len() as u16).to_be_bytes());
1343        for ann in anns {
1344            Self::write_annotation(cp, ann, &mut attr);
1345        }
1346        attr
1347    }
1348
1349    pub fn finish(mut self) -> Result<Vec<u8>, String> {
1350        let mut cp = self.cp;
1351
1352        let mut field_bytes = Vec::new();
1353        field_bytes.extend_from_slice(&(self.fields.len() as u16).to_be_bytes());
1354        for (idx, f) in self.fields.iter().enumerate() {
1355            field_bytes.extend_from_slice(&f.access_flags.to_be_bytes());
1356            field_bytes.extend_from_slice(&cp.add_utf8(&f.name).to_be_bytes());
1357            field_bytes.extend_from_slice(&cp.add_utf8(&f.descriptor).to_be_bytes());
1358            if let Some(sig) = self.field_signatures.get(&idx) {
1359                let sig_attr = cp.add_utf8("Signature");
1360                let sig_idx = cp.add_utf8(sig);
1361                field_bytes.extend_from_slice(&1u16.to_be_bytes());
1362                field_bytes.extend_from_slice(&sig_attr.to_be_bytes());
1363                field_bytes.extend_from_slice(&2u32.to_be_bytes());
1364                field_bytes.extend_from_slice(&sig_idx.to_be_bytes());
1365            } else {
1366                field_bytes.extend_from_slice(&0u16.to_be_bytes());
1367            }
1368        }
1369
1370        let mut method_bytes = Vec::new();
1371        method_bytes.extend_from_slice(&(self.methods.len() as u16).to_be_bytes());
1372        for (idx, m) in self.methods.iter_mut().enumerate() {
1373            method_bytes.extend_from_slice(&m.access_flags.to_be_bytes());
1374            method_bytes.extend_from_slice(&cp.add_utf8(&m.name).to_be_bytes());
1375            method_bytes.extend_from_slice(&cp.add_utf8(&m.descriptor).to_be_bytes());
1376
1377            let mut attrs: Vec<(u16, Vec<u8>)> = Vec::new();
1378            if let Some(code) = m.code.as_mut() {
1379                code.finalize_jumps()?;
1380                if code.auto_stack_map {
1381                    let is_static = (m.access_flags & access_flags::ACC_STATIC) != 0;
1382                    let (max_stack, max_locals, frames) = crate::stack_map::compute_stack_maps(
1383                        &self.this_class_name,
1384                        &m.name,
1385                        &m.descriptor,
1386                        is_static,
1387                        &code.bytecode,
1388                        &code.exception_table,
1389                        &mut cp,
1390                    )?;
1391                    code.max_stack = code.max_stack.max(max_stack);
1392                    code.max_locals = code.max_locals.max(max_locals);
1393                    code.frames = frames;
1394                }
1395                let code_attr_name = cp.add_utf8("Code");
1396                let mut code_body = Vec::new();
1397                code_body.extend_from_slice(&code.max_stack.to_be_bytes());
1398                code_body.extend_from_slice(&code.max_locals.to_be_bytes());
1399                code_body.extend_from_slice(&(code.bytecode.len() as u32).to_be_bytes());
1400                code_body.extend_from_slice(&code.bytecode);
1401
1402                code_body.extend_from_slice(&(code.exception_table.len() as u16).to_be_bytes());
1403                for ex in &code.exception_table {
1404                    code_body.extend_from_slice(&ex.start_pc.to_be_bytes());
1405                    code_body.extend_from_slice(&ex.end_pc.to_be_bytes());
1406                    code_body.extend_from_slice(&ex.handler_pc.to_be_bytes());
1407                    code_body.extend_from_slice(&ex.catch_type.to_be_bytes());
1408                }
1409
1410                if let Some(smt) = code.encode_stack_map_table() {
1411                    let smt_name = cp.add_utf8("StackMapTable");
1412                    code_body.extend_from_slice(&1u16.to_be_bytes());
1413                    code_body.extend_from_slice(&smt_name.to_be_bytes());
1414                    code_body.extend_from_slice(&(smt.len() as u32).to_be_bytes());
1415                    code_body.extend_from_slice(&smt);
1416                } else {
1417                    code_body.extend_from_slice(&0u16.to_be_bytes());
1418                }
1419                attrs.push((code_attr_name, code_body));
1420            }
1421
1422            if let Some(sig) = self.method_signatures.get(&idx) {
1423                let sig_name = cp.add_utf8("Signature");
1424                let sig_idx = cp.add_utf8(sig);
1425                attrs.push((sig_name, sig_idx.to_be_bytes().to_vec()));
1426            }
1427
1428            if !m.annotations.is_empty() {
1429                let rva_name = cp.add_utf8("RuntimeVisibleAnnotations");
1430                let rva_body = Self::encode_annotations_attr(&mut cp, &m.annotations);
1431                attrs.push((rva_name, rva_body));
1432            }
1433
1434            method_bytes.extend_from_slice(&(attrs.len() as u16).to_be_bytes());
1435            for (name_idx, body) in attrs {
1436                method_bytes.extend_from_slice(&name_idx.to_be_bytes());
1437                method_bytes.extend_from_slice(&(body.len() as u32).to_be_bytes());
1438                method_bytes.extend_from_slice(&body);
1439            }
1440        }
1441
1442        let mut class_attrs: Vec<(u16, Vec<u8>)> = Vec::new();
1443        if let Some(sig) = &self.signature {
1444            let sig_name = cp.add_utf8("Signature");
1445            let sig_idx = cp.add_utf8(sig);
1446            class_attrs.push((sig_name, sig_idx.to_be_bytes().to_vec()));
1447        }
1448        if !self.inner_classes.is_empty() {
1449            let ic_name = cp.add_utf8("InnerClasses");
1450            let mut ic_body = Vec::new();
1451            ic_body.extend_from_slice(&(self.inner_classes.len() as u16).to_be_bytes());
1452            for ic in &self.inner_classes {
1453                let inner_idx = cp.add_class(&ic.inner_class);
1454                let outer_idx = ic
1455                    .outer_class
1456                    .as_deref()
1457                    .map(|s| cp.add_class(s))
1458                    .unwrap_or(0);
1459                let name_idx = ic
1460                    .inner_name
1461                    .as_deref()
1462                    .map(|s| cp.add_utf8(s))
1463                    .unwrap_or(0);
1464                ic_body.extend_from_slice(&inner_idx.to_be_bytes());
1465                ic_body.extend_from_slice(&outer_idx.to_be_bytes());
1466                ic_body.extend_from_slice(&name_idx.to_be_bytes());
1467                ic_body.extend_from_slice(&ic.access_flags.to_be_bytes());
1468            }
1469            class_attrs.push((ic_name, ic_body));
1470        }
1471        if let Some(host) = &self.nest_host {
1472            let nh_name = cp.add_utf8("NestHost");
1473            let host_idx = cp.add_class(host);
1474            class_attrs.push((nh_name, host_idx.to_be_bytes().to_vec()));
1475        }
1476        if !self.nest_members.is_empty() {
1477            let nm_name = cp.add_utf8("NestMembers");
1478            let mut nm_body = Vec::new();
1479            nm_body.extend_from_slice(&(self.nest_members.len() as u16).to_be_bytes());
1480            for m in &self.nest_members {
1481                let m_idx = cp.add_class(m);
1482                nm_body.extend_from_slice(&m_idx.to_be_bytes());
1483            }
1484            class_attrs.push((nm_name, nm_body));
1485        }
1486        if !self.bootstrap_methods.is_empty() {
1487            let bsm_name = cp.add_utf8("BootstrapMethods");
1488            let mut bsm_body = Vec::new();
1489            bsm_body.extend_from_slice(&(self.bootstrap_methods.len() as u16).to_be_bytes());
1490            for bsm in &self.bootstrap_methods {
1491                bsm_body.extend_from_slice(&bsm.bootstrap_method_ref.to_be_bytes());
1492                bsm_body.extend_from_slice(&(bsm.bootstrap_arguments.len() as u16).to_be_bytes());
1493                for &arg in &bsm.bootstrap_arguments {
1494                    bsm_body.extend_from_slice(&arg.to_be_bytes());
1495                }
1496            }
1497            class_attrs.push((bsm_name, bsm_body));
1498        }
1499        if !self.annotations.is_empty() {
1500            let rva_name = cp.add_utf8("RuntimeVisibleAnnotations");
1501            let rva_body = Self::encode_annotations_attr(&mut cp, &self.annotations);
1502            class_attrs.push((rva_name, rva_body));
1503        }
1504        if !self.invisible_annotations.is_empty() {
1505            let ria_name = cp.add_utf8("RuntimeInvisibleAnnotations");
1506            let ria_body = Self::encode_annotations_attr(&mut cp, &self.invisible_annotations);
1507            class_attrs.push((ria_name, ria_body));
1508        }
1509
1510        let mut out = Vec::with_capacity(512);
1511        out.extend_from_slice(&0xCAFEBABEu32.to_be_bytes());
1512        out.extend_from_slice(&0u16.to_be_bytes());
1513        out.extend_from_slice(&self.major_version.to_be_bytes());
1514        cp.write(&mut out);
1515        out.extend_from_slice(&self.access_flags.to_be_bytes());
1516        out.extend_from_slice(&self.this_class.to_be_bytes());
1517        out.extend_from_slice(&self.super_class.to_be_bytes());
1518        out.extend_from_slice(&(self.interfaces.len() as u16).to_be_bytes());
1519        for iface in &self.interfaces {
1520            out.extend_from_slice(&iface.to_be_bytes());
1521        }
1522        out.extend_from_slice(&field_bytes);
1523        out.extend_from_slice(&method_bytes);
1524        out.extend_from_slice(&(class_attrs.len() as u16).to_be_bytes());
1525        for (name_idx, body) in class_attrs {
1526            out.extend_from_slice(&name_idx.to_be_bytes());
1527            out.extend_from_slice(&(body.len() as u32).to_be_bytes());
1528            out.extend_from_slice(&body);
1529        }
1530
1531        Ok(out)
1532    }
1533}