alef-backend-kotlin 0.17.35

Kotlin (JVM) backend for alef
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
//! Kotlin Multiplatform (KMP) binding generator — Phase 3.
//!
//! Emits a KMP project layout under `packages/kotlin-mpp/`:
//!
//! - `src/commonMain/kotlin/<package>/<Module>.kt`  — shared DTOs + `expect object` declarations
//! - `src/jvmMain/kotlin/<package>/<Module>.kt`     — `actual object` delegating to the JVM facade
//! - `src/nativeMain/kotlin/<package>/<Module>.kt`  — `actual object` using `kotlinx.cinterop.*`
//! - `<crate>.def`                                  — cinterop definition (same as Native target)
//! - `build.gradle.kts`                             — KMP project build script

use alef_core::backend::GeneratedFile;
use alef_core::config::ResolvedCrateConfig;
use alef_core::ir::{ApiSurface, FunctionDef};
use alef_core::template_versions;
use std::collections::BTreeSet;
use std::path::PathBuf;

use crate::gen_bindings::{
    emit_enum_pub, emit_error_type_pub, emit_function_jvm, emit_type_pub, format_param_pub, kotlin_type_str_pub,
    to_lower_camel, to_pascal_case,
};
use crate::gen_native::emit_native_function_pub;

const BRIDGE_ALIAS: &str = "Bridge";

/// Emit all Kotlin Multiplatform files for the given API surface.
///
/// Returns five generated files:
/// 1. `packages/kotlin-mpp/src/commonMain/kotlin/<package>/<Module>.kt`
/// 2. `packages/kotlin-mpp/src/jvmMain/kotlin/<package>/<Module>.kt`
/// 3. `packages/kotlin-mpp/src/nativeMain/kotlin/<package>/<Module>.kt`
/// 4. `packages/kotlin-mpp/<crate>.def`
/// 5. `packages/kotlin-mpp/build.gradle.kts`
pub fn emit(api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
    let package = config.kotlin_package();
    let package_path = package.replace('.', "/");
    let module_name = to_pascal_case(&config.name);
    let crate_name = &config.name;

    let mpp_root = "packages/kotlin-mpp".to_string();

    let common_kt_path = PathBuf::from(&mpp_root)
        .join("src/commonMain/kotlin")
        .join(&package_path)
        .join(format!("{module_name}.kt"));

    let jvm_kt_path = PathBuf::from(&mpp_root)
        .join("src/jvmMain/kotlin")
        .join(&package_path)
        .join(format!("{module_name}.kt"));

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

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

    Ok(vec![
        GeneratedFile {
            path: common_kt_path,
            content: emit_common(api, config),
            generated_header: false,
        },
        GeneratedFile {
            path: jvm_kt_path,
            content: emit_jvm_actual(api, config),
            generated_header: false,
        },
        GeneratedFile {
            path: native_kt_path,
            content: emit_native_actual(api, config),
            generated_header: false,
        },
        GeneratedFile {
            path: def_path,
            content: emit_def_file(config),
            generated_header: false,
        },
        GeneratedFile {
            path: gradle_path,
            content: emit_gradle_build(config),
            generated_header: false,
        },
    ])
}

// ---------------------------------------------------------------------------
// commonMain — shared DTOs + expect object declarations
// ---------------------------------------------------------------------------

