alef 0.20.1

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
//! Service-API codegen for the Java backend.
//!
//! Generates Java source files for service lifecycle and handler registration:
//! - Service class wrapping opaque owner handles (from JNI constructor/destructor)
//! - Registration methods accepting Java functional handlers (forwarded to native code)
//! - Entrypoint methods (run/finalize) driving the service lifecycle
//!
//! Java delegates all logic to Rust via JNI native symbols, with type marshalling
//! and handler object wrapping. All errors are propagated as Java exceptions.

use crate::core::backend::GeneratedFile;
use crate::core::config::ResolvedCrateConfig;
use crate::core::ir::{ApiSurface, EntrypointKind, ServiceDef, TypeRef};
use heck::{ToLowerCamelCase, ToSnakeCase, ToUpperCamelCase};
use std::path::PathBuf;

// ────────────────────────────────────────────────────────── helpers ──

/// Map TypeRef to Java parameter type.
fn java_type_for_metadata(ty: &TypeRef) -> String {
    match ty {
        TypeRef::String | TypeRef::Char => "String".to_owned(),
        TypeRef::Primitive(p) => {
            use crate::core::ir::PrimitiveType;
            match p {
                PrimitiveType::Bool => "boolean".to_owned(),
                PrimitiveType::U8 | PrimitiveType::I8 => "byte".to_owned(),
                PrimitiveType::U16 | PrimitiveType::I16 => "short".to_owned(),
                PrimitiveType::U32 | PrimitiveType::I32 => "int".to_owned(),
                PrimitiveType::U64 | PrimitiveType::I64 => "long".to_owned(),
                PrimitiveType::F32 => "float".to_owned(),
                PrimitiveType::F64 => "double".to_owned(),
                PrimitiveType::Usize | PrimitiveType::Isize => "long".to_owned(),
            }
        }
        TypeRef::Bytes => "byte[]".to_owned(),
        TypeRef::Unit => "void".to_owned(),
        _ => "Object".to_owned(),
    }
}

// ──────────────────────────────────────────────── Java Service Class ──

