alef 0.48.15

Opinionated polyglot binding generator for Rust libraries
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
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn jni_return_type_unit() {
        assert_eq!(jni_return_type(&TypeRef::Unit), "()");
    }

    #[test]
    fn jni_return_type_i64() {
        assert_eq!(jni_return_type(&TypeRef::Primitive(PrimitiveType::I64)), "jlong");
    }

    #[test]
    fn jni_return_type_string() {
        assert_eq!(jni_return_type(&TypeRef::String), "jstring");
    }

    #[test]
    fn jni_return_type_vec_u8() {
        assert_eq!(
            jni_return_type(&TypeRef::Vec(Box::new(TypeRef::Primitive(PrimitiveType::U8)))),
            "jbyteArray"
        );
    }

    #[test]
    fn type_ref_to_core_path_uses_btree_for_btree_map() {
        let map = TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::String));
        assert_eq!(
            type_ref_to_core_path_with_btree(&map, "core_crate", true),
            "std::collections::BTreeMap<String, String>"
        );
        assert_eq!(
            type_ref_to_core_path_with_btree(&map, "core_crate", false),
            "std::collections::HashMap<String, String>"
        );
    }

    #[test]
    fn bytes_call_arg_optional_ref_uses_as_deref() {
        assert_eq!(
            bytes_call_arg("document_bytes", true, true),
            "document_bytes.as_deref()"
        );
        assert_eq!(bytes_call_arg("document_bytes", true, false), "document_bytes");
        assert_eq!(bytes_call_arg("document_bytes", false, true), "&document_bytes");
        assert_eq!(bytes_call_arg("document_bytes", false, false), "document_bytes");
    }

    fn btree_fixture_config() -> crate::core::config::ResolvedCrateConfig {
        use crate::core::config::NewAlefConfig;
        let raw: NewAlefConfig = toml::from_str(
            r#"
[workspace]
languages = ["kotlin_android", "jni"]

[[crates]]
name = "demo"
sources = ["src/lib.rs"]

[crates.kotlin_android]
package = "dev.sample_crate"
namespace = "dev.sample_crate"
"#,
        )
        .unwrap();
        raw.resolve().unwrap().remove(0)
    }

    fn api_with_functions(functions: Vec<crate::core::ir::FunctionDef>) -> crate::core::ir::ApiSurface {
        crate::core::ir::ApiSurface {
            crate_name: "demo".into(),
            version: "0.1.0".into(),
            types: vec![],
            functions,
            enums: vec![],
            errors: vec![],
            excluded_type_paths: Default::default(),
            excluded_trait_names: ::std::collections::HashSet::new(),
            services: vec![],
            handler_contracts: vec![],
            unsupported_public_items: Vec::new(),
        }
    }

    /// `analyze_document(..., document_bytes: Option<&[u8]>)` must pass
    /// `document_bytes.as_deref()` (Option<Vec<u8>> -> Option<&[u8]>), not the owned
    /// `Option<Vec<u8>>` which fails with E0308.
    #[test]
    fn optional_byte_slice_param_uses_as_deref_at_call_site() {
        let func = crate::core::ir::FunctionDef {
            name: "analyze_document".into(),
            rust_path: "demo::analyze_document".into(),
            params: vec![crate::core::ir::ParamDef {
                name: "document_bytes".into(),
                ty: TypeRef::Bytes,
                optional: true,
                is_ref: true,
                ..Default::default()
            }],
            return_type: TypeRef::String,
            error_type: Some("DemoError".into()),
            ..Default::default()
        };
        let content = emit_lib_rs(&api_with_functions(vec![func]), &btree_fixture_config());
        assert!(
            content.contains("document_bytes.as_deref()"),
            "optional &[u8] param must be passed via .as_deref(): {content}"
        );
        assert!(
            content.contains("core_crate::analyze_document(document_bytes.as_deref())"),
            "call site must pass document_bytes.as_deref(): {content}"
        );
    }

    /// `resolve(..., context: &BTreeMap<String, String>)` must deserialize into a
    /// `BTreeMap` (not `HashMap`) so the `&context` argument matches the core's
    /// `&BTreeMap<String, String>` slot (E0308 otherwise).
    #[test]
    fn btree_map_param_deserializes_into_btreemap() {
        let func = crate::core::ir::FunctionDef {
            name: "resolve".into(),
            rust_path: "demo::resolve".into(),
            params: vec![crate::core::ir::ParamDef {
                name: "context".into(),
                ty: TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::String)),
                optional: false,
                is_ref: true,
                map_is_btree: true,
                ..Default::default()
            }],
            return_type: TypeRef::String,
            error_type: Some("DemoError".into()),
            ..Default::default()
        };
        let content = emit_lib_rs(&api_with_functions(vec![func]), &btree_fixture_config());
        assert!(
            content.contains("let context: std::collections::BTreeMap<String, String>"),
            "BTreeMap param must deserialize into BTreeMap: {content}"
        );
        assert!(
            !content.contains("let context: std::collections::HashMap<String, String>"),
            "BTreeMap param must NOT deserialize into HashMap: {content}"
        );
        assert!(
            content.contains("core_crate::resolve(&context)"),
            "call site must pass &context: {content}"
        );
    }

    /// A free function resolved into a *sibling* workspace crate (rust_path
    /// `<sibling_crate>::<fn>`, where the sibling crate is not the umbrella crate)
    /// must be reached through the umbrella facade by item path
    /// (`core_crate::<fn>`), mirroring how opaque types are referenced. Prefixing
    /// the origin crate — `core_crate::<sibling_crate>::<fn>` — does not resolve
    /// (E0433: cannot find `<sibling_crate>` in `core_crate`).
    #[test]
    fn sibling_crate_function_is_reached_through_umbrella_facade() {
        let func = crate::core::ir::FunctionDef {
            name: "schema_query_only".into(),
            rust_path: "demo_graphql::schema_query_only".into(),
            params: vec![],
            return_type: TypeRef::String,
            error_type: None,
            ..Default::default()
        };
        let content = emit_lib_rs(&api_with_functions(vec![func]), &btree_fixture_config());
        assert!(
            content.contains("core_crate::schema_query_only("),
            "sibling-crate fn must be called as core_crate::schema_query_only(): {content}"
        );
        assert!(
            !content.contains("core_crate::demo_graphql::"),
            "sibling-crate fn must NOT be prefixed with the origin crate: {content}"
        );
    }

    /// The generated `throw_jni_error` helper must use `env.throw_new(...).is_err()`
    /// and fall back to `java/lang/RuntimeException` rather than silently discarding
    /// a failed throw (which would leave the Kotlin caller with no exception pending
    /// and a null/zero sentinel that looks like a valid return value).
    #[test]
    fn throw_jni_error_has_runtime_exception_fallback() {
        use crate::core::config::NewAlefConfig;
        let raw: NewAlefConfig = toml::from_str(
            r#"
[workspace]
languages = ["kotlin_android", "jni"]

[[crates]]
name = "demo"
sources = ["src/lib.rs"]

[crates.kotlin_android]
package = "dev.sample_crate"
namespace = "dev.sample_crate"
"#,
        )
        .unwrap();
        let config = raw.resolve().unwrap().remove(0);
        let api = crate::core::ir::ApiSurface {
            crate_name: "demo".into(),
            version: "0.1.0".into(),
            types: vec![],
            functions: vec![],
            enums: vec![],
            errors: vec![],
            excluded_type_paths: Default::default(),
            excluded_trait_names: ::std::collections::HashSet::new(),
            services: vec![],
            handler_contracts: vec![],
            unsupported_public_items: Vec::new(),
        };
        let content = emit_lib_rs(&api, &config);
        assert!(
            !content.contains("let _ = env.throw_new(ERROR_CLASS"),
            "throw_jni_error must not discard the throw_new result: {content}"
        );
        assert!(
            content.contains("if env.throw_new(&class_jni, &msg_jni).is_err()"),
            "throw_jni_error must check throw_new result: {content}"
        );
        assert!(
            content.contains("jni::strings::JNIString::from(ERROR_CLASS)"),
            "throw_jni_error must wrap ERROR_CLASS in JNIString::from: {content}"
        );
        assert!(
            content.contains("java/lang/RuntimeException"),
            "throw_jni_error must fall back to RuntimeException: {content}"
        );
    }

    /// Build an `ApiSurface` whose single opaque client type carries `methods`,
    /// so `emit_lib_rs` routes them through `emit_method_shim` (the request-map
    /// multi-param path) rather than the per-param free-function path.
    fn api_with_client_methods(methods: Vec<crate::core::ir::MethodDef>) -> crate::core::ir::ApiSurface {
        let client = crate::core::ir::TypeDef {
            name: "Loader".into(),
            rust_path: "demo::Loader".into(),
            is_opaque: true,
            methods,
            ..Default::default()
        };
        crate::core::ir::ApiSurface {
            crate_name: "demo".into(),
            version: "0.1.0".into(),
            types: vec![client],
            functions: vec![],
            enums: vec![],
            errors: vec![],
            excluded_type_paths: Default::default(),
            excluded_trait_names: ::std::collections::HashSet::new(),
            services: vec![],
            handler_contracts: vec![],
            unsupported_public_items: Vec::new(),
        }
    }

    /// Multi-param method `parse_preset(path: &str, raw: &[u8])` is decoded from the
    /// request map. The `&[u8]` param must bind `let raw: Vec<u8>` (not the generic
    /// `serde_json::Value` catch-all) and be passed as `&raw` so `&Vec<u8>` derefs to
    /// `&[u8]` (E0308 otherwise: `expected &[u8], found &Value`).
    #[test]
    fn request_map_byte_slice_param_binds_vec_u8_not_json_value() {
        let method = crate::core::ir::MethodDef {
            name: "parse_preset".into(),
            params: vec![
                crate::core::ir::ParamDef {
                    name: "path".into(),
                    ty: TypeRef::String,
                    is_ref: true,
                    ..Default::default()
                },
                crate::core::ir::ParamDef {
                    name: "raw".into(),
                    ty: TypeRef::Bytes,
                    is_ref: true,
                    ..Default::default()
                },
            ],
            return_type: TypeRef::Named("Preset".into()),
            error_type: Some("LoadError".into()),
            receiver: Some(crate::core::ir::ReceiverKind::Ref),
            ..Default::default()
        };
        let content = emit_lib_rs(&api_with_client_methods(vec![method]), &btree_fixture_config());
        assert!(
            content.contains("let raw: Vec<u8> = match req_map.get(\"raw\")"),
            "request-map &[u8] param must bind Vec<u8>: {content}"
        );
        assert!(
            !content.contains("let raw: serde_json::Value"),
            "request-map &[u8] param must NOT bind serde_json::Value: {content}"
        );
        assert!(
            content.contains("client.parse_preset(&path, &raw)"),
            "call site must pass &path and &raw: {content}"
        );
    }

    /// Multi-param method `load_at(path: &Path, raw: &[u8])`: a `&Path` param in the
    /// request-map path must deserialize as `String` then convert to `PathBuf` (so
    /// `&path` derefs `&PathBuf` → `&Path`), never bind the `serde_json::Value`
    /// catch-all (E0277: `Value` does not impl `AsRef<Path>`).
    #[test]
    fn request_map_path_param_binds_pathbuf_not_json_value() {
        let method = crate::core::ir::MethodDef {
            name: "load_at".into(),
            params: vec![
                crate::core::ir::ParamDef {
                    name: "path".into(),
                    ty: TypeRef::Path,
                    is_ref: true,
                    ..Default::default()
                },
                crate::core::ir::ParamDef {
                    name: "raw".into(),
                    ty: TypeRef::Bytes,
                    is_ref: true,
                    ..Default::default()
                },
            ],
            return_type: TypeRef::Named("Preset".into()),
            error_type: Some("LoadError".into()),
            receiver: Some(crate::core::ir::ReceiverKind::Ref),
            ..Default::default()
        };
        let content = emit_lib_rs(&api_with_client_methods(vec![method]), &btree_fixture_config());
        assert!(
            content.contains("let path = std::path::PathBuf::from(path);"),
            "request-map &Path param must convert to PathBuf: {content}"
        );
        assert!(
            !content.contains("let path: serde_json::Value"),
            "request-map &Path param must NOT bind serde_json::Value: {content}"
        );
        assert!(
            content.contains("client.load_at(&path, &raw)"),
            "call site must pass &path and &raw: {content}"
        );
    }

    /// A client type listed in `[crates.kotlin_android].exclude_types` (or the shared
    /// `[crates.ffi].exclude_types`) must not have any JNI shims emitted. The
    /// kotlin_android binding backend already drops the Kotlin class via
    /// `effective_exclude_types`; without the matching filter here the JNI side emits
    /// orphan `#[no_mangle]` shims and re-exposes a type every other FFI-derived
    /// binding hides (e.g. the test-only client). The exclusion must be *targeted*:
    /// a sibling client that is not excluded keeps its shims.
    #[test]
    fn excluded_client_type_emits_no_shims_but_keeps_others() {
        use crate::core::config::NewAlefConfig;
        let raw: NewAlefConfig = toml::from_str(
            r#"
[workspace]
languages = ["kotlin_android", "jni"]

[[crates]]
name = "demo"
sources = ["src/lib.rs"]

[crates.kotlin_android]
package = "dev.sample_crate"
namespace = "dev.sample_crate"
exclude_types = ["Loader"]
"#,
        )
        .unwrap();
        let config = raw.resolve().unwrap().remove(0);
        let method = |name: &str| crate::core::ir::MethodDef {
            name: name.into(),
            params: vec![crate::core::ir::ParamDef {
                name: "path".into(),
                ty: TypeRef::String,
                is_ref: true,
                ..Default::default()
            }],
            return_type: TypeRef::String,
            error_type: Some("LoadError".into()),
            receiver: Some(crate::core::ir::ReceiverKind::Ref),
            ..Default::default()
        };
        let client = |name: &str, m: crate::core::ir::MethodDef| crate::core::ir::TypeDef {
            name: name.into(),
            rust_path: format!("demo::{name}"),
            is_opaque: true,
            methods: vec![m],
            ..Default::default()
        };
        let api = crate::core::ir::ApiSurface {
            crate_name: "demo".into(),
            version: "0.1.0".into(),
            types: vec![
                client("Loader", method("excluded_call")),
                client("Keeper", method("kept_call")),
            ],
            functions: vec![],
            enums: vec![],
            errors: vec![],
            excluded_type_paths: Default::default(),
            excluded_trait_names: ::std::collections::HashSet::new(),
            services: vec![],
            handler_contracts: vec![],
            unsupported_public_items: Vec::new(),
        };
        let content = emit_lib_rs(&api, &config);
        assert!(
            !content.contains("excluded_call"),
            "excluded client type must not emit method shims: {content}"
        );
        assert!(
            !content.contains("FreeLoader") && !content.contains("nativeFreeLoader"),
            "excluded client type must not emit a destructor shim: {content}"
        );
        assert!(
            content.contains("client.kept_call"),
            "a non-excluded sibling client must keep its shims: {content}"
        );
    }
}