prebindgen-jni 0.5.0

JNI / Kotlin binding generator for prebindgen
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
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
//! Kotlin/JVM identifier mangling + the whole-artifact symbol-validation
//! pass (issue #89).
//!
//! Distinct from the sibling [`symbol`](super::symbol) module: that one
//! escapes **native `Java_…` export symbols** (the JNI ABI charset); this one
//! sanitizes and validates **Kotlin source identifiers** (class / function /
//! member / field / package names) and builds the per-package and
//! native-symbol collision tables.
//!
//! ## The "default mangler" design
//!
//! [`mangle_kotlin_ident`] — `kotlin_codegen`'s deterministic sanitizer, the
//! same primitive the Kotlin writer validates against — turns any string into
//! a valid Kotlin identifier. Every DEFAULT (Rust-derived) name flows through
//! it: the seven name-mangle hooks default to it (see `builder.rs`) and the
//! four non-hook derived-name sites call it directly, so the emitter always
//! produces valid names on the default path. The only ways an invalid name
//! can survive to [`validate_symbols`] are an explicit `.name()` override or
//! a custom mangle hook; both are author input, so an invalid one is a hard
//! error the author can correct in build.rs.

pub(crate) use kotlin_codegen::{
    is_valid_kotlin_ident, mangle_kotlin_ident, mangle_kotlin_package,
};
use kotlin_codegen::{KtFun, KtType};

use super::*;

