alef 0.25.33

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
use super::*;
use crate::core::ir::{
    EntrypointDef, EntrypointKind, HandlerContractDef, MethodDef, ParamDef, RegistrationDef, ServiceDef, TypeRef,
};

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,
        version: Default::default(),
    };

    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: Some("HandlerError".to_owned()),
        doc: "Register a request handler.".to_owned(),
        variants: vec![],
        ..Default::default()
    };

    let run_entrypoint = 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("IoError".to_owned()),
        doc: "Start the service.".to_owned(),
    };

    let handler_contract = HandlerContractDef {
        trait_name: "RequestHandler".to_owned(),
        rust_path: "my_crate::RequestHandler".to_owned(),
        dispatch: MethodDef {
            name: "handle".to_owned(),
            params: vec![ParamDef {
                name: "req".to_owned(),
                ty: TypeRef::Named("RequestData".to_owned()),
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            return_type: TypeRef::Named("Response".to_owned()),
            is_async: true,
            is_static: false,
            error_type: None,
            doc: "Handle 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,
            version: Default::default(),
        },
        optional_methods: vec![],
        wire_request_type: Some("RequestData".to_owned()),
        wire_response_type: Some("Response".to_owned()),
        dispatch_extra_params: vec![],
        wire_param_name: None,
        dispatch_return_type: None,
        response_adapter: None,
        doc: "Handler contract.".to_owned(),
    };

    ApiSurface {
        crate_name: "test_crate".to_owned(),
        version: "1.0.0".to_owned(),
        services: vec![ServiceDef {
            name: "TestService".to_owned(),
            rust_path: "my_crate::TestService".to_owned(),
            constructor,
            configurators: vec![],
            registrations: vec![registration],
            entrypoints: vec![run_entrypoint],
            doc: "Test service.".to_owned(),
            cfg: None,
        }],
        handler_contracts: vec![handler_contract],
        ..ApiSurface::default()
    }
}

#[test]
fn test_gen_service_rs_produces_valid_rust() {
    let api = make_fixture_surface();
    let config = ResolvedCrateConfig {
        name: "test_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };

    let rs = gen_service_rs(&api, &config);

    // Verify that the generated Rust contains expected FFI markers
    assert!(rs.contains("#[no_mangle]"));
    assert!(rs.contains("extern \"C\""));
    assert!(rs.contains("TestServiceOpaque"));
    assert!(rs.contains("test_service_new"));
    assert!(rs.contains("test_service_free"));
    assert!(rs.contains("FfiRequestHandlerBridge"));
    assert!(rs.contains("Pin<Box<dyn std::future::Future"));
}

#[test]
fn test_handler_bridge_struct_is_generated() {
    let api = make_fixture_surface();
    let config = ResolvedCrateConfig {
        name: "test_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };

    let rs = gen_service_rs(&api, &config);

    // The bridge must have callback and context fields
    assert!(rs.contains("struct FfiRequestHandlerBridge"));
    assert!(rs.contains("callback: extern \"C\" fn"));
    assert!(rs.contains("context: *mut c_void"));
}

#[test]
fn test_opaque_has_constructor_and_destructor() {
    let api = make_fixture_surface();
    let config = ResolvedCrateConfig {
        name: "test_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };

    let rs = gen_service_rs(&api, &config);

    // Constructor and destructor should be present
    assert!(rs.contains("pub extern \"C\" fn test_crate_test_service_new()"));
    assert!(rs.contains("pub extern \"C\" fn test_crate_test_service_free"));
}

#[test]
fn test_registration_function_exists() {
    let api = make_fixture_surface();
    let config = ResolvedCrateConfig {
        name: "test_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };

    let rs = gen_service_rs(&api, &config);

    // Registration function should be present for each registration
    assert!(rs.contains("test_crate_test_service_register_add_handler"));
    // The callback function pointer type is used in the handler bridge
    assert!(rs.contains("extern \"C\" fn(*mut c_void, *const c_char) -> *mut c_char"));
}

#[test]
fn test_entrypoint_function_exists() {
    let api = make_fixture_surface();
    let config = ResolvedCrateConfig {
        name: "test_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };

    let rs = gen_service_rs(&api, &config);

    // Entrypoint function should be present
    assert!(rs.contains("test_crate_test_service_ep_run"));
    assert!(rs.contains("tokio::runtime::Runtime"));
}

#[test]
fn test_service_header_declares_metadata_and_entrypoint_params() {
    let api = make_fixture_surface();
    let header = gen_service_h(&api, "test_crate");

    assert!(
        header.contains("handler_callback_t callback,\n    void* context,\n    const char* path\n);"),
        "registration metadata param missing from service header:\n{header}"
    );
    assert!(
        header.contains(
            "test_crate_test_service_ep_run(\n    test_crateTestServiceOpaque* owner,\n    const char* addr\n);"
        ),
        "entrypoint param missing from service header:\n{header}"
    );
}

// ── registration-variant tests ────────────────────────────────────────────

fn make_surface_with_variant() -> ApiSurface {
    use crate::core::ir::{
        ParamDef, RegistrationVariant, RegistrationVariantOverride, WrapperConstructorArg, WrapperConstructorCall,
    };

    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,
        version: Default::default(),
    };

    let get_variant = RegistrationVariant {
        name: "get".to_owned(),
        overrides: vec![RegistrationVariantOverride {
            param_name: "method".to_owned(),
            value_expr: "my_crate::Method::GET".to_owned(),
        }],
        wrapper_call: Some(WrapperConstructorCall {
            metadata_param: "builder".to_owned(),
            wrapper_type_path: "my_crate::RouteBuilder".to_owned(),
            wrapper_type_name: "RouteBuilder".to_owned(),
            constructor_method: "new".to_owned(),
            args: vec![
                WrapperConstructorArg::Fixed {
                    param_name: "method".to_owned(),
                    value_expr: "my_crate::Method::GET".to_owned(),
                },
                WrapperConstructorArg::Free {
                    param: ParamDef {
                        name: "path".to_owned(),
                        ty: TypeRef::String,
                        optional: false,
                        default: None,
                        ..ParamDef::default()
                    },
                },
            ],
        }),
        signature_params: vec![ParamDef {
            name: "path".to_owned(),
            ty: TypeRef::String,
            optional: false,
            default: None,
            ..ParamDef::default()
        }],
        doc: Some("Register a GET handler.".to_owned()),
        style: Default::default(),
        ..Default::default()
    };

    let registration = RegistrationDef {
        method: "add_route".to_owned(),
        callback_param: "handler".to_owned(),
        callback_contract: "RequestHandler".to_owned(),
        metadata_params: vec![ParamDef {
            name: "builder".to_owned(),
            ty: TypeRef::Named("RouteBuilder".to_owned()),
            optional: false,
            default: None,
            ..ParamDef::default()
        }],
        receiver: Some(crate::core::ir::ReceiverKind::RefMut),
        return_type: TypeRef::Unit,
        error_type: Some("HandlerError".to_owned()),
        doc: "Register a route.".to_owned(),
        variants: vec![get_variant],
        ..Default::default()
    };

    let handler_contract = HandlerContractDef {
        trait_name: "RequestHandler".to_owned(),
        rust_path: "my_crate::RequestHandler".to_owned(),
        dispatch: MethodDef {
            name: "handle".to_owned(),
            params: vec![ParamDef {
                name: "req".to_owned(),
                ty: TypeRef::Named("RequestData".to_owned()),
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            return_type: TypeRef::Named("Response".to_owned()),
            is_async: true,
            is_static: false,
            error_type: None,
            doc: "Handle 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,
            version: Default::default(),
        },
        optional_methods: vec![],
        wire_request_type: Some("RequestData".to_owned()),
        wire_response_type: Some("Response".to_owned()),
        dispatch_extra_params: vec![],
        wire_param_name: None,
        dispatch_return_type: None,
        response_adapter: None,
        doc: "Handler contract.".to_owned(),
    };

    ApiSurface {
        crate_name: "my_crate".to_owned(),
        version: "1.0.0".to_owned(),
        services: vec![ServiceDef {
            name: "App".to_owned(),
            rust_path: "my_crate::App".to_owned(),
            constructor,
            configurators: vec![],
            registrations: vec![registration],
            entrypoints: vec![],
            doc: "App service.".to_owned(),
            cfg: None,
        }],
        handler_contracts: vec![handler_contract],
        ..ApiSurface::default()
    }
}

#[test]
fn test_variant_fn_is_emitted() {
    let api = make_surface_with_variant();
    let config = ResolvedCrateConfig {
        name: "my_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };

    let rs = gen_service_rs(&api, &config);

    assert!(
        rs.contains("fn my_crate_app_get("),
        "expected variant fn my_crate_app_get not found in:\n{rs}"
    );
}

#[test]
fn test_variant_fn_has_no_mangle_and_extern_c() {
    let api = make_surface_with_variant();
    let config = ResolvedCrateConfig {
        name: "my_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };

    let rs = gen_service_rs(&api, &config);

    let variant_start = rs.find("fn my_crate_app_get(").expect("variant fn not found");
    let preamble = &rs[..variant_start];
    let preamble_tail = preamble.rsplit("#[no_mangle]").next().unwrap_or(preamble);
    assert!(
        preamble.contains("#[no_mangle]"),
        "#[no_mangle] must precede the variant fn"
    );
    assert!(
        preamble_tail.trim().starts_with("pub extern") || preamble_tail.trim().starts_with("pub unsafe extern"),
        "#[no_mangle] must directly precede the extern fn (intervening: `{preamble_tail}`)"
    );
}

#[test]
fn test_variant_fn_has_free_param_and_wrapper_construction() {
    let api = make_surface_with_variant();
    let config = ResolvedCrateConfig {
        name: "my_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };

    let rs = gen_service_rs(&api, &config);

    assert!(
        rs.contains("path: *const c_char"),
        "free param 'path' missing from variant signature"
    );
    assert!(
        rs.contains("my_crate::Method::GET"),
        "fixed arg my_crate::Method::GET missing from wrapper construction"
    );
    assert!(
        rs.contains("my_crate::RouteBuilder::new("),
        "wrapper constructor call not emitted"
    );
    assert!(
        rs.contains("owner_ref.add_route(builder, handler)"),
        "variant dispatch call must pass wrapper metadata before handler"
    );
}

#[test]
fn test_variant_fn_has_null_check_for_owner() {
    let api = make_surface_with_variant();
    let config = ResolvedCrateConfig {
        name: "my_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };

    let rs = gen_service_rs(&api, &config);

    let start = rs.find("fn my_crate_app_get(").expect("variant fn not found");
    let body = &rs[start..];
    assert!(
        body.contains("if owner.is_null()"),
        "owner null check missing from variant fn"
    );
}

#[test]
fn test_variant_without_wrapper_call_is_not_emitted() {
    use crate::core::ir::{ParamDef, RegistrationVariant, RegistrationVariantOverride};

    let constructor = MethodDef {
        name: "new".to_owned(),
        params: vec![],
        return_type: TypeRef::Unit,
        is_async: false,
        is_static: true,
        error_type: None,
        doc: String::new(),
        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,
        version: Default::default(),
    };

    let plain_variant = RegistrationVariant {
        name: "plain".to_owned(),
        overrides: vec![RegistrationVariantOverride {
            param_name: "path".to_owned(),
            value_expr: "\"/fixed\"".to_owned(),
        }],
        wrapper_call: None,
        signature_params: vec![],
        doc: None,
        style: Default::default(),
        ..Default::default()
    };

    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: String::new(),
        variants: vec![plain_variant],
        ..Default::default()
    };

    let handler_contract = HandlerContractDef {
        trait_name: "RequestHandler".to_owned(),
        rust_path: "my_crate::RequestHandler".to_owned(),
        dispatch: MethodDef {
            name: "handle".to_owned(),
            params: vec![],
            return_type: TypeRef::Unit,
            is_async: false,
            is_static: false,
            error_type: None,
            doc: String::new(),
            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,
            version: Default::default(),
        },
        optional_methods: vec![],
        wire_request_type: None,
        wire_response_type: None,
        dispatch_extra_params: vec![],
        wire_param_name: None,
        dispatch_return_type: None,
        response_adapter: None,
        doc: String::new(),
    };

    let api = ApiSurface {
        crate_name: "my_crate".to_owned(),
        version: "1.0.0".to_owned(),
        services: vec![ServiceDef {
            name: "App".to_owned(),
            rust_path: "my_crate::App".to_owned(),
            constructor,
            configurators: vec![],
            registrations: vec![registration],
            entrypoints: vec![],
            doc: String::new(),
            cfg: None,
        }],
        handler_contracts: vec![handler_contract],
        ..ApiSurface::default()
    };

    let config = ResolvedCrateConfig {
        name: "my_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };
    let rs = gen_service_rs(&api, &config);

    assert!(
        !rs.contains("fn my_crate_app_plain("),
        "plain variant without wrapper_call must not emit a C symbol"
    );
}

/// Configurator functions must take the owner's inner field out, call the
/// consuming method, and put the result back. The opaque handle stores the owner
/// as `Option<Box<OwnerType>>`, so the generator must emit
/// `let inner = match (*owner).inner.take() { Some(boxed) => *boxed, None => ... };`
/// followed by `(*owner).inner = Some(Box::new(inner.method(args)));`.
#[test]
fn configurator_function_unboxes_and_reboxes_inner() {
    use crate::core::ir::{MethodDef, ParamDef, ReceiverKind, ServiceDef, TypeRef};

    let configurator = MethodDef {
        name: "setup".to_owned(),
        params: vec![ParamDef {
            name: "opts".to_owned(),
            ty: TypeRef::Named("Options".to_owned()),
            optional: false,
            default: None,
            ..ParamDef::default()
        }],
        return_type: TypeRef::Named("Worker".to_owned()),
        is_async: false,
        is_static: false,
        error_type: None,
        doc: String::new(),
        receiver: Some(ReceiverKind::Owned),
        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,
        version: Default::default(),
    };
    let constructor = MethodDef {
        name: "new".to_owned(),
        params: vec![],
        return_type: TypeRef::Named("Worker".to_owned()),
        is_async: false,
        is_static: true,
        error_type: None,
        doc: String::new(),
        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,
        version: Default::default(),
    };
    let api = ApiSurface {
        crate_name: "worker_crate".to_owned(),
        version: "1.0.0".to_owned(),
        services: vec![ServiceDef {
            name: "Worker".to_owned(),
            rust_path: "worker_crate::Worker".to_owned(),
            constructor,
            configurators: vec![configurator],
            registrations: vec![],
            entrypoints: vec![],
            doc: String::new(),
            cfg: None,
        }],
        handler_contracts: vec![],
        ..ApiSurface::default()
    };
    let config = ResolvedCrateConfig {
        name: "worker_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };
    let rs = gen_service_rs(&api, &config);

    // The generated configurator function must appear with the correct symbol name.
    assert!(
        rs.contains("fn worker_crate_worker_setup("),
        "configurator fn must be emitted; got:\n{rs}"
    );
    // Must take the inner App out of the Option before calling the consuming method.
    assert!(
        rs.contains("let inner = match (*owner).inner.take()"),
        "configurator must `take()` owner.inner before calling the consuming method; got:\n{rs}"
    );
    // Must re-box the returned value and assign it back inside Some(...).
    assert!(
        rs.contains("(*owner).inner = Some(Box::new(inner.setup("),
        "configurator must re-box the result and assign to owner.inner; got:\n{rs}"
    );
}

/// Regression test for builder/config double-free bug (alef issue #TBD).
/// FFI registration functions that accept a builder or config pointer must
/// NOT transfer ownership (Box::from_raw) since the C caller still holds the
/// pointer and will call _free() or a deferred finalizer afterwards. Instead,
/// borrow the pointer as a reference (&*ptr).
///
/// Previously the emitted code was:
///   let builder = unsafe { *Box::from_raw(builder) };
/// which dropped the builder at function end, causing a double-free when
/// Java's finalizer or C's deferred _free() ran on the same pointer.
///
/// The fix borrows instead:
///   let builder = unsafe { &*builder };
/// The C caller retains ownership and responsibility for freeing.
#[test]
fn registration_function_does_not_consume_builder_ownership() {
    let api = make_fixture_surface();
    let config = ResolvedCrateConfig {
        name: "test_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };

    let rs = gen_service_rs(&api, &config);

    // The registration function must borrow the metadata params (path) as references,
    // not consume them with Box::from_raw.
    assert!(
        !rs.contains("*Box::from_raw(path)"),
        "registration function must not use Box::from_raw on metadata params; got:\n{rs}"
    );
    // String parameters are converted from *const c_char to owned String,
    // but any Named type (builder, config) must be borrowed.
    // Verify that path (a String param) uses the correct C-to-Rust conversion
    // (CStr::from_ptr), not a pointer-ownership transfer.
    assert!(
        rs.contains("CStr::from_ptr(path)"),
        "registration function must convert string params via CStr::from_ptr; got:\n{rs}"
    );
}

/// Regression test: when a registration carries a `TypeRef::Named` metadata
/// param backed by a public `TypeDef` (i.e. an opaque pointer with `_new` /
/// `_free` exports), the conversion borrows the pointer (`unsafe { &*ptr }`)
/// AND the call site clones the borrow so the consuming Rust API can take
/// the value by ownership.
///
/// The borrow alone (without `.clone()`) was introduced in 16279dba9 to fix a
/// double-free, but it broke compilation: downstream methods like
/// `App::route(builder: RouteBuilder, ...)` and `App::config(config:
/// ServerConfig) -> Self` consume `T` by value, so passing `&T` produced
/// `error[E0308]: mismatched types`. The fix is to emit `.clone()` at the
/// call site (every opaque type wired through this path must derive `Clone`).
///
/// This test fails if either:
///   - the borrow is missing (double-free regression — alef 0.25.5)
///   - the `.clone()` is missing on the call-site arg expression
///     (E0308 regression — alef 0.25.5..=0.25.18)
#[test]
fn registration_named_opaque_param_clones_borrowed_pointer_at_call_site() {
    use crate::core::ir::TypeDef;

    let mut api = make_surface_with_variant();
    // Register RouteBuilder as a public opaque type so the param-binding
    // arm `TypeRef::Named(n) if api.types.iter().any(|t| t.name == *n)` fires.
    api.types.push(TypeDef {
        name: "RouteBuilder".to_owned(),
        rust_path: "my_crate::RouteBuilder".to_owned(),
        is_opaque: true,
        is_clone: true,
        ..TypeDef::default()
    });
    let config = ResolvedCrateConfig {
        name: "my_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };

    let rs = gen_service_rs(&api, &config);

    // The borrow must be present (no Box::from_raw double-free).
    assert!(
        rs.contains("let builder = unsafe { &*builder };"),
        "opaque-pointer metadata param `builder` must be borrowed via &*ptr; got:\n{rs}"
    );
    // The registration-dispatch call site must clone the borrow so the
    // consuming `route()` API receives `RouteBuilder` by value, not
    // `&RouteBuilder`. (Variant fns construct their own owned builder via
    // `RouteBuilder::new(...)` and intentionally pass it by value without
    // `.clone()` — that path is unaffected.)
    assert!(
        rs.contains(".add_route(builder.clone(), handler)"),
        "opaque-pointer metadata param `builder` must be `.clone()`d at the \
         registration dispatch call site so the consuming Rust API receives \
         `T`, not `&T`; got:\n{rs}"
    );
    // Belt-and-braces: ensure the broken double-free path (Box::from_raw on
    // the builder pointer) did not regress.
    assert!(
        !rs.contains("*Box::from_raw(builder)"),
        "opaque-pointer metadata param `builder` must not be consumed via \
         `Box::from_raw` — the C caller still holds the pointer; got:\n{rs}"
    );
}