/// Generate the idiomatic Java service class wrapper.
///
/// The class exposes:
/// - Constructor that calls the native constructor, storing the returned owner handle
/// - Registration methods that accept functional handlers and pass them to native code
/// - Run/Finalize entrypoint methods that call the native entrypoint
/// - AutoCloseable interface with close() to free the owner handle
fn gen_service_class(_api: &ApiSurface, service: &ServiceDef, package: &str) -> String {
    let mut out = String::new();

    // File header
    out.push_str("// Auto-generated by alef — DO NOT EDIT\n\n");
    out.push_str(&format!("package {};\n\n", package));

    // Service class
    let class_name = &service.name;
    out.push_str("/**\n");
    out.push_str(&format!(" * Service wrapper for {}.\n", service.name));
    out.push_str(" */\n");
    out.push_str(&format!(
        "public class {} implements AutoCloseable {{\n\n",
        class_name
    ));

    // Private opaque owner handle field
    out.push_str("    private long ownerHandle;\n\n");

    // Constructor
    {
        out.push_str("    /**\n");
        out.push_str(&format!("     * Create a new {}.\n", service.name));
        out.push_str("     */\n");
        out.push_str(&format!("    public {}() {{\n", class_name));
        let service_snake = service.name.to_snake_case();
        out.push_str(&format!(
            "        this.ownerHandle = nativeConstructor{}();\n",
            service_snake.to_upper_camel_case()
        ));
        out.push_str("    }\n\n");
    }

    // Registration methods
    for reg in &service.registrations {
        let reg_method = &reg.method;
        let reg_method_camel = reg_method.to_upper_camel_case();
        let service_pascal = service.name.to_upper_camel_case();

        out.push_str("    /**\n");
        out.push_str(&format!("     * Register a handler for {}.\n", reg_method));
        out.push_str("     */\n");

        out.push_str(&format!(
            "    public int register{}{}(Callable handler",
            service_pascal, reg_method_camel
        ));

        // Add metadata parameters
        for meta_param in &reg.metadata_params {
            let java_type = java_type_for_metadata(&meta_param.ty);
            let param_name = meta_param.name.to_lower_camel_case();
            out.push_str(&format!(", {} {}", java_type, param_name));
        }

        out.push_str(") {\n");
        out.push_str(&format!(
            "        return nativeRegister{}{}(ownerHandle, handler",
            service_pascal, reg_method_camel
        ));

        // Pass metadata arguments
        for meta_param in &reg.metadata_params {
            let param_name = meta_param.name.to_lower_camel_case();
            out.push_str(&format!(", {}", param_name));
        }

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

    // Entrypoint methods
    for ep in &service.entrypoints {
        let ep_method = &ep.method;
        let ep_method_camel = ep_method.to_upper_camel_case();
        let service_pascal = service.name.to_upper_camel_case();

        out.push_str("    /**\n");
        out.push_str(&format!("     * {}.\n", ep_method));
        out.push_str("     */\n");

        let return_type = match ep.kind {
            EntrypointKind::Run => "void",
            EntrypointKind::Finalize => "long",
        };

        out.push_str(&format!(
            "    public {} {}(",
            return_type, ep_method
        ));

        // Add entrypoint parameters
        for (i, param) in ep.params.iter().enumerate() {
            if i > 0 {
                out.push_str(", ");
            }
            let java_type = java_type_for_metadata(&param.ty);
            let param_name = param.name.to_lower_camel_case();
            out.push_str(&format!("{} {}", java_type, param_name));
        }

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

        let call_prefix = if matches!(ep.kind, EntrypointKind::Finalize) {
            "return "
        } else {
            ""
        };

        out.push_str(&format!(
            "        {}nativeEntrypoint{}{}(ownerHandle",
            call_prefix, ep_method_camel, service_pascal
        ));

        // Pass entrypoint arguments
        for param in &ep.params {
            let param_name = param.name.to_lower_camel_case();
            out.push_str(&format!(", {}", param_name));
        }

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

    // AutoCloseable implementation
    let service_snake = service.name.to_snake_case();
    out.push_str("    @Override\n");
    out.push_str("    public void close() {\n");
    out.push_str(&format!(
        "        if (ownerHandle != 0L) {{\n            nativeFree{}(ownerHandle);\n            ownerHandle = 0L;\n        }}\n",
        service_snake.to_upper_camel_case()
    ));
    out.push_str("    }\n\n");

    // Native method declarations
    out.push_str("    // ─── Native method declarations ───\n\n");

    // Constructor native
    out.push_str("    /**\n");
    out.push_str("     * Allocate a new service instance via JNI.\n");
    out.push_str("     *\n");
    out.push_str(&format!(
        "     * Maps to: Java_com_example_constructor_{service_snake}()\n"
    ));
    out.push_str("     */\n");
    out.push_str(&format!(
        "    private static native long nativeConstructor{}();\n\n",
        service_snake.to_upper_camel_case()
    ));

    // Destructor native
    out.push_str("    /**\n");
    out.push_str("     * Free the service instance via JNI.\n");
    out.push_str("     *\n");
    out.push_str(&format!(
        "     * Maps to: Java_com_example_free_{service_snake}(env, class, handle)\n"
    ));
    out.push_str("     */\n");
    out.push_str(&format!(
        "    private static native void nativeFree{}(long handle);\n\n",
        service_snake.to_upper_camel_case()
    ));

    // Registration natives
    for reg in &service.registrations {
        let service_pascal = service.name.to_upper_camel_case();
        let reg_method_camel = reg.method.to_upper_camel_case();

        out.push_str("    /**\n");
        out.push_str(&format!(
            "     * Register a handler for {} via JNI.\n",
            reg.method
        ));
        out.push_str("     *\n");
        out.push_str(&format!(
            "     * Maps to: Java_com_example_register{}{}(...)\n",
            service_pascal, reg_method_camel
        ));
        out.push_str("     */\n");

        out.push_str(&format!(
            "    private static native int nativeRegister{}{}(long ownerHandle, Callable handler",
            service_pascal, reg_method_camel
        ));

        for meta_param in &reg.metadata_params {
            let java_type = java_type_for_metadata(&meta_param.ty);
            out.push_str(&format!(", {} {}", java_type, meta_param.name));
        }

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

    // Entrypoint natives
    for ep in &service.entrypoints {
        let service_pascal = service.name.to_upper_camel_case();
        let ep_method_camel = ep.method.to_upper_camel_case();

        let return_type = match ep.kind {
            EntrypointKind::Run => "void",
            EntrypointKind::Finalize => "long",
        };

        out.push_str("    /**\n");
        out.push_str(&format!(
            "     * Drive {} entrypoint via JNI.\n",
            ep.method
        ));
        out.push_str("     *\n");
        out.push_str(&format!(
            "     * Maps to: Java_com_example_{}{}(env, class, ownerHandle, ...)\n",
            ep.method, service_pascal
        ));
        out.push_str("     */\n");

        out.push_str(&format!(
            "    private static native {} nativeEntrypoint{}{}(long ownerHandle",
            return_type, ep_method_camel, service_pascal
        ));

        for param in &ep.params {
            let java_type = java_type_for_metadata(&param.ty);
            out.push_str(&format!(", {} {}", java_type, param.name));
        }

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

    out.push_str("}\n");

    out
}

/// Generate the @FunctionalInterface Callable interface.
///
/// A simple interface that handlers must implement to be passed to registration methods.
fn gen_callable_interface(package: &str) -> String {
    let mut out = String::new();

    out.push_str("// Auto-generated by alef — DO NOT EDIT\n\n");
    out.push_str(&format!("package {};\n\n", package));

    out.push_str("/**\n");
    out.push_str(" * Functional interface for service handlers.\n");
    out.push_str(" *\n");
    out.push_str(" * Implementations receive a JSON request string and return a JSON response string.\n");
    out.push_str(" */\n");
    out.push_str("@FunctionalInterface\n");
    out.push_str("public interface Callable {\n");
    out.push_str("    /**\n");
    out.push_str("     * Handle a request.\n");
    out.push_str("     *\n");
    out.push_str("     * @param request JSON request string\n");
    out.push_str("     * @return JSON response string\n");
    out.push_str("     */\n");
    out.push_str("    String handle(String request);\n");
    out.push_str("}\n");

    out
}

// ──────────────────────────────────────────────── public entry point ──

/// Generate all service-API files for the Java backend.
///
/// Returns Java source files:
/// - One service class per [`ServiceDef`]
/// - One Callable interface (shared)
pub fn generate(api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
    if api.services.is_empty() {
        return Ok(vec![]);
    }

    let package = config.java_package();
    let package_path = package.replace('.', "/");

    let output_dir = config
        .output_for("java")
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or_else(|| "packages/java/src/main/java/".to_string());

    let base_path = if output_dir.ends_with(&package_path) || output_dir.ends_with(&format!("{}/", package_path)) {
        PathBuf::from(&output_dir)
    } else {
        PathBuf::from(&output_dir).join(&package_path)
    };

    let mut files = Vec::new();

    // Generate one service class per service
    for service in &api.services {
        let service_class = gen_service_class(api, service, &package);
        files.push(GeneratedFile {
            path: base_path.join(format!("{}.java", service.name)),
            content: service_class,
            generated_header: false, // Header already included
        });
    }

    // Generate Callable interface (once, shared across all services)
    files.push(GeneratedFile {
        path: base_path.join("Callable.java"),
        content: gen_callable_interface(&package),
        generated_header: false,
    });

    Ok(files)
}

// ───────────────────────────────────────────────────────────────────── tests ──

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::ir::{
        EntrypointDef, EntrypointKind, HandlerContractDef, MethodDef, ParamDef, RegistrationDef, ServiceDef, TypeRef,
    };

    /// Construct a minimal but realistic [`ApiSurface`] that exercises:
    /// - A service with a constructor, one registration, and Run entrypoint
    /// - One [`HandlerContractDef`] with wire request/response DTO names
    fn make_fixture_surface() -> ApiSurface {
        let constructor = MethodDef {
            name: "new".to_owned(),
            params: vec![],
            return_type: TypeRef::Unit,
            is_async: false,
            is_static: true,
            error_type: None,
            doc: "Create a new service owner.".to_owned(),
            receiver: None,
            sanitized: false,
            trait_source: None,
            returns_ref: false,
            returns_cow: false,
            return_newtype_wrapper: None,
            has_default_impl: false,
            binding_excluded: false,
            binding_exclusion_reason: None,
        };

        let registration = RegistrationDef {
            method: "add_handler".to_owned(),
            callback_param: "handler".to_owned(),
            callback_contract: "RequestHandler".to_owned(),
            metadata_params: vec![ParamDef {
                name: "path".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            receiver: Some(crate::core::ir::ReceiverKind::RefMut),
            return_type: TypeRef::Unit,
            error_type: None,
            doc: "Register a request handler.".to_owned(),
        };

        let run_ep = EntrypointDef {
            method: "run".to_owned(),
            kind: EntrypointKind::Run,
            is_async: true,
            params: vec![ParamDef {
                name: "addr".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            return_type: TypeRef::Unit,
            error_type: Some("ServiceError".to_owned()),
            doc: "Run the service.".to_owned(),
        };

        let service = ServiceDef {
            name: "TestService".to_owned(),
            rust_path: "my_crate::TestService".to_owned(),
            constructor,
            configurators: vec![],
            registrations: vec![registration],
            entrypoints: vec![run_ep],
            doc: "A test service owner.".to_owned(),
            cfg: None,
        };

        let dispatch_method = MethodDef {
            name: "handle".to_owned(),
            params: vec![ParamDef {
                name: "request".to_owned(),
                ty: TypeRef::Named("RequestData".to_owned()),
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            return_type: TypeRef::Named("ResponseData".to_owned()),
            is_async: true,
            is_static: false,
            error_type: Some("HandlerError".to_owned()),
            doc: "Dispatch a request.".to_owned(),
            receiver: Some(crate::core::ir::ReceiverKind::Ref),
            sanitized: false,
            trait_source: None,
            returns_ref: false,
            returns_cow: false,
            return_newtype_wrapper: None,
            has_default_impl: false,
            binding_excluded: false,
            binding_exclusion_reason: None,
        };

        let contract = HandlerContractDef {
            trait_name: "RequestHandler".to_owned(),
            rust_path: "my_crate::RequestHandler".to_owned(),
            dispatch: dispatch_method,
            optional_methods: vec![],
            wire_request_type: Some("RequestData".to_owned()),
            wire_response_type: Some("ResponseData".to_owned()),
            doc: "Async trait for handling requests.".to_owned(),
        };

        ApiSurface {
            crate_name: "my_crate".to_owned(),
            version: "0.1.0".to_owned(),
            services: vec![service],
            handler_contracts: vec![contract],
            ..ApiSurface::default()
        }
    }

    #[test]
    fn java_class_contains_service_class() {
        let surface = make_fixture_surface();
        let java = gen_service_class(&surface, &surface.services[0], "com.example");

        assert!(java.contains("public class TestService"));
        assert!(java.contains("implements AutoCloseable"));
        assert!(java.contains("private long ownerHandle"));
    }

    #[test]
    fn java_class_contains_constructor() {
        let surface = make_fixture_surface();
        let java = gen_service_class(&surface, &surface.services[0], "com.example");

        assert!(java.contains("public TestService()"));
        assert!(java.contains("nativeConstructorTestService()"));
    }

    #[test]
    fn java_class_contains_registration_method() {
        let surface = make_fixture_surface();
        let java = gen_service_class(&surface, &surface.services[0], "com.example");

        assert!(java.contains("public int registerTestServiceAddHandler("));
        assert!(java.contains("Callable handler"));
        assert!(java.contains("String path"));
        assert!(java.contains("nativeRegisterTestServiceAddHandler(ownerHandle, handler, path)"));
    }

    #[test]
    fn java_class_contains_native_register_declaration() {
        let surface = make_fixture_surface();
        let java = gen_service_class(&surface, &surface.services[0], "com.example");

        assert!(java.contains("private static native int nativeRegisterTestServiceAddHandler("));
        assert!(java.contains("long ownerHandle, Callable handler, String path"));
        assert!(
            java.contains("Maps to: Java_com_example_registerTestServiceAddHandler"),
            "native method should document JNI mapping: {}",
            java
        );
    }

    #[test]
    fn java_class_contains_entrypoint_method() {
        let surface = make_fixture_surface();
        let java = gen_service_class(&surface, &surface.services[0], "com.example");

        assert!(java.contains("public void run(String addr)"));
        assert!(java.contains("nativeEntrypointRunTestService(ownerHandle, addr)"));
    }

    #[test]
    fn java_class_contains_native_entrypoint_declaration() {
        let surface = make_fixture_surface();
        let java = gen_service_class(&surface, &surface.services[0], "com.example");

        assert!(java.contains("private static native void nativeEntrypointRunTestService("));
        assert!(java.contains("long ownerHandle, String addr"));
        assert!(
            java.contains("Maps to: Java_com_example_runTestService"),
            "native entrypoint should document JNI mapping"
        );
    }

    #[test]
    fn java_class_contains_close_method() {
        let surface = make_fixture_surface();
        let java = gen_service_class(&surface, &surface.services[0], "com.example");

        assert!(java.contains("@Override"));
        assert!(java.contains("public void close()"));
        assert!(java.contains("nativeFreeTestService(ownerHandle)"));
    }

    #[test]
    fn java_class_contains_native_free_declaration() {
        let surface = make_fixture_surface();
        let java = gen_service_class(&surface, &surface.services[0], "com.example");

        assert!(java.contains("private static native void nativeFreeTestService(long handle)"));
        assert!(java.contains("Maps to: Java_com_example_free_test_service"));
    }

    #[test]
    fn callable_interface_is_functional() {
        let iface = gen_callable_interface("com.example");

        assert!(iface.contains("@FunctionalInterface"));
        assert!(iface.contains("public interface Callable"));
        assert!(iface.contains("String handle(String request)"));
    }

    #[test]
    fn generate_returns_service_and_callable() {
        let surface = make_fixture_surface();
        let config = ResolvedCrateConfig {
            name: "my-crate".to_owned(),
            ..ResolvedCrateConfig::default()
        };

        let files = generate(&surface, &config).expect("generate should not fail");
        assert!(files.len() >= 2, "expected at least service class + Callable interface");

        let has_service_class = files.iter().any(|f| f.path.to_string_lossy().contains("TestService.java"));
        let has_callable = files.iter().any(|f| f.path.to_string_lossy().contains("Callable.java"));

        assert!(has_service_class, "expected TestService.java");
        assert!(has_callable, "expected Callable.java");
    }

    #[test]
    fn generate_returns_empty_for_no_services() {
        let surface = ApiSurface::default();
        let config = ResolvedCrateConfig {
            name: "my-crate".to_owned(),
            ..ResolvedCrateConfig::default()
        };

        let files = generate(&surface, &config).expect("generate should not fail");
        assert!(files.is_empty(), "expected no files for surface without services");
    }

    #[test]
    fn java_class_passes_all_metadata_params() {
        let mut surface = make_fixture_surface();
        let reg = &mut surface.services[0].registrations[0];

        // Add more metadata parameters
        reg.metadata_params.push(ParamDef {
            name: "method".to_owned(),
            ty: TypeRef::String,
            optional: false,
            default: None,
            ..ParamDef::default()
        });
        reg.metadata_params.push(ParamDef {
            name: "priority".to_owned(),
            ty: TypeRef::Primitive(crate::core::ir::PrimitiveType::I32),
            optional: false,
            default: None,
            ..ParamDef::default()
        });

        let java = gen_service_class(&surface, &surface.services[0], "com.example");

        // Check that the method signature includes all params
        assert!(
            java.contains("public int registerTestServiceAddHandler(Callable handler, String path, String method, int priority)"),
            "registration method must include all metadata parameters"
        );

        // Check that the native call passes all params
        assert!(
            java.contains("nativeRegisterTestServiceAddHandler(ownerHandle, handler, path, method, priority)"),
            "native call must pass all metadata parameters"
        );

        // Check native declaration
        assert!(
            java.contains("private static native int nativeRegisterTestServiceAddHandler(long ownerHandle, Callable handler, String path, String method, int priority)"),
            "native declaration must include all parameters"
        );
    }

    fn make_test_config() -> ResolvedCrateConfig {
        ResolvedCrateConfig {
            name: "my-crate".to_owned(),
            ..ResolvedCrateConfig::default()
        }
    }
}