droid_wrap_derive/
lib.rs

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
/*
 * Copyright (c) 2024. The RigelA open source project team and
 * its contributors reserve all rights.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */

mod utils;

use proc_macro::TokenStream;

use heck::ToLowerCamelCase;
use proc_macro2::{Ident, Span, TokenStream as TokenStream2};
use quote::{quote, ToTokens};
use syn::{
    parse2, parse_macro_input, punctuated::Punctuated, Field, FieldMutability, Fields, FieldsNamed,
    ImplItem, ItemFn, ItemImpl, ItemStruct, ItemTrait, LitInt, Token, TraitItem, Type,
    TypeParamBound, Visibility,
};

use crate::utils::{get_object_return_value_token, get_result_token, get_return_value_token, parse_function_signature, ClassMetadata, FieldMetadata, InterfaceMetadata, MethodMetadata};

//noinspection SpellCheckingInspection
/// 定义java class,将此属性标记在struct上,可以自动实现操作java对象的必要功能。
///
/// # Arguments
///
/// * `attrs`: 属性输入。
/// * `input`: struct输入。
///
/// returns: TokenStream
///
/// # Examples
///
/// ```
/// use droid_wrap_derive::java_class;
/// #[java_class(name = "java/lang/System")]
/// struct System;
/// ```
#[proc_macro_attribute]
pub fn java_class(attrs: TokenStream, input: TokenStream) -> TokenStream {
    let attrs: ClassMetadata = parse2(Into::<TokenStream2>::into(attrs)).unwrap();
    let cls = attrs.class_name;
    let based = attrs.base_class;
    let mut item = parse_macro_input!(input as ItemStruct);
    let name = item.ident.clone();
    let generics = item.generics.clone();
    let mut item2 = item.clone();

    let mut add_field_this = Field {
        attrs: vec![],
        vis: Visibility::Inherited,
        mutability: FieldMutability::None,
        ident: Some(Ident::new("_this", Span::call_site())),
        colon_token: None,
        ty: Type::Verbatim(quote! {droid_wrap_utils::GlobalRef}),
    };
    let mut add_field_super = Field {
        attrs: vec![],
        vis: Visibility::Inherited,
        mutability: FieldMutability::None,
        ident: Some(Ident::new("_based", Span::call_site())),
        colon_token: None,
        ty: Type::Verbatim(based.to_token_stream()),
    };

    let (fields, added_this, added_super, added_default) = match item.fields {
        Fields::Named(mut f) => {
            let mut added_default = TokenStream2::new();
            for i in f.named.iter() {
                let i = i.ident.clone();
                added_default.extend(quote! {#i: fields.#i,});
            }
            f.named.push(add_field_this);
            let added_super = if based.is_some() {
                f.named.push(add_field_super);
                quote! {_based}
            } else {
                quote!()
            };
            (Fields::Named(f), quote! {_this}, added_super, added_default)
        }
        Fields::Unnamed(mut f) => {
            let mut added_default = TokenStream2::new();
            for i in 0..f.unnamed.len() {
                let i = LitInt::new(&i.to_string(), Span::call_site());
                added_default.extend(quote! {#i: fields.#i,});
            }
            add_field_this.ident = None;
            add_field_super.ident = None;
            let len = LitInt::new(&f.unnamed.len().to_string(), Span::call_site());
            let added_this = quote! {#len};
            f.unnamed.push(add_field_this);
            let added_super = if based.is_some() {
                let len = LitInt::new(&f.unnamed.len().to_string(), Span::call_site());
                f.unnamed.push(add_field_super);
                quote! {#len}
            } else {
                quote!()
            };
            (Fields::Unnamed(f), added_this, added_super, added_default)
        }
        Fields::Unit => {
            let mut fields = Punctuated::<Field, Token![,]>::new();
            fields.push(add_field_this);
            let added_super = if based.is_some() {
                fields.push(add_field_super);
                quote! {_based}
            } else {
                quote!()
            };
            (
                Fields::Named(FieldsNamed {
                    brace_token: Default::default(),
                    named: fields,
                }),
                quote! {_this},
                added_super,
                quote!(),
            )
        }
    };
    item.fields = fields;

    let build_self = if based.is_some() {
        quote! {
            Self {#added_this: this.clone(), #added_super: this.into(), #added_default }
        }
    } else {
        quote! {
            Self {#added_this:this.clone(), #added_default }
        }
    };

    let (item2_token, name2) = if added_default.is_empty() {
        (quote!(), quote! {()})
    } else {
        let name2 = Ident::new((name.to_string() + "Default").as_str(), Span::call_site());
        item2.ident = name2.clone();
        (quote! {#item2}, quote! {#name2})
    };

    let impl_based_deref = if based.is_some() {
        quote! {
            impl #generics std::ops::Deref for #name #generics {
                type Target = #based;

                fn deref(&self) -> &Self::Target {
                    &self.#added_super
                }
            }

            impl #generics std::ops::DerefMut for #name #generics {
                fn deref_mut(&mut self) -> &mut Self::Target {
                    &mut self.#added_super
                }
            }
        }
    } else {
        quote! {
            impl #generics std::ops::Deref for #name #generics {
                type Target = droid_wrap_utils::GlobalRef;

                fn deref(&self) -> &Self::Target {
                    &self.#added_this
                }
            }
        }
    };

    let stream = quote! {
        #item
        #item2_token

        impl #generics JObjNew for #name #generics {
            type Fields = #name2;

            fn _new(this: &droid_wrap_utils::GlobalRef, fields: Self::Fields) -> Self {
                #build_self
            }
        }

        impl #generics JType for #name #generics {
            type Error = droid_wrap_utils::Error;
            const CLASS: &'static str = #cls;
            const OBJECT_SIG: &'static str = concat!("L", #cls, ";");
        }

        impl #generics JObjRef for #name #generics {
            fn java_ref(&self) -> droid_wrap_utils::GlobalRef {
                self.#added_this.clone()
            }
        }

        impl #generics PartialEq for #name #generics {
            fn eq(&self, other: &Self) -> bool {
                let r = self.java_ref();
                let t = other.java_ref();
                if r.is_null() && t.is_null() {
                    return true;
                }
                if r.is_null() {
                    return false;
                }
                droid_wrap_utils::vm_attach!(mut env);
                env.call_method(
                    r.clone(),
                    "equals",
                    "(Ljava/lang/Object;)Z",
                    &[t.as_obj().into()]
                ).unwrap().z().unwrap()
            }
    }

        impl #generics ToString for #name #generics {
            fn to_string(&self) -> String {
                let r = self.java_ref();
                if r.is_null() {
                    return "null".to_string();
                }
                droid_wrap_utils::vm_attach!(mut env);
                let s = match env.call_method(r.clone(), "toString", format!("()L{};", String::CLASS).as_str(), &[]) {
                    Ok(s) => match s.l() {
                        Ok(s) => s,
                        Err(e) => return e.to_string()
                    },
                    Err(e) => return e.to_string()
                };
                let s = match env.get_string((&s).into()) {
                    Ok(s) => s,
                    Err(e) => return e.to_string()
                };
                s.to_str().unwrap().to_string()
            }
        }

        impl #generics std::fmt::Debug for #name #generics {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", self.to_string())
            }
        }

        impl #generics From<&droid_wrap_utils::GlobalRef> for #name #generics {
            fn from(obj: &droid_wrap_utils::GlobalRef) -> Self {
                Self::_new(&obj, <Self as JObjNew>::Fields::default())
            }
        }

        impl #generics Into<droid_wrap_utils::GlobalRef> for &#name #generics {
            fn into(self) -> droid_wrap_utils::GlobalRef {
                self.java_ref()
            }
        }

        #impl_based_deref
    };
    stream.into()
}