/// The whole-artifact Kotlin-identifier + top-level-name validation pass
/// (issue #89), called from [`validate_bindings`]. Returns the collected
/// errors (joined into the same message the native-symbol table produces) and
/// emits `cargo:warning=` lines directly for names the default mangler had to
/// change. Runs on the resolved registry before any file is written.
///
/// * **Invalid-name errors** — a final Kotlin name that is still not a legal
///   identifier can only come from a `.name()` override or a custom mangle
///   hook (the default path is mangled → always valid), so it is an author
///   mistake, easy to correct in build.rs.
/// * **Top-level collisions** — two class / interface / harness / const-`val`
///   names colliding in one package, including a collision the mangler
///   created.
/// * **Warnings** — where the default mangler sanitized a Rust-derived name.
pub(crate) fn validate_symbols(ext: &Declarations, registry: &Registry<KotlinMeta>) -> Vec<String> {
    let mut errors: Vec<String> = Vec::new();
    // (package, name) → origin, for top-level-unique Kotlin declarations.
    let mut top_level: BTreeMap<(String, String), String> = BTreeMap::new();

    let mut add_top_level =
        |package: &str, name: &str, origin: String, errors: &mut Vec<String>| {
            if let Some(prev) =
                top_level.insert((package.to_string(), name.to_string()), origin.clone())
            {
                errors.push(format!(
                    "duplicate top-level Kotlin name `{name}` in package `{package}`: \
                     declared by both {prev} and {origin}",
                ));
            }
        };

    // Overload table: (scope, kotlin name, erased JVM signature) → origin.
    // `scope` separates the independent overload sets — a package's free
    // functions, one class's instance methods, one class's companion
    // factories. Two wrappers landing on the same key have an identical
    // Kotlin/JVM signature and cannot coexist (a "platform declaration
    // clash"); distinct signatures are legitimate overloads and pass.
    let mut overloads: BTreeMap<(String, String, JvmSignature), String> = BTreeMap::new();
    let mut add_overload = |scope: &str, f: &KtFun, origin: &str, errors: &mut Vec<String>| {
        let sig = jvm_signature(f);
        let key = (scope.to_string(), f.name.clone(), sig.clone());
        if let Some(prev) = overloads.insert(key, origin.to_string()) {
            errors.push(format!(
                "conflicting Kotlin overload `{}{sig}` in {scope}: {prev} and {origin} \
                     have the same erased JVM signature — rename one via `.name(...)` or \
                     change a parameter type",
                f.name,
            ));
        }
    };
    // `build_wrapper_surface` is pure — no import set to thread; the
    // validator only reads each surface's `fun.params`.

    // Classes (ptr / data / value / enum), in deterministic key order.
    let mut class_keys: Vec<&TypeKey> = ext
        .types
        .iter()
        .filter(|(_, cfg)| cfg.name_spec.is_some())
        .map(|(k, _)| k)
        .collect();
    class_keys.sort_by_key(|k| k.as_str().to_string());
    for key in class_keys {
        let cfg = &ext.types[key];
        let spec = cfg.name_spec.as_ref().expect("filtered to Some");
        let fqn = ext.fqn_of(spec);
        let (package, short) = fqn.rsplit_once('.').unwrap_or(("", fqn.as_str()));
        let origin = format!("class `{key}`");
        check_ident(short, &origin, &mut errors);
        add_top_level(package, short, origin.clone(), &mut errors);
        if cfg.interface_enabled {
            let iface = ext.interface_short_name_unchecked(
                package,
                short,
                cfg.interface_name_override.as_deref(),
            );
            let iorigin = format!("interface of class `{key}`");
            check_ident(&iface, &iorigin, &mut errors);
            add_top_level(package, &iface, iorigin, &mut errors);
        }
        // A sealed class's variants are Kotlin classes too — nested inside the
        // interface, so they are NOT registered as top-level names (nesting is
        // exactly what keeps them out of the package namespace). They instead
        // share the interface body, which is its own scope: check them against
        // each other, and against the one name in that scope the generator
        // cannot move.
        //
        // The companion object is deliberately NOT seeded here. Its default
        // name `Companion` is ours — an artifact of emitting a companion at
        // all, not a name Kotlin reserves — so when a variant wants it the
        // generator renames the companion instead of making the source crate
        // rename a legitimate variant (`Declarations::sum_companion_name`).
        //
        // The interface's own name is different: BOTH colliding names come
        // from the source crate (the enum's name and its variant's), so the
        // generator has no basis to pick which one to change — renaming
        // either would silently reshape the user's public Kotlin API. It is
        // also not repairable by qualifying the supertype: an inner
        // classifier shadows the outer name for the whole body, so
        // `fromParts`'s return type resolves to the variant too ("Type
        // mismatch: inferred type is E.Missing but E.E was expected").
        // Verified against kotlinc. So this one is a declaration error, and
        // the message names both ways to disambiguate.
        if let Some(sum_cfg) = cfg.sum() {
            let mut seen: BTreeMap<String, String> = BTreeMap::from([(
                short.to_string(),
                format!("sealed class `{key}` itself (its variants' supertype)"),
            )]);
            // The ELEMENT's alternatives, not the `syn::ItemEnum`'s variants:
            // this needs each one's NAME, which an `Alternative` carries.
            if let Some(alts) = key
                .ident()
                .and_then(|i| declared_member_names(registry, &i))
            {
                for v in alts {
                    let name = ext.sum_variant_class_name(sum_cfg, &v);
                    let vorigin = format!("variant `{v}` of sealed class `{key}`");
                    check_ident(&name, &vorigin, &mut errors);
                    if let Some(prev) = seen.insert(name.clone(), vorigin.clone()) {
                        errors.push(format!(
                            "Kotlin name `{name}` is taken twice inside sealed class `{key}`: \
                             by {prev} and by {vorigin} — rename either with \
                             `variant!(...).name(\"...\")` or `sealed_class!(...).name(\"...\")`",
                        ));
                    }
                }
            }
        }
    }

    // The central JNINative harness object — one per base package.
    let harness = ext.jni_native_class_name();
    check_ident(&harness, "the `JNINative` harness object", &mut errors);
    add_top_level(
        &ext.package,
        &harness,
        "the `JNINative` harness object".to_string(),
        &mut errors,
    );

    // Declared package-level functions + their const `val`s, per subpackage.
    let mut subpackages: Vec<&String> = ext.packages.keys().collect();
    subpackages.sort();
    for sub in subpackages {
        let pkg_cfg = &ext.packages[sub];
        let package = ext.package_name(sub);
        let fn_scope = format!("package `{package}`");
        for entry in &pkg_cfg.functions {
            let name = ext.effective_function_name(sub, entry);
            let origin = format!("function `{}`", entry.rust_ident);
            check_ident(&name, &origin, &mut errors);
            // Same-named free functions may overload if their erased JVM
            // signatures differ; the overload table rejects clashes. The
            // surface signature (base + `.split_on_param` shells) comes from
            // the SAME `build_wrapper_surface` emission uses — a body-less
            // prototype, so the validator doesn't pay for body codegen.
            if let Some(item_fn) = registry.flat().function(&entry.rust_ident) {
                if let Some(s) = build_wrapper_surface(ext, item_fn, registry, Some(&name), None) {
                    for ov in render_param_overloads(ext, item_fn, registry, &s.fun) {
                        add_overload(&fn_scope, &ov, &origin, &mut errors);
                    }
                    add_overload(&fn_scope, &s.fun, &origin, &mut errors);
                }
            }
        }
        // Const `val`s ARE top-level-unique (a property, not an overloadable fn).
        for entry in pkg_cfg
            .constants
            .iter()
            .chain(pkg_cfg.constant_functions.iter())
        {
            let name = entry
                .kotlin_name_override
                .clone()
                .unwrap_or_else(|| mangle_kotlin_ident(&entry.rust_ident.to_string()));
            let origin = format!("const `{}`", entry.rust_ident);
            check_ident(&name, &origin, &mut errors);
            add_top_level(&package, &name, origin, &mut errors);
        }
        for decl in &pkg_cfg.constant_exprs {
            let origin = format!("expression constant `{}`", decl.kotlin_name);
            check_ident(&decl.kotlin_name, &origin, &mut errors);
            add_top_level(&package, &decl.kotlin_name, origin, &mut errors);
        }
    }

    // Class members: instance methods and companion factories are separate
    // overload sets (distinct JVM scopes), so a method and a constructor may
    // share a name. Render each exactly as emission does — a method with the
    // receiver bound (`receiver_key = Some`), a constructor without — and
    // collect its overload signature under a per-class, per-kind scope.
    let mut member_keys: Vec<&TypeKey> = ext.class_members.keys().collect();
    member_keys.sort_by_key(|k| k.as_str().to_string());
    for key in member_keys {
        for m in &ext.class_members[key] {
            let name = ext.effective_method_name(key, m);
            check_ident(&name, &format!("method `{}`", m.rust_ident), &mut errors);
            let Some(item_fn) = registry.flat().function(&m.rust_ident) else {
                continue;
            };
            let (scope, receiver) = match m.kind {
                MemberKind::Method => (format!("class `{key}` methods"), Some(key)),
                MemberKind::Constructor => (format!("class `{key}` factories"), None),
            };
            let origin = format!("member `{}`", m.rust_ident);
            if let Some(s) = build_wrapper_surface(ext, item_fn, registry, Some(&name), receiver) {
                for ov in render_param_overloads(ext, item_fn, registry, &s.fun) {
                    add_overload(&scope, &ov, &origin, &mut errors);
                }
                add_overload(&scope, &s.fun, &origin, &mut errors);
            }
        }
    }

    // Warnings: Rust-derived names the DEFAULT mangler had to sanitize (a
    // struct field / enum variant named like a Kotlin keyword). Author
    // `.name()` / custom-hook names are covered by the errors above.
    warn_derived_name_changes(ext, registry);

    errors
}

