alef 0.107.9

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
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
use crate::backends::java::type_map::java_ffi_type;
use crate::core::ir::{FunctionDef, ParamDef, PrimitiveType, TypeRef};
use ahash::AHashSet;
use heck::ToSnakeCase;

/// Returns true when the function's Rust return type is `Result<Vec<u8>>` (or
/// `Result<Option<Vec<u8>>>`). The FFI layer emits these as the out-param
/// convention: `(inputs..., out_ptr: *mut *mut u8, out_len: *mut usize,
/// out_cap: *mut usize) -> i32`.
pub(crate) fn is_bytes_result(func: &FunctionDef) -> bool {
    func.return_type.returns_bytes_out_params()
}

/// Check if the return type is a string-like type that requires pointer-based
/// FFI return handling (allocate + free pattern). `Optional<String>` and
/// `Optional<Path>` reduce to a nullable pointer with the same handling — the
/// boxed Java type is also `String`/`Path`, so the wrapper signature is
/// unchanged from the non-optional case.
pub(crate) fn is_ffi_string_return(ty: &TypeRef) -> bool {
    match ty {
        TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => true,
        TypeRef::Optional(inner) => matches!(
            inner.as_ref(),
            TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json
        ),
        _ => false,
    }
}

/// Returns the Java cast expression to apply to `MethodHandle.invoke()` return value.
///
/// The cast must match the widened ValueLayout from `java_ffi_type()`. When the
/// FunctionDescriptor uses a wider layout than the logical Java type (e.g. JAVA_LONG
/// for i32, JAVA_LONG for i16), `invoke()` boxes the wider type. We emit a chain of
/// casts to unbox then narrow back to the target type.
///
/// Examples:
/// - JAVA_LONG return (i32 → long): `(int)(long)` unboxes Long then narrows to int
/// - JAVA_LONG return (i16 → long): `(short)(long)` unboxes Long then narrows to short
/// - JAVA_LONG return (bool → long): `(int)(long)` unboxes Long then narrows to int
///
/// The bool arm previously emitted a bare `(long)`, on the reasoning that the `!= 0`
/// comparison in [`java_ffi_return_expr`] "handles narrowing". It does not: `!= 0` on a
/// `long` compares all 64 bits. The native function returns `int32_t` while the descriptor
/// declares JAVA_LONG, so the upper half is whatever happened to be in the register — and
/// any non-zero garbage there turns a native `false` into a Java `true`. A boolean-returning
/// FFI call could therefore never report false. Narrowing to `int` first discards the
/// undefined half, matching the i32 arm directly above.
///
/// The fix belongs here, at the call site, and NOT in the layout: `java_ffi_type` maps Bool
/// to JAVA_LONG deliberately and is pinned by a test, because narrowing the *descriptor* to
/// JAVA_INT reintroduces a JBR-on-Windows `ClassCastException`
/// (`ValueLayouts$OfIntImpl` cannot be cast to `ValueLayout$OfLong`). Widened layout,
/// narrowed call site. ~keep
pub(crate) fn java_ffi_return_cast(ty: &TypeRef) -> &'static str {
    match ty {
        TypeRef::Primitive(prim) => match prim {
            PrimitiveType::Bool => "(int)(long)",
            PrimitiveType::U8 | PrimitiveType::I8 => "(byte)(long)",
            PrimitiveType::U16 | PrimitiveType::I16 => "(short)(long)",
            PrimitiveType::U32 | PrimitiveType::I32 => "(int)(long)",
            PrimitiveType::U64 | PrimitiveType::I64 | PrimitiveType::Usize | PrimitiveType::Isize => "(long)",
            PrimitiveType::F32 => "(float)",
            PrimitiveType::F64 => "(double)",
        },
        TypeRef::Duration => "(long)",
        _ => "(MemorySegment)",
    }
}

pub(crate) fn java_ffi_return_expr(ty: &TypeRef, var_name: &str) -> String {
    match ty {
        TypeRef::Primitive(PrimitiveType::Bool) => format!("{var_name} != 0"),
        _ => var_name.to_string(),
    }
}

