|
| 1 | +use std::fmt::Write; |
| 2 | +use std::path::Path; |
| 3 | + |
| 4 | +use cafebabe::descriptors::{FieldDescriptor, FieldType, ReturnDescriptor}; |
| 5 | + |
| 6 | +use super::classes::Class; |
| 7 | +use super::methods::Method; |
| 8 | +use crate::emit::Context; |
| 9 | + |
| 10 | +impl Class { |
| 11 | + pub(crate) fn write_java_proxy(&self, context: &Context, methods: &[Method]) -> anyhow::Result<String> { |
| 12 | + let java_proxy_path = format!( |
| 13 | + "{}/{}", |
| 14 | + context.config.proxy_package, |
| 15 | + self.java.path().as_str().replace("$", "_") |
| 16 | + ); |
| 17 | + |
| 18 | + let package_name = java_proxy_path.rsplit_once('/').map(|x| x.0).unwrap_or(""); |
| 19 | + let class_name = java_proxy_path.split('/').next_back().unwrap(); |
| 20 | + |
| 21 | + let mut w = String::new(); |
| 22 | + |
| 23 | + // Package declaration |
| 24 | + if !package_name.is_empty() { |
| 25 | + writeln!(w, "package {};", package_name.replace("/", "."))?; |
| 26 | + writeln!(w)?; |
| 27 | + } |
| 28 | + |
| 29 | + // Class declaration |
| 30 | + let parent_type = if self.java.is_interface() { |
| 31 | + "implements" |
| 32 | + } else { |
| 33 | + "extends" |
| 34 | + }; |
| 35 | + |
| 36 | + writeln!(w, "@SuppressWarnings(\"rawtypes\")")?; |
| 37 | + |
| 38 | + writeln!( |
| 39 | + w, |
| 40 | + "class {} {} {} {{", |
| 41 | + class_name, |
| 42 | + parent_type, |
| 43 | + self.java.path().as_str().replace('/', ".") |
| 44 | + )?; |
| 45 | + |
| 46 | + // ptr field |
| 47 | + writeln!(w, " long ptr;")?; |
| 48 | + writeln!(w)?; |
| 49 | + |
| 50 | + // Constructor |
| 51 | + writeln!(w, " private {class_name}(long ptr) {{")?; |
| 52 | + writeln!(w, " this.ptr = ptr;")?; |
| 53 | + writeln!(w, " }}")?; |
| 54 | + writeln!(w)?; |
| 55 | + |
| 56 | + // Finalize method |
| 57 | + writeln!(w, " @Override")?; |
| 58 | + writeln!(w, " protected void finalize() throws Throwable {{")?; |
| 59 | + writeln!(w, " native_finalize(this.ptr);")?; |
| 60 | + writeln!(w, " }}")?; |
| 61 | + writeln!(w, " private native void native_finalize(long ptr);")?; |
| 62 | + writeln!(w)?; |
| 63 | + |
| 64 | + // Generate methods |
| 65 | + for method in methods { |
| 66 | + let Some(_rust_name) = method.rust_name() else { continue }; |
| 67 | + if method.java.is_static() |
| 68 | + || method.java.is_static_init() |
| 69 | + || method.java.is_constructor() |
| 70 | + || method.java.is_final() |
| 71 | + || method.java.is_private() |
| 72 | + { |
| 73 | + continue; |
| 74 | + } |
| 75 | + |
| 76 | + let method_name = method.java.name(); |
| 77 | + |
| 78 | + // Method signature |
| 79 | + let return_type = match &method.java.descriptor.return_type { |
| 80 | + ReturnDescriptor::Void => "void".to_string(), |
| 81 | + ReturnDescriptor::Return(desc) => java_type_name(desc)?, |
| 82 | + }; |
| 83 | + |
| 84 | + let mut params = Vec::new(); |
| 85 | + for (i, param) in method.java.descriptor.parameters.iter().enumerate() { |
| 86 | + let param_type = java_type_name(param)?; |
| 87 | + params.push(format!("{param_type} arg{i}")); |
| 88 | + } |
| 89 | + |
| 90 | + writeln!(w, " @Override")?; |
| 91 | + writeln!( |
| 92 | + w, |
| 93 | + " public {} {}({}) {{", |
| 94 | + return_type, |
| 95 | + method_name, |
| 96 | + params.join(", ") |
| 97 | + )?; |
| 98 | + |
| 99 | + // Method body - call native method |
| 100 | + let native_method_name = format!("native_{method_name}"); |
| 101 | + let mut args = vec!["ptr".to_string()]; |
| 102 | + for i in 0..method.java.descriptor.parameters.len() { |
| 103 | + args.push(format!("arg{i}")); |
| 104 | + } |
| 105 | + |
| 106 | + if return_type == "void" { |
| 107 | + writeln!(w, " {}({});", native_method_name, args.join(", "))?; |
| 108 | + } else { |
| 109 | + writeln!(w, " return {}({});", native_method_name, args.join(", "))?; |
| 110 | + } |
| 111 | + writeln!(w, " }}")?; |
| 112 | + |
| 113 | + // Native method declaration |
| 114 | + let mut native_params = vec!["long ptr".to_string()]; |
| 115 | + for (i, param) in method.java.descriptor.parameters.iter().enumerate() { |
| 116 | + let param_type = java_type_name(param)?; |
| 117 | + native_params.push(format!("{param_type} arg{i}")); |
| 118 | + } |
| 119 | + |
| 120 | + writeln!( |
| 121 | + w, |
| 122 | + " private native {} {}({});", |
| 123 | + return_type, |
| 124 | + native_method_name, |
| 125 | + native_params.join(", ") |
| 126 | + )?; |
| 127 | + writeln!(w)?; |
| 128 | + } |
| 129 | + |
| 130 | + writeln!(w, "}}")?; |
| 131 | + |
| 132 | + Ok(w) |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +fn java_type_name(desc: &FieldDescriptor) -> anyhow::Result<String> { |
| 137 | + let mut result = String::new(); |
| 138 | + |
| 139 | + let base_type = match &desc.field_type { |
| 140 | + FieldType::Byte => "byte", |
| 141 | + FieldType::Char => "char", |
| 142 | + FieldType::Double => "double", |
| 143 | + FieldType::Float => "float", |
| 144 | + FieldType::Integer => "int", |
| 145 | + FieldType::Long => "long", |
| 146 | + FieldType::Short => "short", |
| 147 | + FieldType::Boolean => "boolean", |
| 148 | + FieldType::Object(path) => { |
| 149 | + // Convert JNI path to Java path |
| 150 | + return Ok(format!( |
| 151 | + "{}{}", |
| 152 | + path.replace('/', "."), |
| 153 | + "[]".repeat(desc.dimensions as usize) |
| 154 | + )); |
| 155 | + } |
| 156 | + }; |
| 157 | + |
| 158 | + result.push_str(base_type); |
| 159 | + |
| 160 | + // Add array dimensions |
| 161 | + for _ in 0..desc.dimensions { |
| 162 | + result.push_str("[]"); |
| 163 | + } |
| 164 | + |
| 165 | + Ok(result) |
| 166 | +} |
| 167 | + |
| 168 | +pub fn write_java_proxy_files(context: &Context, output_dir: &Path) -> anyhow::Result<()> { |
| 169 | + for (_, class) in context.all_classes.iter() { |
| 170 | + let cc = context.config.resolve_class(class.java.path().as_str()); |
| 171 | + if !cc.proxy { |
| 172 | + continue; |
| 173 | + } |
| 174 | + |
| 175 | + // Collect methods for this class |
| 176 | + let mut methods = Vec::new(); |
| 177 | + methods.extend(class.java.methods().map(|m| Method::new(&class.java, m))); |
| 178 | + |
| 179 | + let java_code = class.write_java_proxy(context, &methods)?; |
| 180 | + |
| 181 | + // Calculate output file path |
| 182 | + let java_proxy_path = class.java.path().as_str().replace("$", "_"); |
| 183 | + |
| 184 | + let relative_path = format!("{java_proxy_path}.java"); |
| 185 | + let output_file = output_dir.join(&relative_path); |
| 186 | + |
| 187 | + // Create directory if it doesn't exist |
| 188 | + if let Some(parent) = output_file.parent() { |
| 189 | + std::fs::create_dir_all(parent)?; |
| 190 | + } |
| 191 | + |
| 192 | + // Write Java file |
| 193 | + std::fs::write(&output_file, java_code)?; |
| 194 | + |
| 195 | + println!("Generated Java proxy: {}", output_file.display()); |
| 196 | + } |
| 197 | + |
| 198 | + Ok(()) |
| 199 | +} |
0 commit comments