flapigen 0.11.0

Tool for connecting libraries written in Rust with other languages
Documentation
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
mod fclass;
mod fenum;
mod find_cache;
mod finterface;
mod java_code;
mod map_class_self_type;
mod map_type;
mod rust_code;

use log::debug;
use proc_macro2::{Span, TokenStream};
use quote::quote;
use rustc_hash::{FxHashMap, FxHashSet};
use smol_str::SmolStr;
use std::{fmt, io::Write, path::PathBuf};
use syn::{spanned::Spanned, Type};

use crate::{
    error::{invalid_src_id_span, DiagnosticError, Result},
    extension::{ClassExtHandlers, ExtHandlers, MethodExtHandlers},
    file_cache::FileWriteCache,
    typemap::{
        ast::{
            check_if_smart_pointer_return_inner_type, if_result_return_ok_err_types,
            if_ty_result_return_ok_type, DisplayToTokens, UniqueName,
        },
        ty::RustType,
        utils::{
            configure_ftype_rule, remove_files_if, validate_cfg_options, ForeignMethodSignature,
            ForeignTypeInfoT,
        },
        ForeignTypeInfo, TypeMapConvRuleInfo,
    },
    types::{ForeignClassInfo, ForeignMethod, ItemToExpand, MethodVariant},
    JavaConfig, JavaReachabilityFence, LanguageGenerator, SourceCode, TypeMap,
    SMART_PTR_COPY_TRAIT, WRITE_TO_MEM_FAILED_MSG,
};
use map_class_self_type::register_typemap_for_self_type;

const INTERNAL_PTR_MARKER: &str = "InternalPointerMarker";
const JAVA_RUST_SELF_NAME: &str = "mNativeObj";
const REACHABILITY_FENCE_CLASS: &str = "JNIReachabilityFence";

struct JavaContext<'a> {
    cfg: &'a JavaConfig,
    conv_map: &'a mut TypeMap,
    pointer_target_width: usize,
    rust_code: &'a mut Vec<TokenStream>,
    generated_foreign_files: &'a mut FxHashSet<PathBuf>,
    java_type_to_jni_sig_map: FxHashMap<SmolStr, SmolStr>,
    class_ext_handlers: &'a ClassExtHandlers,
    method_ext_handlers: &'a MethodExtHandlers,
}

#[derive(Clone, Copy, Debug)]
enum NullAnnotation {
    NonNull,
    Nullable,
}

#[derive(Debug)]
struct JavaForeignTypeInfo {
    pub base: ForeignTypeInfo,
    pub java_converter: Option<JavaConverter>,
    annotation: Option<NullAnnotation>,
}

impl ForeignTypeInfoT for JavaForeignTypeInfo {
    fn corresponding_rust_type(&self) -> &RustType {
        &self.base.corresponding_rust_type
    }
}

#[derive(Debug)]
struct JavaConverter {
    java_transition_type: UniqueName,
    annotation: Option<NullAnnotation>,
    converter: String,
}

impl AsRef<ForeignTypeInfo> for JavaForeignTypeInfo {
    fn as_ref(&self) -> &ForeignTypeInfo {
        &self.base
    }
}

impl From<ForeignTypeInfo> for JavaForeignTypeInfo {
    fn from(x: ForeignTypeInfo) -> Self {
        JavaForeignTypeInfo {
            base: ForeignTypeInfo {
                name: x.name,
                corresponding_rust_type: x.corresponding_rust_type,
            },
            java_converter: None,
            annotation: None,
        }
    }
}

struct JniForeignMethodSignature {
    output: JavaForeignTypeInfo,
    input: Vec<JavaForeignTypeInfo>,
}

impl ForeignMethodSignature for JniForeignMethodSignature {
    type FI = JavaForeignTypeInfo;
    fn input(&self) -> &[JavaForeignTypeInfo] {
        &self.input[..]
    }
}

