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
use inflector::cases::camelcase::to_camel_case;
use proc_macro2::{TokenStream, TokenTree};
use proc_macro_error::{abort, emit_error, emit_warning};
use quote::{quote_spanned, ToTokens};
use syn::fold::Fold;
use syn::spanned::Spanned;
use syn::{parse_quote, TypePath, Type, PathArguments, GenericArgument};
use syn::{FnArg, ImplItemMethod, Pat, PatIdent, ReturnType, Signature};
use crate::utils::{get_abi, get_env_arg, is_self_method};
use crate::transformation::utils::get_call_type;
use crate::transformation::{CallType, CallTypeAttribute, SafeParams};
use std::collections::HashSet;
use crate::transformation::context::StructContext;
pub struct ImportedMethodTransformer<'ctx> {
pub(crate) struct_context: &'ctx StructContext
}
impl<'ctx> Fold for ImportedMethodTransformer<'ctx> {
fn fold_impl_item_method(&mut self, node: ImplItemMethod) -> ImplItemMethod {
let abi = get_abi(&node.sig);
match (&node.vis, &abi.as_deref()) {
(_, Some("java")) => {
let constructor_attribute = node.attrs.iter().find(|a| a.path.get_ident().map(ToString::to_string).as_deref() == Some("constructor"));
let is_constructor = {
match constructor_attribute {
Some(a) => {
if !a.tokens.is_empty() {
emit_warning!(a.tokens, "#[constructor] attribute does not take parameters")
}
true
},
None => false
}
};
if !node.block.stmts.is_empty() {
emit_error!(
node.block,
"`extern \"java\"` methods must have an empty body"
)
}
let original_signature = node.sig.clone();
let self_method = is_self_method(&node.sig);
let (signature, env_arg) = get_env_arg(node.sig.clone());
let impl_item_attributes: Vec<_> = {
let discarded_known_attributes: HashSet<&str> = {
let mut h = HashSet::new();
h.insert("call_type");
if is_constructor {
h.insert("constructor");
}
h
};
node.clone().attrs
.into_iter()
.filter(|a| {
!discarded_known_attributes
.contains(&a.path.segments.to_token_stream().to_string().as_str())
})
.collect()
};
let dummy = ImplItemMethod {
sig: Signature {
abi: None,
..original_signature.clone()
},
block: parse_quote! {{
unimplemented!()
}},
attrs: impl_item_attributes.clone(),
..node.clone()
};
if is_constructor && self_method {
emit_error!(original_signature,
"cannot have self methods declared as constructors");
return dummy;
}
if env_arg.is_none() {
if !self_method {
emit_error!(
original_signature,
"imported static methods must have a parameter of type `&JNIEnv` as first parameter"
);
} else {
emit_error!(
original_signature,
"imported self methods must have a parameter of type `&JNIEnv` as second parameter"
);
}
return dummy;
}
let call_type_attribute = get_call_type(&node);
let call_type = call_type_attribute.as_ref().map(|c| &c.call_type).unwrap_or(&CallType::Safe(None));
if let Some(CallTypeAttribute { attr, ..}) = &call_type_attribute {
if let CallType::Safe(Some(params)) = call_type {
if let SafeParams { message: Some(_), .. } | SafeParams { exception_class: Some(_), .. } = params {
abort!(attr, "can't have exception message or exception class for imported methods")
}
}
}
let jni_package_path = self
.struct_context
.package
.as_ref()
.map(|p| p.to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "".into())
.replace('.', "/");
let java_class_path = [jni_package_path, self.struct_context.struct_name.clone()]
.iter()
.filter(|s| !s.is_empty())
.map(|s| s.to_owned())
.collect::<Vec<_>>()
.join("/");
let java_method_name = to_camel_case(&signature.ident.to_string());
let input_types_conversions = signature
.inputs
.iter()
.filter_map(|i| match i {
FnArg::Typed(t) => match &*t.pat {
Pat::Ident(PatIdent { ident, .. }) if ident == "self" => None,
_ => Some((&t.ty, t.ty.span()))
},
FnArg::Receiver(_) => None,
})
.map(|(t, span)| {
if let CallType::Safe(_) = call_type {
quote_spanned! { span => <#t as ::robusta_jni::convert::TryIntoJavaValue>::SIG_TYPE, }
} else {
quote_spanned! { span => <#t as ::robusta_jni::convert::IntoJavaValue>::SIG_TYPE, }
}
})
.fold(TokenStream::new(), |t, mut tok| {
t.to_tokens(&mut tok);
tok
});
let output_type_span = {
match &signature.output {
ReturnType::Default => signature.output.span(),
ReturnType::Type(_arrow, ref ty) => ty.span()
}
};
let output_conversion = match signature.output {
ReturnType::Default => quote_spanned!(signature.output.span() => ),
ReturnType::Type(_arrow, ref ty) => {
if is_constructor {
quote_spanned! { output_type_span => "V" }
} else {
match call_type {
CallType::Safe(_) => {
let inner_result_ty = match &**ty {
Type::Path(TypePath { path, .. }) => {
path.segments.last().map(|s| match &s.arguments {
PathArguments::AngleBracketed(a) => {
match &a.args.first().expect("return type must be `::robusta_jni::jni::errors::Result` when using \"java\" ABI with an implicit or \"safe\" `call_type`") {
GenericArgument::Type(t) => t,
_ => abort!(a, "first generic argument in return type must be a type")
}
},
PathArguments::None => {
let user_attribute_message = call_type_attribute.as_ref().map(|_| "because of this attribute");
abort!(s, "return type must be `::robusta_jni::jni::errors::Result` when using \"java\" ABI with an implicit or \"safe\" `call_type`";
help = "replace `{}` with `Result<{}>`", s.ident, s.ident;
help =? call_type_attribute.as_ref().map(|c| c.attr.span()).unwrap() => user_attribute_message)
},
_ => abort!(s, "return type must be `::robusta_jni::jni::errors::Result` when using \"java\" ABI with an implicit or \"safe\" `call_type`")
})
},
_ => abort!(ty, "return type must be `::robusta_jni::jni::errors::Result` when using \"java\" ABI with an implicit or \"safe\" `call_type`")
}.unwrap();
quote_spanned! { output_type_span => <#inner_result_ty as ::robusta_jni::convert::TryIntoJavaValue>::SIG_TYPE }
}
CallType::Unchecked(_) => {
if let Type::Path(TypePath { path, .. }) = ty.as_ref() {
if let Some(r) = path.segments.last().filter(|i| i.ident == "Result") {
if let PathArguments::AngleBracketed(_) = r.arguments {
let call_type_span = call_type_attribute.as_ref().map(|c| c.attr.span());
let call_type_hint = call_type_span.map(|_| "maybe you meant `#[call_type(safe)]`?");
emit_warning!(ty, "using a `Result` type in a `#[call_type(unchecked)]` method";
hint =? call_type_span.unwrap() => call_type_hint)
}
}
}
quote_spanned! { output_type_span => <#ty as ::robusta_jni::convert::IntoJavaValue>::SIG_TYPE }
}
}
}
}
};
let java_signature =
quote_spanned! { signature.span() => ["(", #input_types_conversions ")", #output_conversion].join("") };
let input_conversions = signature.inputs.iter().fold(TokenStream::new(), |mut tok, input| {
match input {
FnArg::Receiver(_) => { tok }
FnArg::Typed(t) => {
let ty = &t.ty;
let pat: TokenStream = {
let pat = &t.pat;
let mut p: TokenTree = parse_quote! { #pat };
p.set_span(ty.span());
p.into()
};
let conversion: TokenStream = if let CallType::Safe(_) = call_type {
quote_spanned! { ty.span() => ::std::convert::Into::into(<#ty as ::robusta_jni::convert::TryIntoJavaValue>::try_into(#pat, &env)?), }
} else {
quote_spanned! { ty.span() => ::std::convert::Into::into(<#ty as ::robusta_jni::convert::IntoJavaValue>::into(#pat, &env)), }
};
conversion.to_tokens(&mut tok);
tok
}
}
});
let return_expr = match call_type {
CallType::Safe(_) => {
if is_constructor {
quote_spanned! { output_type_span =>
res.and_then(|v| ::robusta_jni::convert::TryFromJavaValue::try_from(v, &env))
}
} else {
quote_spanned! { output_type_span =>
res.and_then(|v| ::std::convert::TryInto::try_into(::robusta_jni::convert::JValueWrapper::from(v)))
.and_then(|v| ::robusta_jni::convert::TryFromJavaValue::try_from(v, &env))
}
}
}
CallType::Unchecked(_) => {
if is_constructor {
quote_spanned! { output_type_span =>
::robusta_jni::convert::FromJavaValue::from(res, &env)
}
} else {
quote_spanned! { output_type_span =>
::std::convert::TryInto::try_into(::robusta_jni::convert::JValueWrapper::from(res))
.map(|v| ::robusta_jni::convert::FromJavaValue::from(v, &env))
.unwrap()
}
}
}
};
let env_ident = match env_arg.unwrap() {
FnArg::Typed(t) => {
match *t.pat {
Pat::Ident(PatIdent { ident, .. }) => ident,
_ => panic!("non-ident pat in FnArg")
}
},
_ => panic!("Bug -- please report to library author. Expected env parameter, found receiver")
};
ImplItemMethod {
sig: Signature {
abi: None,
..original_signature
},
block: if self_method {
let self_span = node.sig.inputs.iter().next().unwrap().span();
match call_type {
CallType::Safe(_) => {
parse_quote_spanned! { self_span => {
let env: &'_ ::robusta_jni::jni::JNIEnv<'_> = #env_ident;
let res = env.call_method(::robusta_jni::convert::JavaValue::autobox(::robusta_jni::convert::TryIntoJavaValue::try_into(self, &env)?, &env), #java_method_name, #java_signature, &[#input_conversions]);
#return_expr
}}
}
CallType::Unchecked(_) => {
parse_quote_spanned! { self_span => {
let env: &'_ ::robusta_jni::jni::JNIEnv<'_> = #env_ident;
let res = env.call_method(::robusta_jni::convert::JavaValue::autobox(::robusta_jni::convert::IntoJavaValue::into(self, &env), &env), #java_method_name, #java_signature, &[#input_conversions]).unwrap();
#return_expr
}}
}
}
} else {
match call_type {
CallType::Safe(_) => {
if is_constructor {
parse_quote! {{
let env: &'_ ::robusta_jni::jni::JNIEnv<'_> = #env_ident;
let res = env.new_object(#java_class_path, #java_signature, &[#input_conversions]);
#return_expr
}}
} else {
parse_quote! {{
let env: &'_ ::robusta_jni::jni::JNIEnv<'_> = #env_ident;
let res = env.call_static_method(#java_class_path, #java_method_name, #java_signature, &[#input_conversions]);
#return_expr
}}
}
},
CallType::Unchecked(_) => {
if is_constructor {
parse_quote! {{
let env: &'_ ::robusta_jni::jni::JNIEnv<'_> = #env_ident;
let res = env.new_object(#java_class_path, #java_signature, &[#input_conversions]).unwrap();
#return_expr
}}
} else {
parse_quote! {{
let env: &'_ ::robusta_jni::jni::JNIEnv<'_> = #env_ident;
let res = env.call_static_method(#java_class_path, #java_method_name, #java_signature, &[#input_conversions]).unwrap();
#return_expr
}}
}
}
}
},
attrs: impl_item_attributes,
..node
}
}
_ => node,
}
}
}