pub(crate) fn gen_ffi_layout_with_enums(ty: &TypeRef, enum_names: &AHashSet<String>) -> String {
    match ty {
        TypeRef::Primitive(prim) => java_ffi_type(prim).to_string(),
        TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => "ValueLayout.ADDRESS".to_string(),
        TypeRef::Bytes => "ValueLayout.ADDRESS".to_string(),
        TypeRef::Optional(inner) => gen_ffi_layout_with_enums(inner, enum_names),
        TypeRef::Vec(_) => "ValueLayout.ADDRESS".to_string(),
        TypeRef::Map(_, _) => "ValueLayout.ADDRESS".to_string(),
        TypeRef::Named(name) => {
            if enum_names.contains(name.as_str()) {
                "ValueLayout.JAVA_LONG".to_string()
            } else {
                "ValueLayout.ADDRESS".to_string()
            }
        }
        TypeRef::Unit => "".to_string(),
        TypeRef::Duration => "ValueLayout.JAVA_LONG".to_string(),
    }
}

/// C 32-bit integer parameters require `JAVA_INT`; return layouts stay widened for JBR. ~keep
fn gen_ffi_param_layout_with_enums(ty: &TypeRef, enum_names: &AHashSet<String>) -> String {
    match ty {
        TypeRef::Primitive(PrimitiveType::U32 | PrimitiveType::I32) => "ValueLayout.JAVA_INT".to_string(),
        TypeRef::Optional(inner) => gen_ffi_param_layout_with_enums(inner, enum_names),
        other => gen_ffi_layout_with_enums(other, enum_names),
    }
}

/// Build the Jackson `writer` expression that preserves generic element-type
/// info for a `Vec<T>` / `Map<K, V>` Java parameter. Without this, `MAPPER.
/// writeValueAsString(list)` erases T at runtime, dropping `@JsonTypeInfo`
/// discriminators on polymorphic element types like the tagged-enum DTO
/// `PageAction`. The returned expression is a `ObjectWriter`.
///
/// Also reached from the untagged-union wrapper (`types::enums::gen_java_untagged_wrapper`),
/// whose `ofObject(Object)` factory hits the identical erasure hazard. ~keep
pub(crate) fn build_collection_writer_for(
    inner: &TypeRef,
    outer: &TypeRef,
    _opaque_types: &AHashSet<String>,
) -> String {
    let elem_class = java_class_literal_for(inner);
    match outer {
        TypeRef::Vec(_) => format!(
            "MAPPER.writerFor(MAPPER.getTypeFactory().constructCollectionType(java.util.List.class, {elem_class}))"
        ),
        TypeRef::Map(k, _) => {
            let key_class = java_class_literal_for(k);
            format!(
                "MAPPER.writerFor(MAPPER.getTypeFactory().constructMapType(java.util.Map.class, {key_class}, {elem_class}))"
            )
        }
        _ => "MAPPER.writer()".to_string(),
    }
}

/// Render the Java `Class<?>` literal (e.g., `String.class`, `PageAction.class`,
/// `Integer.class`) for a Rust IR type. Used to construct typed Jackson
/// CollectionType / MapType so polymorphic element types serialize correctly.
fn java_class_literal_for(ty: &TypeRef) -> String {
    match ty {
        TypeRef::String | TypeRef::Char => "String.class".to_string(),
        TypeRef::Bytes => "byte[].class".to_string(),
        TypeRef::Path => "java.nio.file.Path.class".to_string(),
        TypeRef::Json => "Object.class".to_string(),
        TypeRef::Unit => "Void.class".to_string(),
        TypeRef::Duration => "Long.class".to_string(),
        TypeRef::Primitive(prim) => match prim {
            PrimitiveType::Bool => "Boolean.class".to_string(),
            PrimitiveType::U8 | PrimitiveType::I8 => "Byte.class".to_string(),
            PrimitiveType::U16 | PrimitiveType::I16 => "Short.class".to_string(),
            PrimitiveType::U32 | PrimitiveType::I32 => "Integer.class".to_string(),
            PrimitiveType::U64 | PrimitiveType::I64 | PrimitiveType::Usize | PrimitiveType::Isize => {
                "Long.class".to_string()
            }
            PrimitiveType::F32 => "Float.class".to_string(),
            PrimitiveType::F64 => "Double.class".to_string(),
        },
        TypeRef::Named(name) => format!("{name}.class"),
        TypeRef::Optional(inner) => java_class_literal_for(inner),
        TypeRef::Vec(_) => "java.util.List.class".to_string(),
        TypeRef::Map(_, _) => "java.util.Map.class".to_string(),
    }
}

fn render_marshaled_value(out: &mut String, template: &str, name: &str) {
    let cname = format!("c{name}");
    out.push_str(&crate::backends::java::template_env::render(
        template,
        minijinja::context! { cname, name },
    ));
}