impl JavaConfig {
    fn register_class(&self, ctx: &mut JavaContext, class: &ForeignClassInfo) -> Result<()> {
        class
            .validate_class()
            .map_err(|err| DiagnosticError::new(class.src_id, class.span(), err))?;
        if let Some(self_desc) = class.self_desc.as_ref() {
            let constructor_ret_type = &self_desc.constructor_ret_type;
            let this_type_for_method = if_ty_result_return_ok_type(constructor_ret_type)
                .unwrap_or_else(|| constructor_ret_type.clone());

            let mut traits = vec!["SwigForeignClass"];
            if class.clone_derived() {
                traits.push("Clone");
            }
            if class.copy_derived() {
                if !class.clone_derived() {
                    traits.push("Clone");
                }
                traits.push("Copy");
            }
            if class.smart_ptr_copy_derived() {
                traits.push(SMART_PTR_COPY_TRAIT);
            }

            let this_type: RustType = ctx.conv_map.find_or_alloc_rust_type_that_implements(
                &this_type_for_method,
                &traits,
                class.src_id,
            );
            if class.smart_ptr_copy_derived() {
                if class.copy_derived() {
                    println!(
                        "cargo:warning=class {} marked as Copy and {}, ignore Copy",
                        class.name, SMART_PTR_COPY_TRAIT
                    );
                }
                if check_if_smart_pointer_return_inner_type(&this_type, "Rc").is_none()
                    && check_if_smart_pointer_return_inner_type(&this_type, "Arc").is_none()
                {
                    return Err(DiagnosticError::new(
                        class.src_id,
                        this_type.ty.span(),
                        format!(
                            "class {} marked as {}, but type '{}' is not Arc<> or Rc<>",
                            class.name, SMART_PTR_COPY_TRAIT, this_type
                        ),
                    ));
                }
            }
            register_typemap_for_self_type(ctx, class, this_type, self_desc)?;
        }

        let _ = ctx
            .conv_map
            .find_or_alloc_rust_type(&class.self_type_as_ty(), class.src_id);

        Ok(())
    }
}

impl LanguageGenerator for JavaConfig {
    fn expand_items(
        &self,
        conv_map: &mut TypeMap,
        pointer_target_width: usize,
        code: &[SourceCode],
        items: Vec<ItemToExpand>,
        remove_not_generated_files: bool,
        ext_handlers: ExtHandlers,
    ) -> Result<Vec<TokenStream>> {
        let mut ret = Vec::with_capacity(items.len());
        let mut generated_foreign_files = FxHashSet::default();
        let mut ctx = JavaContext {
            cfg: self,
            conv_map,
            pointer_target_width,
            rust_code: &mut ret,
            generated_foreign_files: &mut generated_foreign_files,
            java_type_to_jni_sig_map: rust_code::predefined_java_type_to_jni_sig(),
            class_ext_handlers: ext_handlers.class_ext_handlers,
            method_ext_handlers: ext_handlers.method_ext_handlers,
        };
        init(&mut ctx, code)?;
        for item in &items {
            if let ItemToExpand::Class(ref fclass) = item {
                self.register_class(&mut ctx, fclass)?;
            }
        }
        for item in items {
            match item {
                ItemToExpand::Class(fclass) => {
                    fclass::generate(&mut ctx, &fclass)?;
                }
                ItemToExpand::Enum(fenum) => {
                    fenum::generate_enum(&mut ctx, &fenum)?;
                }
                ItemToExpand::Interface(finterface) => {
                    finterface::generate_interface(&mut ctx, &finterface)?;
                }
            }
        }

        if remove_not_generated_files {
            remove_files_if(&self.output_dir, |path| {
                if let Some(ext) = path.extension() {
                    if ext == "java" && !generated_foreign_files.contains(path) {
                        return true;
                    }
                }
                false
            })
            .map_err(DiagnosticError::map_any_err_to_our_err)?;
        }

        Ok(ret)
    }
    fn post_proccess_code(
        &self,
        _conv_map: &mut TypeMap,
        _pointer_target_width: usize,
        mut generated_code: Vec<u8>,
    ) -> Result<Vec<u8>> {
        rust_code::generate_load_unload_jni_funcs(&mut generated_code)?;
        Ok(generated_code)
    }
}