/// Error when `name` is not a legal Kotlin identifier — reachable only from a
/// `.name()` override or a custom mangle hook (see [`validate_symbols`]).
///
/// Deliberately the plain predicate, not `kotlin_codegen::is_writable_kotlin_ident`:
/// Kotlin would accept a back-ticked name here, but it can't be a native-symbol
/// component, so the generator never emits one.
fn check_ident(name: &str, origin: &str, errors: &mut Vec<String>) {
    if !is_valid_kotlin_ident(name) {
        errors.push(format!(
            "`{name}` ({origin}) is not a valid Kotlin identifier — fix the `.name(...)` \
             override or the name mangle hook that produced it",
        ));
    }
}

/// Emit a `cargo:warning` for each Rust struct field (data-class property) or
/// enum variant whose Kotlin name the default mangler had to change.
fn warn_derived_name_changes(ext: &Declarations, registry: &Registry<KotlinMeta>) {
    let warn = |raw: &str, mangled: &str, what: &str, owner: &str| {
        if raw != mangled {
            println!(
                "cargo:warning=prebindgen: {what} `{raw}` of `{owner}` emitted as `{mangled}` \
                 (invalid Kotlin identifier sanitized)"
            );
        }
    };
    let mut class_keys: Vec<&TypeKey> = ext
        .types
        .iter()
        .filter(|(_, cfg)| cfg.name_spec.is_some())
        .map(|(k, _)| k)
        .collect();
    class_keys.sort_by_key(|k| k.as_str().to_string());
    for key in class_keys {
        let Some(ident) = key.ident() else {
            continue;
        };
        if let Some(s) = registry.flat().struct_type(&ident) {
            for f in &s.fields {
                if let Some(fname) = &f.name {
                    let camel = kt_snake_to_camel(&fname.to_string());
                    warn(
                        &camel,
                        &mangle_kotlin_ident(&camel),
                        "field",
                        &ident.to_string(),
                    );
                }
            }
        }
        if let Some(names) = declared_member_names(registry, &ident) {
            for v in names {
                let screaming = crate::util::camel_to_screaming_snake(&v.to_string());
                warn(
                    &screaming,
                    &mangle_kotlin_ident(&screaming),
                    "enum variant",
                    &ident.to_string(),
                );
            }
        }
    }
}