/// Whether a `Named` type field is an opaque handle or a value type, and whether it is wrapped
/// in `Option<T>`. Grouped only to keep [`marshal_named`]'s parameter list short.
struct NamedFieldShape {
    opaque: bool,
    optional: bool,
}

fn marshal_named(out: &mut String, name: &str, type_name: &str, shape: NamedFieldShape, prefix: &str, resources: &str) {
    let NamedFieldShape { opaque, optional } = shape;
    if opaque {
        let template = if optional {
            "marshal_optional_opaque_handle.jinja"
        } else {
            "marshal_opaque_handle.jinja"
        };
        render_marshaled_value(out, template, name);
        return;
    }
    let type_upper = type_name.to_snake_case().to_uppercase();
    let prefix_upper = prefix.to_uppercase();
    let template = if optional {
        "marshal_optional_named_type.jinja"
    } else {
        "marshal_named_type.jinja"
    };
    out.push_str(&crate::backends::java::template_env::render(
        template,
        minijinja::context! {
            cname => format!("c{name}"), name,
            from_json_handle => format!("NativeLib.{prefix_upper}_{type_upper}_FROM_JSON"),
            free_handle => format!("NativeLib.{prefix_upper}_{type_upper}_FREE"), resources,
        },
    ));
}

fn optional_primitive_carrier(primitive: &PrimitiveType) -> (&'static str, &'static str) {
    match primitive {
        PrimitiveType::U64 | PrimitiveType::Usize => ("long", "-1L"),
        PrimitiveType::I64 | PrimitiveType::Isize => ("long", "Long.MAX_VALUE"),
        PrimitiveType::U32 => ("int", "-1"),
        PrimitiveType::I32 => ("int", "Integer.MAX_VALUE"),
        PrimitiveType::U16 => ("short", "(short) -1"),
        PrimitiveType::I16 => ("short", "Short.MAX_VALUE"),
        PrimitiveType::U8 => ("byte", "(byte) -1"),
        PrimitiveType::I8 => ("byte", "Byte.MAX_VALUE"),
        PrimitiveType::F32 => ("float", "Float.NaN"),
        PrimitiveType::F64 => ("double", "Double.NaN"),
        PrimitiveType::Bool => ("int", "0"),
    }
}

fn marshal_optional_primitive(out: &mut String, name: &str, primitive: &PrimitiveType) {
    let (prim_kw, none_lit) = optional_primitive_carrier(primitive);
    let value_expr = if matches!(primitive, PrimitiveType::Bool) {
        format!("({name} ? 1 : 0)")
    } else {
        name.to_string()
    };
    let range_check = matches!(primitive, PrimitiveType::U8 | PrimitiveType::U16 | PrimitiveType::U32 | PrimitiveType::U64 | PrimitiveType::Usize)
        .then(|| format!("            if ({name} != null && {name} < 0) {{\n              throw new IllegalArgumentException(\"{name} must be non-negative\");\n            }}\n"))
        .unwrap_or_default();
    out.push_str(&range_check);
    out.push_str(&crate::backends::java::template_env::render(
        "marshal_optional_primitive.jinja",
        minijinja::context! { cname => format!("c{name}"), name, prim_kw, none_lit, value_expr },
    ));
}

fn marshal_optional(
    out: &mut String,
    name: &str,
    inner: &TypeRef,
    opaque_types: &AHashSet<String>,
    prefix: &str,
    resources: &str,
) {
    match inner {
        TypeRef::String | TypeRef::Char => render_marshaled_value(out, "marshal_optional_string.jinja", name),
        TypeRef::Path => render_marshaled_value(out, "marshal_optional_path.jinja", name),
        TypeRef::Bytes => render_marshaled_value(out, "marshal_optional_bytes.jinja", name),
        TypeRef::Named(type_name) => marshal_named(
            out,
            name,
            type_name,
            NamedFieldShape {
                opaque: opaque_types.contains(type_name),
                optional: true,
            },
            prefix,
            resources,
        ),
        TypeRef::Primitive(primitive) => marshal_optional_primitive(out, name, primitive),
        _ => {}
    }
}