fn emit_common(api: &ApiSurface, config: &ResolvedCrateConfig) -> String {
    let package = config.kotlin_package();
    let module_name = to_pascal_case(&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();
    let mut body = String::new();

    // DTOs (data classes), enums, and error hierarchies are pure Kotlin — shared in commonMain.
    for ty in api.types.iter().filter(|t| !exclude_types.contains(t.name.as_str())) {
        emit_type_pub(ty, &mut body, &mut imports);
        body.push('\n');
    }

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

    for error in &api.errors {
        emit_error_type_pub(error, &mut body, &mut imports);
        body.push('\n');
    }

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

    // Functions: emit `expect object` with only signatures (no bodies).
    if !visible_functions.is_empty() {
        body.push_str(&crate::template_env::render(
            "expect_object_declaration.jinja",
            minijinja::context! {
                name => module_name,
            },
        ));
        for f in &visible_functions {
            emit_expect_function(f, &mut body, &mut imports);
            body.push('\n');
        }
        body.push_str("}\n");
    }

    render_kt_file(&package, &imports, &body)
}

/// Emit a single `expect` function signature (no body).
fn emit_expect_function(f: &FunctionDef, out: &mut String, imports: &mut BTreeSet<String>) {
    if !f.doc.is_empty() {
        let doc_lines: Vec<String> = f.doc.lines().map(ToString::to_string).collect();
        out.push_str(&crate::template_env::render(
            "doc_comment.jinja",
            minijinja::context! {
                indent => "    ",
                lines => doc_lines,
            },
        ));
    }
    let params: Vec<String> = f.params.iter().map(|p| format_param_pub(p, imports)).collect();
    let return_ty = kotlin_type_str_pub(&f.return_type, false, imports);
    let async_kw = if f.is_async { "suspend " } else { "" };
    let func_name_camel = to_lower_camel(&f.name);
    out.push_str(&crate::template_env::render(
        "expect_function_signature.jinja",
        minijinja::context! {
            async_kw => async_kw,
            name => func_name_camel,
            params => params.join(", "),
            return_type => return_ty,
        },
    ));
}

// ---------------------------------------------------------------------------
// jvmMain — actual object delegating to the JVM Bridge facade
// ---------------------------------------------------------------------------

fn emit_jvm_actual(api: &ApiSurface, config: &ResolvedCrateConfig) -> String {
    let package = config.kotlin_package();
    let module_name = to_pascal_case(&config.name);
    let java_package = config.java_package();

    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 visible_functions: Vec<&FunctionDef> = api
        .functions
        .iter()
        .filter(|f| !exclude_functions.contains(f.name.as_str()))
        .collect();

    let mut imports: BTreeSet<String> = BTreeSet::new();
    let mut body = String::new();

    if !visible_functions.is_empty() {
        imports.insert(format!("import {java_package}.{module_name} as {BRIDGE_ALIAS}"));
        if visible_functions.iter().any(|f| f.is_async) {
            imports.insert("import kotlinx.coroutines.Dispatchers".to_string());
            imports.insert("import kotlinx.coroutines.future.await".to_string());
            imports.insert("import kotlinx.coroutines.withContext".to_string());
        }

        body.push_str(&crate::template_env::render(
            "actual_object_declaration.jinja",
            minijinja::context! {
                name => module_name,
            },
        ));
        for f in &visible_functions {
            emit_function_jvm(f, &mut body, &mut imports, &java_package);
            body.push('\n');
        }
        body.push_str("}\n");
    }

    render_kt_file(&package, &imports, &body)
}

// ---------------------------------------------------------------------------
// nativeMain — actual object using kotlinx.cinterop
// ---------------------------------------------------------------------------

fn emit_native_actual(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 visible_functions: Vec<&FunctionDef> = api
        .functions
        .iter()
        .filter(|f| !exclude_functions.contains(f.name.as_str()))
        .collect();

    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();

    if !visible_functions.is_empty() {
        body.push_str(&crate::template_env::render(
            "actual_object_declaration.jinja",
            minijinja::context! {
                name => module_name,
            },
        ));
        for f in &visible_functions {
            emit_native_function_pub(f, &prefix, &mut body);
            body.push('\n');
        }
        body.push_str("}\n");
    }

    render_kt_file(&package, &imports, &body)
}

// ---------------------------------------------------------------------------
// cinterop .def file (same as Native target)
// ---------------------------------------------------------------------------

fn emit_def_file(config: &ResolvedCrateConfig) -> String {
    let header = config.ffi_header_name();
    let lib_name = config.ffi_lib_name();
    let prefix = config.ffi_prefix();

    format!("headers = {header}\nheaderFilter = {prefix}_*\nlinkerOpts = -L../../../target/release -l{lib_name}\n")
}

// ---------------------------------------------------------------------------
// build.gradle.kts — KMP project
// ---------------------------------------------------------------------------

fn emit_gradle_build(config: &ResolvedCrateConfig) -> String {
    let crate_name = &config.name;
    let kotlin_version = template_versions::maven::KOTLIN_JVM_PLUGIN;

    format!(
        r#"// Generated by alef. Do not edit by hand.

plugins {{
    kotlin("multiplatform") version "{kotlin_version}"
}}

kotlin {{
    jvm()

    linuxX64 {{
        compilations["main"].cinterops {{
            val {crate_name} by creating {{
                defFile = project.file("{crate_name}.def")
            }}
        }}
        binaries {{
            sharedLib()
        }}
    }}

    macosArm64 {{
        compilations["main"].cinterops {{
            val {crate_name} by creating {{
                defFile = project.file("{crate_name}.def")
            }}
        }}
        binaries {{
            sharedLib()
        }}
    }}

    iosX64 {{
        compilations["main"].cinterops {{
            val {crate_name} by creating {{
                defFile = project.file("{crate_name}.def")
            }}
        }}
        binaries {{
            framework()
        }}
    }}

    iosArm64 {{
        compilations["main"].cinterops {{
            val {crate_name} by creating {{
                defFile = project.file("{crate_name}.def")
            }}
        }}
        binaries {{
            framework()
        }}
    }}

    iosSimulatorArm64 {{
        compilations["main"].cinterops {{
            val {crate_name} by creating {{
                defFile = project.file("{crate_name}.def")
            }}
        }}
        binaries {{
            framework()
        }}
    }}

    androidNativeArm64 {{
        compilations["main"].cinterops {{
            val {crate_name} by creating {{
                defFile = project.file("{crate_name}.def")
            }}
        }}
        binaries {{
            sharedLib()
        }}
    }}

    sourceSets {{
        val commonMain by getting
        val jvmMain by getting
        val nativeMain by creating {{
            dependsOn(commonMain)
        }}
        val linuxX64Main by getting {{
            dependsOn(nativeMain)
        }}
        val macosArm64Main by getting {{
            dependsOn(nativeMain)
        }}
        val iosMain by creating {{
            dependsOn(nativeMain)
        }}
        val iosX64Main by getting {{
            dependsOn(iosMain)
        }}
        val iosArm64Main by getting {{
            dependsOn(iosMain)
        }}
        val iosSimulatorArm64Main by getting {{
            dependsOn(iosMain)
        }}
        val androidNativeArm64Main by getting {{
            dependsOn(nativeMain)
        }}
    }}
}}
"#
    )
}

// ---------------------------------------------------------------------------
// Shared rendering helper
// ---------------------------------------------------------------------------

fn render_kt_file(package: &str, imports: &BTreeSet<String>, body: &str) -> String {
    let mut content = String::new();
    content.push_str("// Generated by alef. Do not edit by hand.\n\n");
    content.push_str(&crate::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');
    }
    if !imports.is_empty() {
        content.push('\n');
    }
    content.push_str(body);
    content
}