alef 0.67.4

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
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
//! Kotlin/Native binding generator — Phase 3.
//!
//! Emits Kotlin/Native source that calls into the cbindgen-produced C FFI library
//! via `kotlinx.cinterop.*`. The consumer pattern mirrors the Go and Zig backends:
//! use `config.ffi_prefix()`, `config.ffi_header_name()`, and `config.ffi_lib_name()`
//! as the single source of truth for symbol names and linking directives.

mod cinterop_def;
mod native_build_gradle;
mod native_types;

use crate::codegen::c_consumer;
use crate::core::backend::GeneratedFile;
use crate::core::config::ResolvedCrateConfig;
use crate::core::ir::{ApiSurface, FunctionDef, ParamDef, TypeRef};
use std::collections::BTreeSet;
use std::path::PathBuf;

use crate::backends::kotlin::gen_bindings::{to_lower_camel, to_pascal_case};

/// Emit all Kotlin/Native files for the given API surface.
///
/// Returns three generated files:
/// 1. `packages/kotlin-native/src/nativeMain/kotlin/<package>/<Module>.kt`
/// 2. `packages/kotlin-native/<crate>.def`
/// 3. `packages/kotlin-native/build.gradle.kts`
pub fn emit(api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
    let kt = emit_kotlin_source(api, config);
    let def = cinterop_def::emit_def_file(config);
    let gradle = native_build_gradle::emit_gradle_build(config);

    let package = config.kotlin_package();
    let package_path = package.replace('.', "/");
    let module_name = to_pascal_case(&config.name);
    let crate_name = &config.name;

    let native_root = "packages/kotlin-native".to_string();

    let kt_path = PathBuf::from(&native_root)
        .join("src/nativeMain/kotlin")
        .join(&package_path)
        .join(format!("{module_name}.kt"));

    let def_path = PathBuf::from(&native_root).join(format!("{crate_name}.def"));
    let gradle_path = PathBuf::from(&native_root).join("build.gradle.kts");

    Ok(vec![
        GeneratedFile {
            path: kt_path,
            content: kt,
            generated_header: false,
        },
        GeneratedFile {
            path: def_path,
            content: def,
            generated_header: false,
        },
        GeneratedFile {
            path: gradle_path,
            content: gradle,
            generated_header: false,
        },
    ])
}

fn emit_kotlin_source(api: &ApiSurface, config: &ResolvedCrateConfig) -> String {
    let package = config.kotlin_package();
    let module_name = to_pascal_case(&config.name);
    let prefix = config.ffi_prefix();
    let crate_name = &config.name;

    let exclude_functions: std::collections::HashSet<&str> = config
        .kotlin
        .as_ref()
        .map(|c| c.exclude_functions.iter().map(String::as_str).collect())
        .unwrap_or_default();
    let exclude_types: std::collections::HashSet<&str> = config
        .kotlin
        .as_ref()
        .map(|c| c.exclude_types.iter().map(String::as_str).collect())
        .unwrap_or_default();

    let mut imports: BTreeSet<String> = BTreeSet::new();
    imports.insert("import kotlinx.cinterop.*".to_string());
    imports.insert(format!("import {crate_name}.*"));

    let mut body = String::new();

    for ty in api.types.iter().filter(|t| !exclude_types.contains(t.name.as_str())) {
        native_types::emit_native_type(ty, &mut body);
        body.push('\n');
    }

    for en in api.enums.iter().filter(|e| !exclude_types.contains(e.name.as_str())) {
        native_types::emit_native_enum(en, &mut body);
        body.push('\n');
    }

    for error in &api.errors {
        native_types::emit_native_error(error, &mut body);
        body.push('\n');
    }

    let visible_functions: Vec<&crate::core::ir::FunctionDef> = api
        .functions
        .iter()
        .filter(|f| !exclude_functions.contains(f.name.as_str()))
        .collect();

    if !visible_functions.is_empty() {
        body.push_str(&crate::backends::kotlin::template_env::render(
            "object_declaration.jinja",
            minijinja::context! {
                name => module_name,
            },
        ));
        for f in &visible_functions {
            emit_native_function(f, &prefix, &api.errors, &api.error_taxonomy(), &mut body);
            body.push('\n');
        }
        body.push_str("}\n");
    }

    let mut content = String::new();
    content.push_str(crate::core::hash::SELF_MARKING_HEADER_LINE);
    content.push_str("\n\n");
    content.push_str(&crate::backends::kotlin::template_env::render(
        "package_declaration.jinja",
        minijinja::context! {
            package => package,
        },
    ));
    content.push_str("\n\n");
    for import in &imports {
        content.push_str(import);
        content.push('\n');
    }
    content.push('\n');
    content.push_str(&body);
    content
}