/// The member names of a declared `enum` — its values for a fieldless one, its
/// alternatives for a sum.
///
/// `enum_item` answered for both shapes by handing back the whole
/// `syn::ItemEnum`; the model states them as two elements, and both carry the
/// names this asks for. `None` when `ident` names neither.
fn declared_member_names(
    registry: &impl prebindgen_registry::Conversions<KotlinMeta>,
    ident: &syn::Ident,
) -> Option<Vec<syn::Ident>> {
    use prebindgen_registry::flat::Type;
    match registry.flat().declared_type(ident)? {
        Type::Enum(e) => Some(e.values.iter().map(|v| v.name.clone()).collect()),
        Type::Variant(v) => Some(v.alternatives.iter().map(|a| a.name.clone()).collect()),
        _ => None,
    }
}

// ──────────────────────────────────────────────────────────────────────
// JVM erasure model (issue #89 stage 2)
// ──────────────────────────────────────────────────────────────────────

/// A JVM-erased parameter type token: two parameters collide as overloads
/// iff their tokens are equal. Human-readable, for the diagnostic.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub(crate) struct ErasedJvmType(String);

impl ErasedJvmType {
    /// A verbatim token — the structural fallback for a type with no
    /// resolved Kotlin surface (used by the #52 split-arm erasure).
    pub(crate) fn raw(s: impl Into<String>) -> Self {
        ErasedJvmType(s.into())
    }
}

impl std::fmt::Display for ErasedJvmType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// The JVM overload signature of a generated wrapper: its erased parameter
/// types in order. The **return type is intentionally absent** — the JVM
/// (and Kotlin) resolve overloads by name + parameter types only, so two
/// functions differing only in return type still clash.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub(crate) struct JvmSignature(Vec<ErasedJvmType>);

impl std::fmt::Display for JvmSignature {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "(")?;
        for (i, t) in self.0.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{t}")?;
        }
        write!(f, ")")
    }
}

/// The JVM boxed class of a Kotlin primitive — a nullable primitive crosses
/// as its box (`Int?` → `java.lang.Integer`), a distinct JVM descriptor from
/// the unboxed primitive, so `f(x: Int)` and `f(x: Int?)` do NOT clash.
fn boxed_primitive(simple: &str) -> Option<&'static str> {
    Some(match simple {
        "Int" => "java.lang.Integer",
        "Long" => "java.lang.Long",
        "Short" => "java.lang.Short",
        "Byte" => "java.lang.Byte",
        "Char" => "java.lang.Character",
        "Boolean" => "java.lang.Boolean",
        "Float" => "java.lang.Float",
        "Double" => "java.lang.Double",
        _ => return None,
    })
}

/// Erase a Kotlin surface type to its JVM overload token. Rules (the complete
/// model — issue #89):
///
/// * a type variable declared on the function (`R` / `A`) → `Object`;
/// * a non-null primitive → itself; a **nullable** primitive → its box
///   (`Int?` → `java.lang.Integer`) — a distinct descriptor;
/// * non-null `ULong` → its inline-class carrier `Long`; nullable `ULong?` →
///   the boxed `kotlin.ULong` class;
/// * `String` / `ByteArray` / `Any` → their JVM types (object nullability is
///   irrelevant to the descriptor);
/// * a generic type → its raw class (`List<T>` → `List`), arguments erased;
/// * any other class → its FQN (distinct classes stay distinct);
/// * a function type → `kotlin.Function<arity>`.
pub(crate) fn erase_kt_type(generics: &[String], ty: &KtType) -> ErasedJvmType {
    use kt::KtType;
    let token = match ty {
        KtType::Function { params, .. } => format!("kotlin.Function{}", params.len()),
        KtType::Named { fqn, nullable, .. } => {
            let simple = ty.simple_name().unwrap_or(fqn);
            if generics.iter().any(|g| g == fqn) {
                "java.lang.Object".to_string()
            } else if simple == "ULong" {
                if *nullable {
                    "kotlin.ULong".to_string()
                } else {
                    "Long".to_string()
                }
            } else if let Some(boxed) = boxed_primitive(simple) {
                if *nullable {
                    boxed.to_string()
                } else {
                    simple.to_string()
                }
            } else {
                match simple {
                    "String" => "java.lang.String".to_string(),
                    "ByteArray" => "byte[]".to_string(),
                    "Any" => "java.lang.Object".to_string(),
                    "Unit" => "void".to_string(),
                    // Generic container (args erased) or a plain class: the
                    // declared `fqn` (a generic's `fqn` is its raw name, e.g.
                    // `List`), so `List<X>` and `List<Y>` share one token.
                    _ => fqn.clone(),
                }
            }
        }
    };
    ErasedJvmType(token)
}