fn method_name(method: &ForeignMethod, f_method: &JniForeignMethodSignature) -> String {
    let need_conv = f_method.input.iter().any(|v: &JavaForeignTypeInfo| {
        v.java_converter
            .as_ref()
            .map(|x| !x.converter.is_empty())
            .unwrap_or(false)
    }) || f_method
        .output
        .java_converter
        .as_ref()
        .map(|x| !x.converter.is_empty())
        .unwrap_or(false);
    match method.variant {
        MethodVariant::StaticMethod if !need_conv => method.short_name().as_str().to_string(),
        MethodVariant::Method(_) | MethodVariant::StaticMethod => {
            format!("do_{}", method.short_name())
        }
        MethodVariant::Constructor => "init".into(),
    }
}

fn java_class_full_name(package_name: &str, class_name: &str) -> String {
    let mut ret: String = package_name.into();
    ret.push('.');
    ret.push_str(class_name);
    ret
}

fn java_class_name_to_jni(full_name: &str) -> String {
    full_name.replace('.', "/")
}

fn calc_this_type_for_method(tm: &TypeMap, class: &ForeignClassInfo) -> Option<Type> {
    class
        .self_desc
        .as_ref()
        .map(|x| &x.constructor_ret_type)
        .map(|constructor_ret_type| {
            Some(
                if_result_return_ok_err_types(
                    &tm.ty_to_rust_type_checked(constructor_ret_type)
                        .unwrap_or_else(|| {
                            panic!(
                                "Internal error: constructor type {} for class {} unknown",
                                DisplayToTokens(constructor_ret_type),
                                class.name
                            );
                        }),
                )
                .map(|(ok_ty, _err_ty)| ok_ty)
                .unwrap_or_else(|| constructor_ret_type.clone()),
            )
        })
        .unwrap_or(None)
}

fn merge_rule(ctx: &mut JavaContext, mut rule: TypeMapConvRuleInfo) -> Result<()> {
    debug!("merge_rule begin {:?}", rule);
    if rule.is_empty() {
        return Err(DiagnosticError::new(
            rule.src_id,
            rule.span,
            format!("rule {rule:?} is empty"),
        ));
    }
    let all_options = {
        let mut opts = FxHashSet::<&'static str>::default();
        opts.insert("NullAnnotations");
        opts.insert("NoNullAnnotations");
        opts
    };
    validate_cfg_options(&rule, &all_options)?;
    let options = {
        let mut opts = FxHashSet::<&'static str>::default();
        if ctx.cfg.null_annotation_package.is_some() {
            opts.insert("NullAnnotations");
        } else {
            opts.insert("NoNullAnnotations");
        }
        opts
    };
    if rule.c_types.is_some() {
        return Err(DiagnosticError::new(
            rule.src_id,
            rule.span,
            "c_types not supported for Java/JNI",
        ));
    }
    if !rule.f_code.is_empty() {
        unimplemented!();
    }
    configure_ftype_rule(&mut rule.ftype_left_to_right, "=>", rule.src_id, &options)?;
    configure_ftype_rule(&mut rule.ftype_right_to_left, "<=", rule.src_id, &options)?;
    ctx.conv_map.merge_conv_rule(rule.src_id, rule)?;
    Ok(())
}