/// Emit a Kotlin/Native function body — exposed for `gen_mpp` to reuse.
pub(crate) fn emit_native_function_pub(
    f: &FunctionDef,
    prefix: &str,
    errors: &[crate::core::ir::ErrorDef],
    taxonomy: &[crate::core::ir::ErrorTaxonomy],
    out: &mut String,
) {
    emit_native_function(f, prefix, errors, taxonomy, out)
}

fn emit_native_function(
    f: &FunctionDef,
    prefix: &str,
    errors: &[crate::core::ir::ErrorDef],
    taxonomy: &[crate::core::ir::ErrorTaxonomy],
    out: &mut String,
) {
    if !f.doc.is_empty() {
        let doc_lines: Vec<String> = f.doc.lines().map(ToString::to_string).collect();
        out.push_str(&crate::backends::kotlin::template_env::render(
            "doc_comment.jinja",
            minijinja::context! {
                indent => "    ",
                lines => doc_lines,
            },
        ));
    }

    let params: Vec<String> = f.params.iter().map(format_native_param).collect();
    let return_ty = native_return_type_str(&f.return_type);
    let func_name_camel = to_lower_camel(&f.name);

    let error_code_sym = c_consumer::last_error_code_symbol(prefix);
    let error_context_sym = c_consumer::last_error_context_symbol(prefix);
    let free_sym = c_consumer::free_string_symbol(prefix);
    let c_fn = format!("{prefix}_{}", f.name);

    out.push_str(&crate::backends::kotlin::template_env::render(
        "native_function_header.jinja",
        minijinja::context! {
            name => func_name_camel,
            params => params.join(", "),
            return_type => return_ty,
        },
    ));
    out.push_str("        return memScoped {\n");

    for p in &f.params {
        emit_native_param_conversion(p, out);
    }

    let c_args: Vec<String> = f.params.iter().map(native_c_arg).collect();
    let call = format!("{c_fn}({})", c_args.join(", "));

    if f.error_type.is_some() {
        out.push_str(&crate::backends::kotlin::template_env::render(
            "native_result_assign.jinja",
            minijinja::context! {
                call => call,
            },
        ));
        out.push_str(&crate::backends::kotlin::template_env::render(
            "native_error_code_check.jinja",
            minijinja::context! {
                error_code_sym => error_code_sym,
            },
        ));
        out.push_str("            if (_code != 0) {\n");
        out.push_str(&crate::backends::kotlin::template_env::render(
            "native_error_message.jinja",
            minijinja::context! {
                error_context_sym => error_context_sym,
            },
        ));
        if let Some(error_type) = f.error_type.as_deref()
            && let Some(error) = errors
                .iter()
                .find(|error| error.name == error_type.rsplit("::").next().unwrap_or(error_type))
        {
            for variant in error.variants.iter().filter(|variant| variant.is_unit) {
                let Some(metadata) = taxonomy
                    .iter()
                    .find(|entry| entry.error_type == error.rust_path && entry.variant == variant.name)
                else {
                    continue;
                };
                out.push_str(&format!(
                    "                if (_code == {}) throw {}.{}\n",
                    metadata.code, error.name, variant.name
                ));
            }
        }
        out.push_str("                throw RuntimeException(\"[${_code}] ${_msg}\")\n");
        out.push_str("            }\n");
        if matches!(f.return_type, TypeRef::Unit) {
            out.push_str("            Unit\n");
        } else {
            let expr = native_unwrap_return("_result", &f.return_type, &free_sym);
            out.push_str(&crate::backends::kotlin::template_env::render(
                "native_return_expr.jinja",
                minijinja::context! {
                    expr => expr,
                },
            ));
        }
    } else if matches!(f.return_type, TypeRef::Unit) {
        out.push_str(&crate::backends::kotlin::template_env::render(
            "native_call_only.jinja",
            minijinja::context! {
                call => call,
            },
        ));
        out.push_str("            Unit\n");
    } else {
        out.push_str(&crate::backends::kotlin::template_env::render(
            "native_result_assign.jinja",
            minijinja::context! {
                call => call,
            },
        ));
        let expr = native_unwrap_return("_result", &f.return_type, &free_sym);
        out.push_str(&crate::backends::kotlin::template_env::render(
            "native_return_expr.jinja",
            minijinja::context! {
                expr => expr,
            },
        ));
    }

    out.push_str("        }\n");
    out.push_str("    }\n");
}