pub(crate) fn marshal_param_to_ffi(
    out: &mut String,
    name: &str,
    ty: &TypeRef,
    opaque_types: &AHashSet<String>,
    prefix: &str,
    resources: &str,
) {
    match ty {
        TypeRef::String | TypeRef::Char => render_marshaled_value(out, "marshal_string.jinja", name),
        TypeRef::Path => render_marshaled_value(out, "marshal_path.jinja", name),
        TypeRef::Bytes => render_marshaled_value(out, "marshal_bytes.jinja", name),
        TypeRef::Named(type_name) => marshal_named(
            out,
            name,
            type_name,
            NamedFieldShape {
                opaque: opaque_types.contains(type_name),
                optional: false,
            },
            prefix,
            resources,
        ),
        TypeRef::Optional(inner) => marshal_optional(out, name, inner, opaque_types, prefix, resources),
        TypeRef::Vec(inner) | TypeRef::Map(_, inner) => {
            let java_writer = build_collection_writer_for(inner, ty, opaque_types);
            out.push_str(&crate::backends::java::template_env::render(
                "marshal_vec_map.jinja",
                minijinja::context! { cname => format!("c{name}"), name, java_writer },
            ));
        }
        _ => {}
    }
}

pub(crate) fn opaque_lease_resource(name: &str, ty: &TypeRef, opaque_types: &AHashSet<String>) -> Option<String> {
    let (type_name, optional) = match ty {
        TypeRef::Named(type_name) => (type_name, false),
        TypeRef::Optional(inner) => match inner.as_ref() {
            TypeRef::Named(type_name) => (type_name, true),
            _ => return None,
        },
        _ => return None,
    };
    if !opaque_types.contains(type_name) {
        return None;
    }
    let cname = format!("c{name}");
    let expression = if optional {
        format!("{name} != null ? {name}.borrowHandle() : null")
    } else {
        format!("{name}.borrowHandle()")
    };
    Some(format!("             var {cname}Lease = {expression}"))
}

/// Generate the FFI argument(s) for a parameter.
///
/// Most parameters map to a single FFI argument. However, some expand to multiple:
/// - `Bytes` expands to (pointer, length)
/// - Bytes input parameters in bytes-result functions similarly expand
///
/// Returns a vector of argument expressions to be passed to MethodHandle.invoke().
pub(crate) fn ffi_param_args(name: &str, ty: &TypeRef, _opaque_types: &AHashSet<String>) -> Vec<String> {
    match ty {
        TypeRef::Bytes => {
            let cname = "c".to_string() + name;
            vec![cname.clone(), format!("{}Len", cname)]
        }
        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Bytes) => {
            let cname = "c".to_string() + name;
            vec![cname.clone(), format!("{}Len", cname)]
        }
        TypeRef::String | TypeRef::Char | TypeRef::Path => vec!["c".to_string() + name],
        TypeRef::Json => {
            vec![name.to_string()]
        }
        TypeRef::Named(_) => vec!["c".to_string() + name],
        TypeRef::Vec(_) | TypeRef::Map(_, _) => vec!["c".to_string() + name],
        TypeRef::Optional(inner) => match inner.as_ref() {
            TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Named(_) => {
                vec!["c".to_string() + name]
            }
            TypeRef::Json => {
                vec![name.to_string()]
            }
            TypeRef::Primitive(_) => vec!["c".to_string() + name],
            _ => vec![name.to_string()],
        },
        TypeRef::Primitive(PrimitiveType::Bool) => vec![format!("({name} ? 1 : 0)")],
        _ => vec![name.to_string()],
    }
}

/// Append the FFI layout of every parameter to `layouts`.
///
/// A `Bytes` parameter (bare or `Optional`) occupies an address/length pair; everything else takes
/// one layout. This is the single construction of that rule: the byte-buffer descriptor path, the
/// ordinary free-function path, and the opaque-method path all build from it, so a downcall
/// descriptor can never disagree with a sibling about a parameter's ABI width. Callers pass a Vec
/// rather than receiving one because the method path pre-seeds the receiver's `ADDRESS`. ~keep
pub(crate) fn push_param_layouts(params: &[ParamDef], enum_names: &AHashSet<String>, layouts: &mut Vec<String>) {
    for param in params {
        match &param.ty {
            TypeRef::Bytes => {
                layouts.push("ValueLayout.ADDRESS".to_string());
                layouts.push("ValueLayout.JAVA_LONG".to_string());
            }
            TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Bytes) => {
                layouts.push("ValueLayout.ADDRESS".to_string());
                layouts.push("ValueLayout.JAVA_LONG".to_string());
            }
            other => layouts.push(gen_ffi_param_layout_with_enums(other, enum_names)),
        }
    }
}