fn init(ctx: &mut JavaContext, _code: &[SourceCode]) -> Result<()> {
    if !(ctx.cfg.output_dir.exists() && ctx.cfg.output_dir.is_dir()) {
        return Err(DiagnosticError::map_any_err_to_our_err(format!(
            "Path {} not exists or not directory",
            ctx.cfg.output_dir.display()
        )));
    }
    ctx.conv_map
        .find_or_alloc_rust_type_no_src_id(&parse_type! { jint });
    ctx.conv_map
        .find_or_alloc_rust_type_no_src_id(&parse_type! { jlong });
    let dummy_rust_ty = ctx
        .conv_map
        .find_or_alloc_rust_type_no_src_id(&parse_type! { () });

    let not_merged_data = ctx.conv_map.take_not_merged_not_generic_rules();
    for rule in not_merged_data {
        merge_rule(ctx, rule)?;
    }
    let src_path = ctx
        .cfg
        .output_dir
        .join(format!("{INTERNAL_PTR_MARKER}.java"));
    let mut src_file = FileWriteCache::new(&src_path, ctx.generated_foreign_files);
    writeln!(
        src_file,
        r#"
// Automatically generated by flapigen
package {package};

/*package*/ enum {enum_name} {{
    RAW_PTR;
}}"#,
        package = ctx.cfg.package_name,
        enum_name = INTERNAL_PTR_MARKER,
    )
    .expect(WRITE_TO_MEM_FAILED_MSG);
    src_file.update_file_if_necessary().map_err(|err| {
        DiagnosticError::new2(
            invalid_src_id_span(),
            format!("write to {} failed: {}", src_path.display(), err),
        )
    })?;
    match ctx.cfg.reachability_fence {
        JavaReachabilityFence::Std => {}
        JavaReachabilityFence::GenerateFence(max_args) => {
            let src_path = ctx
                .cfg
                .output_dir
                .join(format!("{REACHABILITY_FENCE_CLASS}.java"));
            let mut src_file = FileWriteCache::new(&src_path, ctx.generated_foreign_files);
            write!(
                src_file,
                r#"
// Automatically generated by flapigen
package {package};

/*package*/ final class {class_name} {{
    private {class_name}() {{}}"#,
                package = ctx.cfg.package_name,
                class_name = REACHABILITY_FENCE_CLASS,
            )
            .expect(WRITE_TO_MEM_FAILED_MSG);

            let mut f_method = JniForeignMethodSignature {
                output: JavaForeignTypeInfo {
                    base: ForeignTypeInfo {
                        name: "void".into(),
                        corresponding_rust_type: dummy_rust_ty.clone(),
                    },
                    java_converter: None,
                    annotation: None,
                },
                input: vec![],
            };

            let mut jni_args = Vec::with_capacity(max_args);

            for i in 1..=max_args {
                let java_method_name = format!("reachabilityFence{i}");
                write!(
                    src_file,
                    "\n    /*package*/ static native void {java_method_name}(Object ref1"
                )
                .expect(WRITE_TO_MEM_FAILED_MSG);
                for j in 2..=i {
                    write!(src_file, ", Object ref{j}").expect(WRITE_TO_MEM_FAILED_MSG);
                }
                src_file.write_all(b");").expect(WRITE_TO_MEM_FAILED_MSG);

                f_method.input.push(JavaForeignTypeInfo {
                    base: ForeignTypeInfo {
                        name: "Object".into(),
                        corresponding_rust_type: dummy_rust_ty.clone(),
                    },
                    java_converter: None,
                    annotation: None,
                });
                let jni_func_name = rust_code::generate_jni_func_name(
                    ctx,
                    REACHABILITY_FENCE_CLASS,
                    invalid_src_id_span(),
                    &java_method_name,
                    MethodVariant::StaticMethod,
                    &f_method,
                    false,
                )?;
                let jni_func_name = syn::Ident::new(&jni_func_name, Span::call_site());
                jni_args.push(quote!(_: jobject));
                let jni_args = &jni_args;
                ctx.rust_code.push(quote! {
                    #[allow(unused_variables, unused_mut, non_snake_case, unused_unsafe)]
                    #[unsafe(no_mangle)]
                    pub extern "C" fn #jni_func_name(_env: *mut JNIEnv, _: jclass, #(#jni_args),*) {
                    }
                });
            }
            src_file.write_all(b"}\n").expect(WRITE_TO_MEM_FAILED_MSG);

            src_file.update_file_if_necessary().map_err(|err| {
                DiagnosticError::new2(
                    invalid_src_id_span(),
                    format!("write to {} failed: {}", src_path.display(), err),
                )
            })?;
        }
    }
    Ok(())
}

fn map_write_err<Err: fmt::Display>(err: Err) -> String {
    format!("write failed: {err}")
}