fn format_native_param(p: &ParamDef) -> String {
    let ty_str = native_param_type_str(&p.ty, p.optional);
    format!("{}: {}", to_lower_camel(&p.name), ty_str)
}

/// The Kotlin/Native type used at the wrapper boundary for a function parameter.
///
/// `String`, `Path`, `Bytes`, `Vec`, `Map` → `String` (caller supplies value;
/// String/Path are converted to `cstr`, Bytes/Vec/Map are passed as JSON strings).
fn native_param_type_str(ty: &TypeRef, optional: bool) -> String {
    let inner = match ty {
        TypeRef::String | TypeRef::Path | TypeRef::Char | TypeRef::Json | TypeRef::Vec(_) | TypeRef::Map(_, _) => {
            "String".to_string()
        }
        TypeRef::Bytes => "ByteArray".to_string(),
        TypeRef::Optional(inner) => return format!("{}?", native_param_type_str(inner, false)),
        other => native_type_str(other, false),
    };
    if optional { format!("{inner}?") } else { inner }
}

/// Emit the `memScoped`-local conversion for a parameter before the C call.
fn emit_native_param_conversion(p: &ParamDef, out: &mut String) {
    let name = to_lower_camel(&p.name);
    match &p.ty {
        TypeRef::String | TypeRef::Path | TypeRef::Char | TypeRef::Json | TypeRef::Vec(_) | TypeRef::Map(_, _) => {
            out.push_str(&crate::backends::kotlin::template_env::render(
                "native_param_cstr_conversion.jinja",
                minijinja::context! {
                    name => &name,
                },
            ));
        }
        TypeRef::Bytes => {
            out.push_str(&crate::backends::kotlin::template_env::render(
                "native_param_bytes_conversion.jinja",
                minijinja::context! {
                    name => &name,
                },
            ));
        }
        _ => {}
    }
}

/// The C argument expression for a parameter.
fn native_c_arg(p: &ParamDef) -> String {
    let name = to_lower_camel(&p.name);
    match &p.ty {
        TypeRef::String | TypeRef::Path | TypeRef::Char | TypeRef::Json | TypeRef::Vec(_) | TypeRef::Map(_, _) => {
            format!("{name}C")
        }
        TypeRef::Bytes => format!("{name}Pin.addressOf(0), {name}.size"),
        _ => name,
    }
}

/// Produce the Kotlin expression that converts a raw C return value to the
/// Kotlin return type.
///
/// String-like returns: copy via `toKString()` then free the C allocation.
/// Everything else: pass through unchanged.
fn native_unwrap_return(raw: &str, ty: &TypeRef, free_sym: &str) -> String {
    match ty {
        TypeRef::String | TypeRef::Path | TypeRef::Char | TypeRef::Json | TypeRef::Vec(_) | TypeRef::Map(_, _) => {
            format!("run {{ val _s = {raw}!!.toKString(); {free_sym}({raw}); _s }}")
        }
        TypeRef::Bytes => {
            format!("run {{ val _s = {raw}!!.toKString().encodeToByteArray(); {free_sym}({raw}); _s }}")
        }
        _ => raw.to_string(),
    }
}

/// Kotlin/Native return type for a function (not for struct fields).
fn native_return_type_str(ty: &TypeRef) -> String {
    match ty {
        TypeRef::Unit => "Unit".to_string(),
        TypeRef::String | TypeRef::Path | TypeRef::Char | TypeRef::Json | TypeRef::Vec(_) | TypeRef::Map(_, _) => {
            "String".to_string()
        }
        TypeRef::Bytes => "ByteArray".to_string(),
        other => native_type_str(other, false),
    }
}