/// The [`JvmSignature`] of a generated wrapper (`render_wrapper_fn` /
/// `render_param_overloads` output): each parameter erased through
/// [`erase_kt_type`] under the function's own generic type variables.
pub(crate) fn jvm_signature(f: &KtFun) -> JvmSignature {
    JvmSignature(
        f.params
            .iter()
            .map(|p| erase_kt_type(&f.generics, &p.ty))
            .collect(),
    )
}

/// A native `Java_…` export symbol — charset-guaranteed valid by
/// [`symbol::native_symbol`](super::symbol::native_symbol). A newtype so the
/// collision table's key type documents itself and can't be confused with a
/// Kotlin name string. (The typed Kotlin-side carriers `KotlinIdent` /
/// `KotlinFqn` / `JvmSignature` arrive in Stage 2, where the JVM-erasure
/// overload model needs them.)
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub(crate) struct NativeSymbol(String);

impl NativeSymbol {
    pub fn new(sym: impl Into<String>) -> Self {
        NativeSymbol(sym.into())
    }
}

#[cfg(test)]
mod tests {
    use kotlin_codegen as kt;

    use super::erase_kt_type;

    fn erase(generics: &[&str], ty: kt::KtType) -> String {
        let gs: Vec<String> = generics.iter().map(|s| s.to_string()).collect();
        erase_kt_type(&gs, &ty).to_string()
    }

    #[test]
    fn jvm_erasure_rules() {
        // Non-null primitive is itself; nullable primitive boxes → distinct.
        assert_eq!(erase(&[], kt::KtType::int()), "Int");
        assert_eq!(
            erase(&[], kt::KtType::int().nullable()),
            "java.lang.Integer"
        );
        assert_ne!(
            erase(&[], kt::KtType::int()),
            erase(&[], kt::KtType::int().nullable()),
            "Int and Int? must NOT clash"
        );
        // Kotlin's ULong is an inline class backed by a primitive long. Its
        // nullable form is boxed as kotlin.ULong, not java.lang.Long.
        assert_eq!(erase(&[], kt::KtType::cls("ULong")), "Long");
        assert_eq!(
            erase(&[], kt::KtType::cls("ULong").nullable()),
            "kotlin.ULong"
        );
        assert_eq!(
            erase(&[], kt::KtType::cls("ULong")),
            erase(&[], kt::KtType::long()),
            "ULong and Long share the same JVM carrier"
        );
        // Object types: nullability is irrelevant to the descriptor.
        assert_eq!(erase(&[], kt::KtType::string()), "java.lang.String");
        assert_eq!(
            erase(&[], kt::KtType::string().nullable()),
            "java.lang.String",
            "String and String? share one descriptor"
        );
        assert_eq!(erase(&[], kt::KtType::byte_array()), "byte[]");
        assert_eq!(erase(&[], kt::KtType::any()), "java.lang.Object");
        // Generics erased to the raw class: List<Int> and List<String> clash.
        assert_eq!(
            erase(&[], kt::KtType::generic("List", [kt::KtType::int()])),
            erase(&[], kt::KtType::generic("List", [kt::KtType::string()])),
        );
        // A function's own type variable erases to Object.
        assert_eq!(erase(&["A"], kt::KtType::var_("A")), "java.lang.Object");
        assert_eq!(erase(&["R"], kt::KtType::var_r()), "java.lang.Object");
        // A single-letter name that is NOT a declared type var stays a class.
        assert_eq!(erase(&[], kt::KtType::cls("io.test.Foo")), "io.test.Foo");
        assert_ne!(
            erase(&[], kt::KtType::cls("io.test.Foo")),
            erase(&[], kt::KtType::cls("io.other.Foo")),
            "distinct FQNs stay distinct"
        );
    }
}