pub(crate) fn gen_function_descriptor(return_layout: &str, param_layouts: &[String]) -> String {
    if return_layout.is_empty() {
        if param_layouts.is_empty() {
            "FunctionDescriptor.ofVoid()".to_string()
        } else {
            format!("FunctionDescriptor.ofVoid({})", param_layouts.join(", "))
        }
    } else {
        if param_layouts.is_empty() {
            format!("FunctionDescriptor.of({})", return_layout)
        } else {
            format!("FunctionDescriptor.of({}, {})", return_layout, param_layouts.join(", "))
        }
    }
}

struct HelperNeeds {
    check_last_error: bool,
    read_cstring: bool,
    read_bytes: bool,
    read_json_list: bool,
    object_mapper: bool,
    native_resources: bool,
}

impl HelperNeeds {
    fn from_output(output: &str) -> Self {
        let read_json_list = output.contains("readJsonList(");
        Self {
            check_last_error: output.contains("checkLastError()"),
            read_cstring: output.contains("readCString("),
            read_bytes: output.contains("readBytes("),
            read_json_list,
            object_mapper: output.contains("MAPPER.") || read_json_list,
            native_resources: output.contains("new NativeResources()"),
        }
    }

    fn is_empty(&self) -> bool {
        !self.check_last_error
            && !self.read_cstring
            && !self.read_bytes
            && !self.read_json_list
            && !self.object_mapper
            && !self.native_resources
    }
}

/// Single source of truth for Java's fixed FFI infrastructure exception classes.
///
/// Every entry here becomes BOTH a generated `<name>.java` class (`JavaBackend::generate_bindings`
/// in `gen_bindings/mod.rs`, which also derives its `infrastructure_exception_names` skip-set from
/// this array) AND a `case <code> -> throw new <name>(msg);` arm in `checkLastError()`'s switch
/// (`emit_error_helper` below). Driving both from one array makes it structurally impossible to
/// add, rename, or drop an infrastructure exception in only one of the two places — the failure
/// mode that once left `InvalidInputException.java` on disk with no reachable dispatch arm after
/// the class was renamed to `ConversionErrorException` without updating both sites in lockstep.
///
/// Cancellation is a generated `{main}Exception` subclass rather than the JDK's
/// `java.util.concurrent.CancellationException`: the generated async wrappers and service classes
/// close with `catch (Throwable ...)` clauses that re-wrap anything outside the crate's exception
/// hierarchy as "FFI call failed", which would bury the cancellation under a nested cause. The
/// name avoids `CancelledException` because an error enum may declare its own `Cancelled`
/// variant, whose class this table would otherwise shadow. ~keep
pub(crate) const INFRASTRUCTURE_ERROR_CLASSES: [(&str, u32, &str); 4] = [
    (
        "ConversionErrorException",
        crate::core::ir::ApiSurface::FFI_ERROR_CODE_CONVERSION,
        "Exception thrown when an FFI value conversion fails.",
    ),
    (
        "CoreErrorException",
        crate::core::ir::ApiSurface::FFI_ERROR_CODE_UNKNOWN,
        "Exception thrown when the Rust core reports an unknown error.",
    ),
    (
        "PanicException",
        crate::core::ir::ApiSurface::FFI_ERROR_CODE_PANIC,
        "Exception thrown when a Rust panic is contained at the FFI boundary.",
    ),
    (
        "OperationCancelledException",
        crate::core::ir::ApiSurface::FFI_ERROR_CODE_CANCELLED,
        "Exception thrown when a native call is cancelled through its cancellation token.",
    ),
];

fn emit_error_helper(out: &mut String, prefix: &str) {
    out.push_str(&crate::backends::java::template_env::render(
        "helper_check_last_error.jinja",
        minijinja::context! {
            prefix_upper => prefix.to_uppercase(),
        },
    ));
}

fn emit_simple_helper(out: &mut String, template: &str) {
    out.push_str(&crate::backends::java::template_env::render(
        template,
        minijinja::context! {},
    ));
}