/// Kotlin/Native type for struct fields (same as JVM type; cinterop types are
/// used only inside function bodies, not in data class declarations).
pub(crate) fn native_type_str(ty: &TypeRef, optional: bool) -> String {
    use crate::core::ir::PrimitiveType;
    let inner = match ty {
        TypeRef::Primitive(p) => match p {
            PrimitiveType::Bool => "Boolean".to_string(),
            PrimitiveType::U8 | PrimitiveType::I8 => "Byte".to_string(),
            PrimitiveType::U16 | PrimitiveType::I16 => "Short".to_string(),
            PrimitiveType::U32 | PrimitiveType::I32 => "Int".to_string(),
            PrimitiveType::U64 | PrimitiveType::I64 | PrimitiveType::Usize | PrimitiveType::Isize => "Long".to_string(),
            PrimitiveType::F32 => "Float".to_string(),
            PrimitiveType::F64 => "Double".to_string(),
        },
        TypeRef::String | TypeRef::Json => "String".to_string(),
        TypeRef::Path => "String".to_string(),
        TypeRef::Char => "Char".to_string(),
        TypeRef::Bytes => "ByteArray".to_string(),
        TypeRef::Unit => "Unit".to_string(),
        TypeRef::Duration => "Long".to_string(),
        TypeRef::Named(name) => name.clone(),
        TypeRef::Optional(inner) => return format!("{}?", native_type_str(inner, false)),
        TypeRef::Vec(inner) => format!("List<{}>", native_type_str(inner, false)),
        TypeRef::Map(k, v) => format!("Map<{}, {}>", native_type_str(k, false), native_type_str(v, false)),
    };
    if optional { format!("{inner}?") } else { inner }
}

#[cfg(test)]
mod typed_error_tests {
    use super::*;

    #[test]
    fn native_function_maps_taxonomy_code_to_unit_variant() {
        let error = crate::core::ir::ErrorDef {
            name: "RequestError".to_string(),
            rust_path: "sample::RequestError".to_string(),
            variants: vec![crate::core::ir::ErrorVariant {
                error_code: Some(100),
                name: "InvalidInput".to_string(),
                is_unit: true,
                ..Default::default()
            }],
            original_rust_path: String::new(),
            doc: String::new(),
            methods: Vec::new(),
            binding_excluded: false,
            binding_exclusion_reason: None,
            version: Default::default(),
        };
        let function = FunctionDef {
            name: "execute".to_string(),
            rust_path: "sample::execute".to_string(),
            return_type: TypeRef::Unit,
            error_type: Some("RequestError".to_string()),
            ..Default::default()
        };
        let taxonomy = error.variants[0]
            .taxonomy(&error.rust_path)
            .expect("explicit test error code");
        let mut output = String::new();

        emit_native_function(
            &function,
            "sample",
            std::slice::from_ref(&error),
            std::slice::from_ref(&taxonomy),
            &mut output,
        );

        assert!(output.contains(&format!(
            "if (_code == {}) throw RequestError.InvalidInput",
            taxonomy.code
        )));
        assert!(output.contains("throw RuntimeException(\"[${_code}] ${_msg}\")"));
    }

    #[test]
    fn native_function_uses_generic_fallback_for_unnumbered_variant() {
        let error = crate::core::ir::ErrorDef {
            name: "RequestError".to_string(),
            rust_path: "sample::RequestError".to_string(),
            variants: vec![crate::core::ir::ErrorVariant {
                name: "InvalidInput".to_string(),
                is_unit: true,
                ..Default::default()
            }],
            original_rust_path: String::new(),
            doc: String::new(),
            methods: Vec::new(),
            binding_excluded: false,
            binding_exclusion_reason: None,
            version: Default::default(),
        };
        let function = FunctionDef {
            name: "execute".to_string(),
            rust_path: "sample::execute".to_string(),
            return_type: TypeRef::Unit,
            error_type: Some("RequestError".to_string()),
            ..Default::default()
        };
        let mut output = String::new();

        emit_native_function(&function, "sample", std::slice::from_ref(&error), &[], &mut output);

        assert!(!output.contains("throw RequestError.InvalidInput"));
        assert!(output.contains("throw RuntimeException(\"[${_code}] ${_msg}\")"));
    }
}