/// 实现java类的方法,将此属性标记在fn函数上,可以自动实现调用java方法,可以自动识别静态方法(如果参数中没有“self”)。
///
/// # Arguments
///
/// * `attrs`: 属性输入。
/// * `input`: 函数输入。
///
/// returns: TokenStream
///
/// # Examples
///
/// ```
/// use droid_wrap_derive::java_method;
/// struct System;
/// impl System {
/// #[java_method]
/// fn current_time_millis() -> i64 {}
/// }
/// ```
#[proc_macro_attribute]
pub fn java_method(attrs: TokenStream, input: TokenStream) -> TokenStream {
    let attrs: MethodMetadata = parse2(Into::<TokenStream2>::into(attrs)).unwrap();
    let type_bounds = attrs.type_bounds;
    let overload = attrs.overload;
    let item = parse_macro_input!(input as ItemFn);
    let attrs = item.attrs.clone();
    let stmts = item.block.stmts.clone();
    let name = if overload.is_none() {
        item.sig.ident.to_string()
    } else {
        overload.unwrap().to_token_stream().to_string()
    }
    .to_lower_camel_case();
    let vis = item.vis.clone();
    let sig = item.sig.clone();

    let (self_, _, arg_types_sig, fmt, arg_values, ret_type) =
        parse_function_signature(&sig, &type_bounds);
    let (ret_value, ret_type_sig, is_result_type) =
        get_return_value_token(&ret_type, &sig.generics, &type_bounds, &None);

    let ret_value = get_result_token(is_result_type, &ret_value);

    let class_token = if let Some(it) = type_bounds.iter().find(|i| i.0.to_string() == "Self") {
        let tt = it.1.clone();
        quote! {<Self as #tt>::CLASS}
    } else {
        quote! {Self::CLASS}
    };

    if self_.is_none() {
        quote! {
            #(#attrs)*
            #vis #sig {
                #(#stmts)*
                droid_wrap_utils::vm_attach!(mut env);
                let ret = env.call_static_method(
                    #class_token,
                    #name,
                    format!(#fmt, #arg_types_sig #ret_type_sig).as_str(),
                    &[#arg_values],
                );
                #ret_value
            }
        }
    } else {
        quote! {
            #(#attrs)*
            #vis #sig {
                #(#stmts)*
                droid_wrap_utils::vm_attach!(mut env);
                let ret = env.call_method(
                    #self_.java_ref(),
                    #name,
                    format!(#fmt, #arg_types_sig #ret_type_sig).as_str(),
                    &[#arg_values],
                );
                #ret_value
            }
        }
    }
    .into()
}

/// 实现java类的构造器,将此属性标记在fn函数上,可以自动实现调用java类的构造器。
///
/// # Arguments
///
/// * `_`: 未使用。
/// * `input`: 函数输入。
///
/// returns: TokenStream
///
/// # Examples
///
/// ```
/// use droid_wrap_derive::java_constructor;
/// struct Integer;
/// impl Integer {
/// #[java_constructor]
/// fn new(value: i32) -> Self {}
/// }
/// ```
#[proc_macro_attribute]
pub fn java_constructor(_: TokenStream, input: TokenStream) -> TokenStream {
    let item = parse_macro_input!(input as ItemFn);
    let attrs = item.attrs.clone();
    let vis = item.vis.clone();
    let sig = item.sig.clone();
    let stmts = item.block.stmts.clone();
    let (self_, _, arg_types, fmt, arg_values, ret_type) = parse_function_signature(&sig, &vec![]);

    if !self_.is_none() {
        panic!(
            "Incorrect constructor, please remove the '{}' in the arguments!",
            self_.to_token_stream()
        );
    }

    if !ret_type.to_string().contains("Self") {
        panic!(
            "Incorrect constructor, please modify the '{}' to 'Self', 'Option<Self>' or 'Result<Self, Self::Error>' in the return value!",
            ret_type
        );
    }

    let (ret_value, _) = get_object_return_value_token(&ret_type);

    let stream = quote! {
        #(#attrs)*
        #vis #sig {
            #(#stmts)*
            droid_wrap_utils::vm_attach!(mut env);
            let obj = env.new_object(
                <Self as JType>::CLASS,
                format!(#fmt, #arg_types "V").as_str(),
                &[#arg_values],
            )
            .unwrap();
            #ret_value
        }
    };

    stream.into()
}

/// 定义java interface,将此属性标记在trait上,可以自动实现提供java对象与rust对象的互操作的功能。
///
/// # Arguments
///
/// * `attrs`: 属性。
/// * `input`: 特征输入。
///
/// returns: TokenStream
///
/// # Examples
///
/// ```
/// use droid_wrap_derive::java_interface;
/// trait Runnable {
/// fn run(&self);
/// }
/// ```
#[proc_macro_attribute]
pub fn java_interface(attrs: TokenStream, input: TokenStream) -> TokenStream {
    let attrs: InterfaceMetadata = parse2(Into::<TokenStream2>::into(attrs)).unwrap();
    let cls = attrs.interface_name;
    let mut item = parse_macro_input!(input as ItemTrait);
    item.supertraits
        .push(TypeParamBound::Verbatim(quote! {JObjRef}));
    item.supertraits
        .push(TypeParamBound::Verbatim(quote! {JObjNew}));
    item.supertraits
        .push(TypeParamBound::Verbatim(quote! {PartialEq}));
    item.supertraits
        .push(TypeParamBound::Verbatim(quote! {std::fmt::Debug}));

    item.items.push(TraitItem::Verbatim(quote! {
        #[doc = #cls]
        const CLASS: &'static str = #cls;
    }));
    item.items.push(TraitItem::Verbatim(quote! {
        #[doc = concat!("L", #cls, ";")]
        const OBJECT_SIG: &'static str = concat!("L", #cls, ";");
    }));
    item.items.push(TraitItem::Verbatim(quote! {
        /// 数组维度
        const DIM: u8 = 0;
    }));
    let stream = quote! {
        #item
    };
    stream.into()
}

//noinspection SpellCheckingInspection
/// 实现java interface,将此属性标记在impl上,可以自动实现java接口的动态代理,从而实现java层回调rust层。
/// 其中在接口中定义的每一个方法将自动实现并暴露给java层,但以下划线“_”开头的函数除外。
///
/// # Arguments
///
/// * `attrs`: 属性。
/// * `input`: impl输入。
///
/// returns: TokenStream
///
/// # Examples
///
/// ```
/// use std::fmt::{Debug, Formatter};
/// use droid_wrap_derive::{java_interface,java_implement};
/// #[java_interface(name = "java/lang/Runnable")]
/// trait Runnable {
/// fn run(&self);
/// }
/// struct RunnableImpl;
/// impl PartialEq for RunnableImpl {
///     fn eq(&self, other: &Self) -> bool {
///         todo!()
///     }
/// }
/// impl Debug for RunnableImpl {
///     fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
///         todo!()
///     }
/// }
/// #[java_implement]
/// impl Runnable for RunnableImpl {
/// fn run(&self) {
/// println!("Called from java.");
/// }
/// }
/// ```
#[proc_macro_attribute]
pub fn java_implement(attrs: TokenStream, input: TokenStream) -> TokenStream {
    let item: TokenStream2 = input.into();
    let attrs: TokenStream2 = attrs.into();

    let item = parse2::<ItemImpl>(item.clone()).unwrap();

    let mut methods = TokenStream2::new();
    for item in item.items.iter() {
        match item {
            ImplItem::Fn(f) => {
                let name = f.sig.ident.clone();
                if name.to_string().starts_with("_") {
                    // 跳过下划线开头的函数
                    continue;
                }
                let name_camel = f.sig.ident.to_string().to_lower_camel_case();
                let (self_, arg_types, _, _, _, ret_type) =
                    parse_function_signature(&f.sig, &vec![]);
                if self_.is_none() {
                    continue;
                }

                let ret_token = match ret_type.to_string().as_str() {
                    "()" => quote! {droid_wrap_utils::null_value(env)},
                    "bool" => quote! {droid_wrap_utils::wrapper_bool_value(ret, env)},
                    "i32" => quote! {droid_wrap_utils::wrapper_integer_value(ret, env)},
                    "u32" => quote! {droid_wrap_utils::wrapper_integer_value(ret as u32, env)},
                    "i64" => quote! {droid_wrap_utils::wrapper_long_value(ret, env)},
                    "u64" => quote! {droid_wrap_utils::wrapper_long_value(ret as u64, env)},
                    _ => quote! {ret.java_ref()},
                };

                let mut arg_tokens = TokenStream2::new();
                for i in 0..arg_types.len() {
                    let (unwrapped_ty, origin_ty) = &arg_types[i];
                    let ty_str = unwrapped_ty.to_string();
                    let ar = if [
                        "bool", "char", "i16", "u16", "i32", "u32", "i64", "u64", "f32", "f64",
                    ]
                    .contains(&ty_str.as_str())
                    {
                        quote! {
                            droid_wrap_utils::ParseJObjectType::<#unwrapped_ty>::parse(&args2[#i], env),
                        }
                    } else if origin_ty.to_string().starts_with("Option") {
                        quote! {{
                            if args2[#i].is_null() {
                                None
                            } else {
                                let r = env.new_global_ref(&args2[#i]).unwrap();
                                Some(#unwrapped_ty::_new(&r, Default::default()))
                            }
                        },}
                    } else {
                        quote! {{
                            let r = env.new_global_ref(&args2[#i]).unwrap();
                            #unwrapped_ty::_new(&r, Default::default())
                        },}
                    };
                    arg_tokens.extend(ar);
                }
                methods.extend(quote! {
                    Ok(#name_camel) => {
                        let args2 = droid_wrap_utils::to_vec(env, &args);
                        let ret = self_.#name(#arg_tokens);
                        #ret_token
                    },
                })
            }
            _ => {}
        }
    }
    // println!("b{}", methods);

    let name = item.self_ty.clone();
    let class_token = match item.trait_ {
        None => quote! {Self::CLASS},
        Some((_, ref p, _)) => quote! {<Self as #p>::CLASS},
    };

    let impl_new = quote! {
        fn new(fields: Self::Fields) -> std::sync::Arc<Self> {
            use std::sync::Arc;
            let interface = #class_token.replace("/", ".");
            let proxy = droid_wrap_utils::new_proxy(&[&interface]);
            let ret = Arc::new(Self::_new(&proxy, fields));
            let self_ = ret.clone();
            droid_wrap_utils::bind_proxy_handler(&proxy, move |env, method, args| {
                let name = env.call_method(&method, "getName", "()Ljava/lang/String;", &[]).unwrap().l().unwrap();
                let name = env.get_string((&name).into()).unwrap();
                match name.to_str() {
                    #methods
                    _ => droid_wrap_utils::null_value(env)
                }
            });
            ret
        }
    };

    let stream = quote! {
        #attrs
        #item

        impl JProxy for #name {
            #impl_new
        }

        impl Drop for #name {
            fn drop(&mut self) {
                self.release();
            }
        }
    };

    stream.into()
}

/// 实现java类的字段,将此属性标记在带有get或set的fn函数上,可以自动实现访问java字段的能力,可以自动识别静态字段(如果参数中没有“self”)。
///
/// # Arguments
///
/// * `_`: 未使用。
/// * `input`: 函数输入。
///
/// returns: TokenStream
///
/// # Examples
///
/// ```
/// use droid_wrap_derive::java_field;
///
/// pub struct LayoutParams;
///
/// impl LayoutParams {
///     #[java_field]
///     pub fn get_width(&self) -> i32 {}
///
///     #[java_field]
///     pub fn set_width(&self, value: i32) {}
/// }
/// ```
#[proc_macro_attribute]
pub fn java_field(attrs: TokenStream, input: TokenStream) -> TokenStream {
    let attrs: FieldMetadata = parse2(Into::<TokenStream2>::into(attrs)).unwrap();
    let default_value = attrs.default_value.clone();
    let item = parse_macro_input!(input as ItemFn);
    let attrs = item.attrs.clone();
    let stmts = item.block.stmts.clone();
    let name = item.sig.ident.to_string().to_lower_camel_case();
    let vis = item.vis.clone();
    let sig = item.sig.clone();

    let (is_set, name) = if name.starts_with("get") {
        (false, name.trim_start_matches("get").to_lower_camel_case())
    } else if name.starts_with("set") {
        (true, name.trim_start_matches("set").to_lower_camel_case())
    } else {
        panic!("Field name `{}` must start with get or set.", name);
    };

    let (self_, arg_types, arg_types_sig, _, arg_values, ret_type) =
        parse_function_signature(&sig, &vec![]);
    if is_set {
        if arg_types.len() != 1 {
            panic!(
                "The number of setter arguments for the field `{}` must be one.",
                name
            )
        }
    } else {
        if !arg_types.is_empty() {
            panic!("The getter field `{}` cannot provide any arguments.", name)
        }
    }

    let (ret_value, ret_type_sig, is_result_type) =
        get_return_value_token(&ret_type, &sig.generics, &vec![], &default_value);

    let ret_value = get_result_token(is_result_type, &ret_value);

    let opt = if is_set {
        if self_.is_none() {
            quote! {
                let ret = env.set_static_field(Self::CLASS, #name, #arg_types_sig #arg_values);
            }
        } else {
            quote! {
                let ret = env.set_field(#self_.java_ref(), #name, #arg_types_sig #arg_values);
            }
        }
    } else {
        if self_.is_none() {
            quote! {
                let ret = env.get_static_field(Self::CLASS, #name, #ret_type_sig);
            }
        } else {
            quote! {
                let ret = env.get_field(#self_.java_ref(), #name, #ret_type_sig);
            }
        }
    };
    let stream = quote! {
        #(#attrs)*
        #vis #sig {
            #(#stmts)*
            droid_wrap_utils::vm_attach!(mut env);
            #opt
            #ret_value
        }
    };
    stream.into()
}