Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/jni field getter setter without signature #2

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions jni-gen/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,10 @@ error_chain::error_chain! {
description("no matching method")
display("no method '{}' with signature '{}' in class '{}'", method, signature, class)
}

NoField(class: String, field: String) {
description("no field")
display("no field '{}' in class'{}'", field, class)
}
}
}
7 changes: 3 additions & 4 deletions jni-gen/src/generators/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,9 @@ impl<'a> ClassGenerator<'a> {
signature.clone(),
suffix.clone(),
)?,
ItemWrapperSpec::FieldGetterSetter {
ref field_name,
ref signature,
} => generate_field_getter_setter(self.env, &self.class, field_name, signature)?,
ItemWrapperSpec::FieldGetterSetter { ref field_name } => {
generate_field_getter_setter(self.env, &self.class, field_name)?
}
};
gen_items.push(gen)
}
Expand Down
101 changes: 88 additions & 13 deletions jni-gen/src/generators/field_getter_setter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,65 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

// use core::num::flt2dec::Sign;

use crate::{class_name::*, errors::*, utils::*};
use jni::JNIEnv;
use jni::{
objects::{JClass, JObject, JValue},
JNIEnv,
};

fn hierarchy_field_lookup<'a>(
env: &JNIEnv<'a>,
class: &ClassName,
lookup_name: &str,
) -> Result<Option<JObject<'a>>> {
let mut clazz = env.find_class(class.path())?;
while !clazz.is_null() {
if let Some(field) = class_field_lookup(env, clazz, lookup_name)? {
return Ok(Some(field));
}

clazz = env.get_superclass(clazz)?;
}

Ok(None)
}

fn class_field_lookup<'a>(
env: &JNIEnv<'a>,
clazz: JClass<'a>,
lookup_name: &str,
) -> Result<Option<JObject<'a>>> {
let fields = env
.call_method(
clazz,
"getDeclaredFields",
"()[Ljava/lang/reflect/Field;",
&[],
)?
.l()?;

let num_fields = env.get_array_length(*fields)?;

for field_index in 0..num_fields {
let field = env.get_object_array_element(*fields, field_index)?;

let field_name = java_str_to_string(
&env.get_string(
env.call_method(field, "getName", "()Ljava/lang/String;", &[])?
.l()?
.into(),
)?,
)?;

if field_name == lookup_name {
return Ok(Some(field));
}
}

Ok(None)
}

fn generate_type_check(type_signature: &str, type_name: &str, is_result: bool) -> String {
if !type_signature.starts_with('L') {
Expand Down Expand Up @@ -50,23 +107,23 @@ fn generate_parameter_type_check(type_signature: &str, type_name: &str) -> Strin
generate_type_check(type_signature, type_name, false)
}

fn generate_field_getter(class_name: &ClassName, field_name: &str, type_signature: &str) -> String {
fn generate_field_getter(class: &ClassName, field_name: &str, type_signature: &str) -> String {
let rust_getter_name = format!("get_{}", java_identifier_to_rust(field_name));
let parameter_type = generate_jni_type(type_signature);

vec![
format!(
"/// Returns the field `{}` of the scala class `{}`.",
field_name,
class_name.full_name()
class.full_name()
),
"///".to_string(),
format!("/// Return type and Java signature: `{parameter_type}` (`{type_signature}`)"),
format!("pub fn {rust_getter_name}("),
" &self,".to_string(),
" receiver: JObject<'a>,".to_string(),
format!(") -> JNIResult<{parameter_type}> {{"),
format!(" let class_name = \"{}\";", class_name.path()),
format!(" let class_name = \"{}\";", class.path()),
format!(" let field_name = \"{field_name}\";"),
format!(" let return_signature = \"{type_signature}\";"),
"".to_string(),
Expand Down Expand Up @@ -94,7 +151,7 @@ fn generate_field_getter(class_name: &ClassName, field_name: &str, type_signatur
+ "\n"
}

fn generate_field_setter(class_name: &ClassName, field_name: &str, type_signature: &str) -> String {
fn generate_field_setter(class: &ClassName, field_name: &str, type_signature: &str) -> String {
let rust_setter_name = format!("set_{}", java_identifier_to_rust(field_name));
let parameter_name = format!("new_{field_name}");
let parameter_type = generate_jni_type(type_signature);
Expand All @@ -103,7 +160,7 @@ fn generate_field_setter(class_name: &ClassName, field_name: &str, type_signatur
format!(
"/// Sets the field `{}` of the scala class `{}`.",
field_name,
class_name.full_name()
class.full_name()
),
"///".to_string(),
"/// Type and Java signature of parameters:".to_string(),
Expand All @@ -116,7 +173,7 @@ fn generate_field_setter(class_name: &ClassName, field_name: &str, type_signatur
" receiver: JObject<'a>,".to_string(),
format!(" {parameter_name}: {parameter_type},"),
") -> JNIResult<()> {".to_string(),
format!(" let class_name = \"{}\";", class_name.path()),
format!(" let class_name = \"{}\";", class.path()),
format!(" let field_name = \"{field_name}\";"),
format!(" let return_signature = \"{type_signature}\";"),
"".to_string(),
Expand All @@ -142,15 +199,33 @@ fn generate_field_setter(class_name: &ClassName, field_name: &str, type_signatur

pub fn generate_field_getter_setter(
env: &JNIEnv,
class_name: &ClassName,
class: &ClassName,
field_name: &str,
type_signature: &str,
) -> Result<String> {
env.get_field_id(class_name.path(), field_name, type_signature)
.map(|_| ())?;
let field_signature = match hierarchy_field_lookup(env, class, field_name)? {
Some(field) => {
let field_type = env
.call_method(field, "getType", "()Ljava/lang/Class;", &[])?
.l()?;

java_str_to_string(
&env.get_string(
env.call_static_method(
"org/objectweb/asm/Type",
"getDescriptor",
"(Ljava/lang/Class;)Ljava/lang/String;",
&[JValue::Object(field_type)],
)?
.l()?
.into(),
)?,
)?
}
_ => return Err(ErrorKind::NoField(class.full_name(), field_name.into()).into()),
};

let setter_code = generate_field_getter(class_name, field_name, type_signature);
let getter_code = generate_field_setter(class_name, field_name, type_signature);
let setter_code = generate_field_getter(class, field_name, &field_signature);
let getter_code = generate_field_setter(class, field_name, &field_signature);

Ok(format!("{setter_code}\n{getter_code}"))
}
4 changes: 1 addition & 3 deletions jni-gen/src/wrapper_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ pub enum ItemWrapperSpec {
},
FieldGetterSetter {
field_name: String,
signature: String,
},
}

Expand Down Expand Up @@ -113,10 +112,9 @@ macro_rules! method {

#[macro_export]
macro_rules! field {
($name:expr, $signature:expr) => {
($name:expr) => {
ItemWrapperSpec::FieldGetterSetter {
field_name: $name.into(),
signature: $signature.into(),
}
};
}
4 changes: 2 additions & 2 deletions jni-gen/systest/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ fn main() {
.wrap_all(vec![
java_class!("java.lang.Integer", vec![
constructor!("(I)V"),
field!("value", "I")
field!("value")
]),
java_class!("java.util.Arrays", vec![
method!("binarySearch", "([Ljava/lang/Object;Ljava/lang/Object;)I"),
]),
java_class!("java.lang.Error", vec![
constructor!("(Ljava/lang/String;)V"),
method!("getMessage"),
field!("detailMessage", "Ljava/lang/String;"),
field!("detailMessage"),
]),
])
.generate(&generated_dir)
Expand Down