fn emit_read_json_list_helper(out: &mut String, prefix: &str, class_name: &str) {
    let free_handle = format!("NativeLib.{}_FREE_STRING", prefix.to_uppercase());
    out.push_str(&crate::backends::java::template_env::render(
        "helper_read_json_list.jinja",
        minijinja::context! {
            class_name => class_name,
            free_handle => free_handle,
        },
    ));
}

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

    #[test]
    fn path_values_are_serialized_as_native_file_system_paths() {
        let mut output = "MAPPER.writeValueAsString(value)".to_string();

        gen_helper_methods(&mut output, "sample", "Sample");

        assert!(
            output.contains("return JsonMapperFactory.withNativePathSerialization(mapper);"),
            "generated Java must apply the native Path serializer after its other modules:\n{output}"
        );
    }
}

pub(crate) fn gen_helper_methods(out: &mut String, prefix: &str, class_name: &str) {
    let needs = HelperNeeds::from_output(out);
    if needs.is_empty() {
        return;
    }

    out.push_str(&crate::backends::java::template_env::render(
        "gen_helper_methods_header.jinja",
        minijinja::context! {},
    ));
    out.push('\n');

    if needs.native_resources {
        emit_simple_helper(out, "helper_native_resources.jinja");
    }

    if needs.check_last_error {
        emit_error_helper(out, prefix);
    }

    if needs.object_mapper {
        emit_simple_helper(out, "helper_object_mapper.jinja");
    }

    if needs.read_cstring {
        emit_simple_helper(out, "helper_read_cstring.jinja");
    }

    if needs.read_bytes {
        emit_simple_helper(out, "helper_read_bytes.jinja");
    }

    if needs.read_json_list {
        emit_read_json_list_helper(out, prefix, class_name);
    }
}

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

    #[test]
    fn helper_maps_taxonomy_code_to_variant_exception() {
        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 api = crate::core::ir::ApiSurface {
            errors: vec![error],
            ..Default::default()
        };
        let code = api.error_taxonomy()[0].code;
        let mut output = "checkLastError()".to_string();

        gen_helper_methods(&mut output, "sample", "Sample");
        let dispatch =
            crate::backends::java::gen_bindings::last_error::gen_last_error_exception(&api, "sample", "Sample");

        assert!(dispatch.contains(&format!("case {code} -> new InvalidInputException(msg);")));
        assert!(dispatch.contains("case 1 -> new ConversionErrorException(msg);"));
        assert!(dispatch.contains("case 2 -> new CoreErrorException(msg);"));
        assert!(dispatch.contains("case 3 -> new PanicException(msg);"));
        assert!(output.contains("throw NativeLib.lastErrorException(errCode, msg);"));
        let null_guard = output
            .find("ctxPtr.equals(MemorySegment.NULL)")
            .expect("null context guard");
        let reinterpret = output.find("ctxPtr.reinterpret").expect("context read");
        assert!(null_guard < reinterpret);
    }

    /// Regression for a collision where a Java infrastructure exception was renamed in the
    /// switch-generating list but not in the file-generating list (or vice versa), leaving two
    /// classes claiming the same numeric code. `INFRASTRUCTURE_ERROR_CLASSES` is the single
    /// array both lists now read from, so this pins its codes and class names as pairwise unique. ~keep
    #[test]
    fn infrastructure_error_classes_have_unique_codes_and_names() {
        let mut codes: Vec<u32> = INFRASTRUCTURE_ERROR_CLASSES.iter().map(|(_, code, _)| *code).collect();
        let mut names: Vec<&str> = INFRASTRUCTURE_ERROR_CLASSES.iter().map(|(name, _, _)| *name).collect();

        let code_count = codes.len();
        codes.sort_unstable();
        codes.dedup();
        assert_eq!(
            codes.len(),
            code_count,
            "infrastructure error codes must be pairwise unique"
        );

        let name_count = names.len();
        names.sort_unstable();
        names.dedup();
        assert_eq!(
            name_count,
            names.len(),
            "infrastructure exception class names must be pairwise unique"
        );
    }

    /// Regression for the same class of bug from the switch-dispatch side: every infrastructure
    /// exception class, plus every explicitly taxonomy-numbered user error variant, must get
    /// exactly one `case <code> -> throw new <name>(msg);` arm — no class emitted with a code
    /// that never appears in the switch (unreachable), and no two classes sharing a code (a
    /// duplicate-`case` compile error in the generated Java). ~keep
    #[test]
    fn every_declared_exception_has_a_unique_reachable_dispatch_arm() {
        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()
                },
                crate::core::ir::ErrorVariant {
                    error_code: Some(101),
                    name: "Timeout".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 api = crate::core::ir::ApiSurface {
            errors: vec![error],
            ..Default::default()
        };
        let output =
            crate::backends::java::gen_bindings::last_error::gen_last_error_exception(&api, "sample", "Sample");

        let expected: Vec<(u32, String)> = INFRASTRUCTURE_ERROR_CLASSES
            .iter()
            .map(|(name, code, _)| (*code, (*name).to_string()))
            .chain(
                api.error_taxonomy()
                    .iter()
                    .map(|entry| (entry.code, format!("{}Exception", entry.variant))),
            )
            .collect();
        assert_eq!(expected.len(), 6, "expected 4 infrastructure + 2 taxonomy exceptions");

        for (code, class_name) in &expected {
            let arm = format!("case {code} -> new {class_name}(msg);");
            assert!(
                output.contains(&arm),
                "missing reachable dispatch arm for {class_name} (code {code}): {arm}"
            );
        }

        let case_count = output.matches("case ").count();
        assert_eq!(
            case_count,
            expected.len(),
            "generated switch must have exactly one case per declared exception, no extras and no drops"
        );
    }
}

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

    /// FFI code 5 (`Cancelled`) must reach a dedicated exception, not the `default` arm that
    /// reports every unknown code as the generic base exception. ~keep
    #[test]
    fn the_cancelled_ffi_code_has_its_own_dispatch_arm_and_class() {
        let output = crate::backends::java::gen_bindings::last_error::gen_last_error_exception(
            &crate::core::ir::ApiSurface::default(),
            "sample",
            "Sample",
        );
        assert!(
            output.contains("case 5 -> new OperationCancelledException(msg);"),
            "missing cancellation arm:\n{output}"
        );
        assert!(
            INFRASTRUCTURE_ERROR_CLASSES
                .iter()
                .any(|(name, code, _)| *name == "OperationCancelledException" && *code == 5)
        );
    }
}

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

    /// A boolean FFI return must be narrowed to `int` before the `!= 0` comparison.
    ///
    /// The descriptor declares JAVA_LONG while the native function returns `int32_t`, so the
    /// upper 32 bits are undefined. Comparing the untruncated `long` against 0 turns any
    /// garbage in that half into a spurious `true`, meaning such a call can never report
    /// false. Reported against two separate consumers' generated bindings. ~keep
    #[test]
    fn a_bool_return_narrows_before_the_zero_comparison() {
        assert_eq!(
            java_ffi_return_cast(&TypeRef::Primitive(PrimitiveType::Bool)),
            "(int)(long)",
            "a bare (long) leaves the undefined upper half in the != 0 comparison"
        );
    }

    /// The companion half: the *layout* must stay JAVA_LONG. Narrowing the descriptor instead
    /// of the call site reintroduces a JBR-on-Windows ClassCastException. ~keep
    #[test]
    fn a_bool_layout_stays_widened() {
        assert_eq!(
            crate::backends::java::type_map::java_ffi_type(&PrimitiveType::Bool),
            "ValueLayout.JAVA_LONG"
        );
    }

    /// Every other integral return already narrows; bool is now consistent with them.
    #[test]
    fn integral_returns_all_narrow_from_the_widened_layout() {
        for (prim, expected) in [
            (PrimitiveType::I8, "(byte)(long)"),
            (PrimitiveType::I16, "(short)(long)"),
            (PrimitiveType::I32, "(int)(long)"),
            (PrimitiveType::Bool, "(int)(long)"),
        ] {
            assert_eq!(java_ffi_return_cast(&TypeRef::Primitive(prim)), expected);
        }
    }
}

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

    #[test]
    fn u32_parameter_uses_java_int_while_wide_parameters_use_java_long() {
        let params = [
            ParamDef {
                name: "limit".to_string(),
                ty: TypeRef::Primitive(PrimitiveType::U32),
                ..Default::default()
            },
            ParamDef {
                name: "offset".to_string(),
                ty: TypeRef::Primitive(PrimitiveType::U64),
                ..Default::default()
            },
            ParamDef {
                name: "length".to_string(),
                ty: TypeRef::Primitive(PrimitiveType::Usize),
                ..Default::default()
            },
        ];
        let mut layouts = Vec::new();

        push_param_layouts(&params, &AHashSet::new(), &mut layouts);

        assert_eq!(
            layouts,
            ["ValueLayout.JAVA_INT", "ValueLayout.JAVA_LONG", "ValueLayout.JAVA_LONG",]
        );
    }
}