alef-backend-java 0.7.0

Java (Panama FFM) 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
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
use ahash::AHashSet;
use alef_core::config::AlefConfig;
use alef_core::hash::{self, CommentStyle};
use alef_core::ir::{ApiSurface, TypeRef};
use heck::ToSnakeCase;
use std::fmt::Write;

use super::marshal::{gen_ffi_layout, gen_function_descriptor};

pub(crate) fn gen_native_lib(
    api: &ApiSurface,
    config: &AlefConfig,
    package: &str,
    prefix: &str,
    has_visitor_bridge: bool,
) -> String {
    // Generate the class body first, then scan it to determine which imports are needed.
    let mut body = String::with_capacity(2048);
    // Derive the native library name from the FFI output path (directory name with hyphens replaced
    // by underscores), falling back to `{ffi_prefix}_ffi`.
    let lib_name = config.ffi_lib_name();

    writeln!(body, "final class NativeLib {{").ok();
    writeln!(body, "    private static final Linker LINKER = Linker.nativeLinker();").ok();
    writeln!(body, "    private static final SymbolLookup LIB;").ok();
    writeln!(
        body,
        "    private static final String NATIVES_RESOURCE_ROOT = \"/natives\";"
    )
    .ok();
    writeln!(
        body,
        "    private static final Object NATIVE_EXTRACT_LOCK = new Object();"
    )
    .ok();
    writeln!(body, "    private static String cachedExtractKey;").ok();
    writeln!(body, "    private static Path cachedExtractDir;").ok();
    writeln!(body).ok();
    writeln!(body, "    static {{").ok();
    writeln!(body, "        loadNativeLibrary();").ok();
    writeln!(body, "        LIB = SymbolLookup.loaderLookup();").ok();
    writeln!(body, "    }}").ok();
    writeln!(body).ok();
    writeln!(body, "    private static void loadNativeLibrary() {{").ok();
    writeln!(
        body,
        "        String osName = System.getProperty(\"os.name\", \"\").toLowerCase(java.util.Locale.ROOT);"
    )
    .ok();
    writeln!(
        body,
        "        String osArch = System.getProperty(\"os.arch\", \"\").toLowerCase(java.util.Locale.ROOT);"
    )
    .ok();
    writeln!(body).ok();
    writeln!(body, "        String libName;").ok();
    writeln!(body, "        String libExt;").ok();
    writeln!(
        body,
        "        if (osName.contains(\"mac\") || osName.contains(\"darwin\")) {{"
    )
    .ok();
    writeln!(body, "            libName = \"lib{}\";", lib_name).ok();
    writeln!(body, "            libExt = \".dylib\";").ok();
    writeln!(body, "        }} else if (osName.contains(\"win\")) {{").ok();
    writeln!(body, "            libName = \"{}\";", lib_name).ok();
    writeln!(body, "            libExt = \".dll\";").ok();
    writeln!(body, "        }} else {{").ok();
    writeln!(body, "            libName = \"lib{}\";", lib_name).ok();
    writeln!(body, "            libExt = \".so\";").ok();
    writeln!(body, "        }}").ok();
    writeln!(body).ok();
    writeln!(body, "        String nativesRid = resolveNativesRid(osName, osArch);").ok();
    writeln!(
        body,
        "        String nativesDir = NATIVES_RESOURCE_ROOT + \"/\" + nativesRid;"
    )
    .ok();
    writeln!(body).ok();
    writeln!(
        body,
        "        Path extracted = tryExtractAndLoadFromResources(nativesDir, libName, libExt);"
    )
    .ok();
    writeln!(body, "        if (extracted != null) {{").ok();
    writeln!(body, "            return;").ok();
    writeln!(body, "        }}").ok();
    writeln!(body).ok();
    writeln!(body, "        try {{").ok();
    writeln!(body, "            System.loadLibrary(\"{}\");", lib_name).ok();
    writeln!(body, "        }} catch (UnsatisfiedLinkError e) {{").ok();
    writeln!(
        body,
        "            String msg = \"Failed to load {} native library. Expected resource: \" + nativesDir + \"/\" + libName",
        lib_name
    ).ok();
    writeln!(
        body,
        "                    + libExt + \" (RID: \" + nativesRid + \"). \""
    )
    .ok();
    writeln!(
        body,
        "                    + \"Ensure the library is bundled in the JAR under natives/{{os-arch}}/, \""
    )
    .ok();
    writeln!(
        body,
        "                    + \"or place it on the system library path (java.library.path).\";",
    )
    .ok();
    writeln!(
        body,
        "            UnsatisfiedLinkError out = new UnsatisfiedLinkError(msg + \" Original error: \" + e.getMessage());"
    )
    .ok();
    writeln!(body, "            out.initCause(e);").ok();
    writeln!(body, "            throw out;").ok();
    writeln!(body, "        }}").ok();
    writeln!(body, "    }}").ok();
    writeln!(body).ok();
    writeln!(
        body,
        "    private static Path tryExtractAndLoadFromResources(String nativesDir, String libName, String libExt) {{"
    )
    .ok();
    writeln!(
        body,
        "        String resourcePath = nativesDir + \"/\" + libName + libExt;"
    )
    .ok();
    writeln!(
        body,
        "        URL resource = NativeLib.class.getResource(resourcePath);"
    )
    .ok();
    writeln!(body, "        if (resource == null) {{").ok();
    writeln!(body, "            return null;").ok();
    writeln!(body, "        }}").ok();
    writeln!(body).ok();
    writeln!(body, "        try {{").ok();
    writeln!(
        body,
        "            Path tempDir = extractOrReuseNativeDirectory(nativesDir);"
    )
    .ok();
    writeln!(body, "            Path libPath = tempDir.resolve(libName + libExt);").ok();
    writeln!(body, "            if (!Files.exists(libPath)) {{").ok();
    writeln!(
        body,
        "                throw new UnsatisfiedLinkError(\"Missing extracted native library: \" + libPath);"
    )
    .ok();
    writeln!(body, "            }}").ok();
    writeln!(body, "            System.load(libPath.toAbsolutePath().toString());").ok();
    writeln!(body, "            return libPath;").ok();
    writeln!(body, "        }} catch (Exception e) {{").ok();
    writeln!(body, "            System.err.println(\"[NativeLib] Failed to extract and load native library from resources: \" + e.getMessage());").ok();
    writeln!(body, "            return null;").ok();
    writeln!(body, "        }}").ok();
    writeln!(body, "    }}").ok();
    writeln!(body).ok();
    writeln!(
        body,
        "    private static Path extractOrReuseNativeDirectory(String nativesDir) throws Exception {{"
    )
    .ok();
    writeln!(
        body,
        "        URL location = NativeLib.class.getProtectionDomain().getCodeSource().getLocation();"
    )
    .ok();
    writeln!(body, "        if (location == null) {{").ok();
    writeln!(
        body,
        "            throw new IllegalStateException(\"Missing code source location for {} JAR\");",
        lib_name
    )
    .ok();
    writeln!(body, "        }}").ok();
    writeln!(body).ok();
    writeln!(body, "        Path codePath = Path.of(location.toURI());").ok();
    writeln!(
        body,
        "        String key = codePath.toAbsolutePath() + \"::\" + nativesDir;"
    )
    .ok();
    writeln!(body).ok();
    writeln!(body, "        synchronized (NATIVE_EXTRACT_LOCK) {{").ok();
    writeln!(
        body,
        "            if (cachedExtractDir != null && key.equals(cachedExtractKey)) {{"
    )
    .ok();
    writeln!(body, "                return cachedExtractDir;").ok();
    writeln!(body, "            }}").ok();
    writeln!(
        body,
        "            Path tempDir = Files.createTempDirectory(\"{}_native\");",
        lib_name
    )
    .ok();
    writeln!(body, "            tempDir.toFile().deleteOnExit();").ok();
    writeln!(
        body,
        "            List<Path> extracted = extractNativeDirectory(codePath, nativesDir, tempDir);"
    )
    .ok();
    writeln!(body, "            if (extracted.isEmpty()) {{").ok();
    writeln!(body, "                throw new IllegalStateException(\"No native files extracted from resources dir: \" + nativesDir);").ok();
    writeln!(body, "            }}").ok();
    writeln!(body, "            cachedExtractKey = key;").ok();
    writeln!(body, "            cachedExtractDir = tempDir;").ok();
    writeln!(body, "            return tempDir;").ok();
    writeln!(body, "        }}").ok();
    writeln!(body, "    }}").ok();
    writeln!(body).ok();
    writeln!(body, "    private static List<Path> extractNativeDirectory(Path codePath, String nativesDir, Path destDir) throws Exception {{").ok();
    writeln!(
        body,
        "        if (!Files.exists(destDir) || !Files.isDirectory(destDir)) {{"
    )
    .ok();
    writeln!(
        body,
        "            throw new IllegalArgumentException(\"Destination directory does not exist: \" + destDir);"
    )
    .ok();
    writeln!(body, "        }}").ok();
    writeln!(body).ok();
    writeln!(
        body,
        "        String prefix = nativesDir.startsWith(\"/\") ? nativesDir.substring(1) : nativesDir;"
    )
    .ok();
    writeln!(body, "        if (!prefix.endsWith(\"/\")) {{").ok();
    writeln!(body, "            prefix = prefix + \"/\";").ok();
    writeln!(body, "        }}").ok();
    writeln!(body).ok();
    writeln!(body, "        if (Files.isDirectory(codePath)) {{").ok();
    writeln!(body, "            Path nativesPath = codePath.resolve(prefix);").ok();
    writeln!(
        body,
        "            if (!Files.exists(nativesPath) || !Files.isDirectory(nativesPath)) {{"
    )
    .ok();
    writeln!(body, "                return List.of();").ok();
    writeln!(body, "            }}").ok();
    writeln!(body, "            return copyDirectory(nativesPath, destDir);").ok();
    writeln!(body, "        }}").ok();
    writeln!(body).ok();
    writeln!(body, "        List<Path> extracted = new ArrayList<>();").ok();
    writeln!(body, "        try (JarFile jar = new JarFile(codePath.toFile())) {{").ok();
    writeln!(body, "            Enumeration<JarEntry> entries = jar.entries();").ok();
    writeln!(body, "            while (entries.hasMoreElements()) {{").ok();
    writeln!(body, "                JarEntry entry = entries.nextElement();").ok();
    writeln!(body, "                String name = entry.getName();").ok();
    writeln!(
        body,
        "                if (!name.startsWith(prefix) || entry.isDirectory()) {{"
    )
    .ok();
    writeln!(body, "                    continue;").ok();
    writeln!(body, "                }}").ok();
    writeln!(
        body,
        "                String relative = name.substring(prefix.length());"
    )
    .ok();
    writeln!(body, "                Path out = safeResolve(destDir, relative);").ok();
    writeln!(body, "                Files.createDirectories(out.getParent());").ok();
    writeln!(body, "                try (var in = jar.getInputStream(entry)) {{").ok();
    writeln!(
        body,
        "                    Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING);"
    )
    .ok();
    writeln!(body, "                }}").ok();
    writeln!(body, "                out.toFile().deleteOnExit();").ok();
    writeln!(body, "                extracted.add(out);").ok();
    writeln!(body, "            }}").ok();
    writeln!(body, "        }}").ok();
    writeln!(body, "        return extracted;").ok();
    writeln!(body, "    }}").ok();
    writeln!(body).ok();
    writeln!(
        body,
        "    private static List<Path> copyDirectory(Path srcDir, Path destDir) throws Exception {{"
    )
    .ok();
    writeln!(body, "        List<Path> copied = new ArrayList<>();").ok();
    writeln!(body, "        try (var paths = Files.walk(srcDir)) {{").ok();
    writeln!(body, "            for (Path src : (Iterable<Path>) paths::iterator) {{").ok();
    writeln!(body, "                if (Files.isDirectory(src)) {{").ok();
    writeln!(body, "                    continue;").ok();
    writeln!(body, "                }}").ok();
    writeln!(body, "                Path relative = srcDir.relativize(src);").ok();
    writeln!(
        body,
        "                Path out = safeResolve(destDir, relative.toString());"
    )
    .ok();
    writeln!(body, "                Files.createDirectories(out.getParent());").ok();
    writeln!(
        body,
        "                Files.copy(src, out, StandardCopyOption.REPLACE_EXISTING);"
    )
    .ok();
    writeln!(body, "                out.toFile().deleteOnExit();").ok();
    writeln!(body, "                copied.add(out);").ok();
    writeln!(body, "            }}").ok();
    writeln!(body, "        }}").ok();
    writeln!(body, "        return copied;").ok();
    writeln!(body, "    }}").ok();
    writeln!(body).ok();
    writeln!(
        body,
        "    private static Path safeResolve(Path destDir, String relative) throws Exception {{"
    )
    .ok();
    writeln!(
        body,
        "        Path normalizedDest = destDir.toAbsolutePath().normalize();"
    )
    .ok();
    writeln!(body, "        Path out = normalizedDest.resolve(relative).normalize();").ok();
    writeln!(body, "        if (!out.startsWith(normalizedDest)) {{").ok();
    writeln!(body, "            throw new SecurityException(\"Blocked extracting native file outside destination directory: \" + relative);").ok();
    writeln!(body, "        }}").ok();
    writeln!(body, "        return out;").ok();
    writeln!(body, "    }}").ok();
    writeln!(body).ok();
    writeln!(
        body,
        "    private static String resolveNativesRid(String osName, String osArch) {{"
    )
    .ok();
    writeln!(body, "        String arch;").ok();
    writeln!(
        body,
        "        if (osArch.contains(\"aarch64\") || osArch.contains(\"arm64\")) {{"
    )
    .ok();
    writeln!(body, "            arch = \"arm64\";").ok();
    writeln!(
        body,
        "        }} else if (osArch.contains(\"x86_64\") || osArch.contains(\"amd64\")) {{"
    )
    .ok();
    writeln!(body, "            arch = \"x86_64\";").ok();
    writeln!(body, "        }} else {{").ok();
    writeln!(body, "            arch = osArch.replaceAll(\"[^a-z0-9_]+\", \"\");").ok();
    writeln!(body, "        }}").ok();
    writeln!(body).ok();
    writeln!(body, "        String os;").ok();
    writeln!(
        body,
        "        if (osName.contains(\"mac\") || osName.contains(\"darwin\")) {{"
    )
    .ok();
    writeln!(body, "            os = \"macos\";").ok();
    writeln!(body, "        }} else if (osName.contains(\"win\")) {{").ok();
    writeln!(body, "            os = \"windows\";").ok();
    writeln!(body, "        }} else {{").ok();
    writeln!(body, "            os = \"linux\";").ok();
    writeln!(body, "        }}").ok();
    writeln!(body).ok();
    writeln!(body, "        return os + \"-\" + arch;").ok();
    writeln!(body, "    }}").ok();
    writeln!(body).ok();

    // Generate method handles for free functions.
    // All functions get handles regardless of is_async — the FFI layer always exposes
    // synchronous C functions, and the Java async wrapper delegates to the sync method.
    for func in &api.functions {
        let ffi_name = format!("{}_{}", prefix, func.name.to_lowercase());
        let return_layout = gen_ffi_layout(&func.return_type);
        let param_layouts: Vec<String> = func.params.iter().map(|p| gen_ffi_layout(&p.ty)).collect();

        let layout_str = gen_function_descriptor(&return_layout, &param_layouts);

        let handle_name = format!("{}_{}", prefix.to_uppercase(), func.name.to_uppercase());

        writeln!(
            body,
            "    static final MethodHandle {} = LINKER.downcallHandle(",
            handle_name
        )
        .ok();
        writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", ffi_name).ok();
        writeln!(body, "        {}", layout_str).ok();
        writeln!(body, "    );").ok();
    }

    // free_string handle for releasing FFI-allocated strings
    {
        let free_name = format!("{}_free_string", prefix);
        let handle_name = format!("{}_FREE_STRING", prefix.to_uppercase());
        writeln!(body).ok();
        writeln!(
            body,
            "    static final MethodHandle {} = LINKER.downcallHandle(",
            handle_name
        )
        .ok();
        writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", free_name).ok();
        writeln!(body, "        FunctionDescriptor.ofVoid(ValueLayout.ADDRESS)").ok();
        writeln!(body, "    );").ok();
    }

    // Error handling — use the FFI's last_error_code and last_error_context symbols
    {
        writeln!(
            body,
            "    static final MethodHandle {}_LAST_ERROR_CODE = LINKER.downcallHandle(",
            prefix.to_uppercase()
        )
        .ok();
        writeln!(body, "        LIB.find(\"{}_last_error_code\").orElseThrow(),", prefix).ok();
        writeln!(body, "        FunctionDescriptor.of(ValueLayout.JAVA_INT)").ok();
        writeln!(body, "    );").ok();

        writeln!(
            body,
            "    static final MethodHandle {}_LAST_ERROR_CONTEXT = LINKER.downcallHandle(",
            prefix.to_uppercase()
        )
        .ok();
        writeln!(
            body,
            "        LIB.find(\"{}_last_error_context\").orElseThrow(),",
            prefix
        )
        .ok();
        writeln!(body, "        FunctionDescriptor.of(ValueLayout.ADDRESS)").ok();
        writeln!(body, "    );").ok();
    }

    // Track emitted free handles to avoid duplicates (a type may appear both as
    // a function return type AND as an opaque type).
    let mut emitted_free_handles: AHashSet<String> = AHashSet::new();

    // Build the set of opaque type names so we can pick the right accessor below.
    let opaque_type_names: AHashSet<String> = api
        .types
        .iter()
        .filter(|t| t.is_opaque)
        .map(|t| t.name.clone())
        .collect();

    // Accessor handles for Named return types (struct pointer → field accessor + free)
    for func in &api.functions {
        if let TypeRef::Named(name) = &func.return_type {
            let type_snake = name.to_snake_case();
            let type_upper = type_snake.to_uppercase();
            let is_opaque = opaque_type_names.contains(name.as_str());

            if is_opaque {
                // Opaque handles: the caller wraps the pointer directly, no JSON needed.
                // No content accessor is emitted for opaque types.
            } else {
                // Non-opaque record types: use _to_json to serialize the full struct to JSON,
                // which the Java side then deserializes with ObjectMapper.
                // NOTE: _content returns only the markdown string field, not the full JSON.
                let to_json_handle = format!("{}_{}_TO_JSON", prefix.to_uppercase(), type_upper);
                let to_json_ffi = format!("{}_{}_to_json", prefix, type_snake);
                writeln!(body).ok();
                writeln!(
                    body,
                    "    static final MethodHandle {} = LINKER.downcallHandle(",
                    to_json_handle
                )
                .ok();
                writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", to_json_ffi).ok();
                writeln!(
                    body,
                    "        FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS)"
                )
                .ok();
                writeln!(body, "    );").ok();
            }

            // _free: (struct_ptr) -> void
            let free_handle = format!("{}_{}_FREE", prefix.to_uppercase(), type_upper);
            let free_ffi = format!("{}_{}_free", prefix, type_snake);
            if emitted_free_handles.insert(free_handle.clone()) {
                writeln!(body).ok();
                writeln!(
                    body,
                    "    static final MethodHandle {} = LINKER.downcallHandle(",
                    free_handle
                )
                .ok();
                writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", free_ffi).ok();
                writeln!(body, "        FunctionDescriptor.ofVoid(ValueLayout.ADDRESS)").ok();
                writeln!(body, "    );").ok();
            }
        }
    }

    // FROM_JSON + FREE handles for non-opaque Named types used as parameters.
    // These allow serializing a Java record to JSON and passing it to the FFI.
    let mut emitted_from_json_handles: AHashSet<String> = AHashSet::new();
    for func in &api.functions {
        for param in &func.params {
            // Handle both Named and Optional<Named> params
            let inner_name = match &param.ty {
                TypeRef::Named(n) => Some(n.clone()),
                TypeRef::Optional(inner) => {
                    if let TypeRef::Named(n) = inner.as_ref() {
                        Some(n.clone())
                    } else {
                        None
                    }
                }
                _ => None,
            };
            if let Some(name) = inner_name {
                if !opaque_type_names.contains(name.as_str()) {
                    let type_snake = name.to_snake_case();
                    let type_upper = type_snake.to_uppercase();

                    // _from_json: (char*) -> struct_ptr
                    let from_json_handle = format!("{}_{}_FROM_JSON", prefix.to_uppercase(), type_upper);
                    let from_json_ffi = format!("{}_{}_from_json", prefix, type_snake);
                    if emitted_from_json_handles.insert(from_json_handle.clone()) {
                        writeln!(body).ok();
                        writeln!(
                            body,
                            "    static final MethodHandle {} = LINKER.downcallHandle(",
                            from_json_handle
                        )
                        .ok();
                        writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", from_json_ffi).ok();
                        writeln!(
                            body,
                            "        FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS)"
                        )
                        .ok();
                        writeln!(body, "    );").ok();
                    }

                    // _free: (struct_ptr) -> void
                    let free_handle = format!("{}_{}_FREE", prefix.to_uppercase(), type_upper);
                    let free_ffi = format!("{}_{}_free", prefix, type_snake);
                    if emitted_free_handles.insert(free_handle.clone()) {
                        writeln!(body).ok();
                        writeln!(
                            body,
                            "    static final MethodHandle {} = LINKER.downcallHandle(",
                            free_handle
                        )
                        .ok();
                        writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", free_ffi).ok();
                        writeln!(body, "        FunctionDescriptor.ofVoid(ValueLayout.ADDRESS)").ok();
                        writeln!(body, "    );").ok();
                    }
                }
            }
        }
    }

    // Collect builder class names from record types with defaults, so we skip
    // opaque types that are superseded by a pure-Java builder class.
    let builder_class_names: AHashSet<String> = api
        .types
        .iter()
        .filter(|t| !t.is_opaque && !t.fields.is_empty() && t.has_default)
        .map(|t| format!("{}Builder", t.name))
        .collect();

    // Free handles for opaque types (handle pointer → void)
    for typ in api.types.iter().filter(|typ| !typ.is_trait) {
        if typ.is_opaque && !builder_class_names.contains(&typ.name) {
            let type_snake = typ.name.to_snake_case();
            let type_upper = type_snake.to_uppercase();
            let free_handle = format!("{}_{}_FREE", prefix.to_uppercase(), type_upper);
            let free_ffi = format!("{}_{}_free", prefix, type_snake);
            if emitted_free_handles.insert(free_handle.clone()) {
                writeln!(body).ok();
                writeln!(
                    body,
                    "    static final MethodHandle {} = LINKER.downcallHandle(",
                    free_handle
                )
                .ok();
                writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", free_ffi).ok();
                writeln!(body, "        FunctionDescriptor.ofVoid(ValueLayout.ADDRESS)").ok();
                writeln!(body, "    );").ok();
            }
        }
    }

    // Inject visitor FFI method handles when a trait bridge is configured.
    if has_visitor_bridge {
        body.push_str(&crate::gen_visitor::gen_native_lib_visitor_handles(prefix));
    }

    writeln!(body, "}}").ok();

    // Now assemble the file with only the imports that are actually used in the body.
    let mut out = String::with_capacity(body.len() + 512);

    out.push_str(&hash::header(CommentStyle::DoubleSlash));
    writeln!(out, "package {};", package).ok();
    writeln!(out).ok();
    if body.contains("Arena") {
        writeln!(out, "import java.lang.foreign.Arena;").ok();
    }
    if body.contains("FunctionDescriptor") {
        writeln!(out, "import java.lang.foreign.FunctionDescriptor;").ok();
    }
    if body.contains("Linker") {
        writeln!(out, "import java.lang.foreign.Linker;").ok();
    }
    if body.contains("MemorySegment") {
        writeln!(out, "import java.lang.foreign.MemorySegment;").ok();
    }
    if body.contains("SymbolLookup") {
        writeln!(out, "import java.lang.foreign.SymbolLookup;").ok();
    }
    if body.contains("ValueLayout") {
        writeln!(out, "import java.lang.foreign.ValueLayout;").ok();
    }
    if body.contains("MethodHandle") {
        writeln!(out, "import java.lang.invoke.MethodHandle;").ok();
    }
    // Imports required by the JAR-extraction native loader (always present).
    writeln!(out, "import java.net.URL;").ok();
    writeln!(out, "import java.nio.file.Files;").ok();
    writeln!(out, "import java.nio.file.Path;").ok();
    writeln!(out, "import java.nio.file.StandardCopyOption;").ok();
    writeln!(out, "import java.util.ArrayList;").ok();
    writeln!(out, "import java.util.Enumeration;").ok();
    writeln!(out, "import java.util.List;").ok();
    writeln!(out, "import java.util.jar.JarEntry;").ok();
    writeln!(out, "import java.util.jar.JarFile;").ok();
    writeln!(out).ok();

    out.push_str(&body);

    out
}