alef 0.58.3

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
793
794
795
796
797
798
799
//! Tests for Rustler service-API generation.

use super::*;
use crate::core::config::ResolvedCrateConfig;
use crate::core::ir::{
    ApiSurface, EntrypointDef, EntrypointKind, HandlerContractDef, MethodDef, ParamDef, PrimitiveType, RegistrationDef,
    RegistrationVariantStyle, ServiceDef, TypeRef,
};

/// Construct a minimal but realistic [`ApiSurface`] that exercises:
/// - A service with a constructor, one configurator, one registration
///   (bound to an async handler contract), and Run + Finalize entrypoints.
/// - 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,
        version: Default::default(),
    };

    let configurator = MethodDef {
        name: "with_timeout".to_owned(),
        params: vec![ParamDef {
            name: "timeout_ms".to_owned(),
            ty: TypeRef::Primitive(PrimitiveType::U64),
            optional: false,
            default: None,
            ..ParamDef::default()
        }],
        return_type: TypeRef::Named("TestService".to_owned()),
        is_async: false,
        is_static: false,
        error_type: None,
        doc: "Set request timeout.".to_owned(),
        receiver: Some(crate::core::ir::ReceiverKind::RefMut),
        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()
            },
            ParamDef {
                name: "method".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 for a path and method.".to_owned(),
        variants: vec![],
        ..Default::default()
    };

    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 finalize_ep = EntrypointDef {
        method: "into_router".to_owned(),
        kind: EntrypointKind::Finalize,
        is_async: false,
        params: vec![],
        return_type: TypeRef::Named("Router".to_owned()),
        error_type: None,
        doc: "Consume and convert into a router.".to_owned(),
    };

    let service = ServiceDef {
        name: "TestService".to_owned(),
        rust_path: "my_crate::TestService".to_owned(),
        constructor,
        configurators: vec![configurator],
        registrations: vec![registration],
        entrypoints: vec![run_ep, finalize_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,
        version: Default::default(),
    };

    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()),
        dispatch_extra_params: vec![],
        wire_param_name: None,
        dispatch_return_type: None,
        response_adapter: None,
        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()
    }
}

/// `gen_service_ex` emits a module named after the service owner.
#[test]
fn elixir_output_contains_service_module() {
    let surface = make_fixture_surface();
    let output = gen_service_ex(&surface, "");
    assert!(
        output.contains("defmodule TestService do"),
        "expected `defmodule TestService do` in output:\n{output}"
    );
}

/// `gen_service_ex` emits a struct definition.
#[test]
fn elixir_output_contains_struct_definition() {
    let surface = make_fixture_surface();
    let output = gen_service_ex(&surface, "");
    assert!(
        output.contains("defstruct"),
        "expected `defstruct` in output:\n{output}"
    );
    assert!(
        output.contains(":registrations"),
        "expected `:registrations` field in output:\n{output}"
    );
}

/// `gen_service_ex` emits a constructor.
#[test]
fn elixir_output_contains_constructor() {
    let surface = make_fixture_surface();
    let output = gen_service_ex(&surface, "");
    assert!(output.contains("def new("), "expected `def new(` in output:\n{output}");
}

/// `gen_service_ex` emits configurator methods.
#[test]
fn elixir_output_contains_configurator() {
    let surface = make_fixture_surface();
    let output = gen_service_ex(&surface, "");
    assert!(
        output.contains("def with_timeout("),
        "expected `with_timeout` configurator:\n{output}"
    );
}

/// `gen_service_ex` emits a registration method.
#[test]
fn elixir_output_contains_registration() {
    let surface = make_fixture_surface();
    let output = gen_service_ex(&surface, "");
    assert!(
        output.contains("def add_handler("),
        "expected `add_handler` registration method:\n{output}"
    );
}

/// `gen_service_ex` emits a GenServer module.
#[test]
fn elixir_output_contains_genserver_module() {
    let surface = make_fixture_surface();
    let output = gen_service_ex(&surface, "");
    assert!(
        output.contains("defmodule TestService.Handler do"),
        "expected `TestService.Handler` GenServer:\n{output}"
    );
    assert!(
        output.contains("use GenServer"),
        "expected `use GenServer` in output:\n{output}"
    );
}

/// `gen_service_ex` emits the `run` entrypoint.
#[test]
fn elixir_output_contains_run_entrypoint() {
    let surface = make_fixture_surface();
    let output = gen_service_ex(&surface, "");
    assert!(output.contains("def run("), "expected `def run(` in output:\n{output}");
}

/// `gen_service_rs` emits the handler bridge struct.
#[test]
fn rust_output_contains_handler_bridge_struct() {
    let surface = make_fixture_surface();
    let config = make_test_config();
    let output = gen_service_rs(&surface, &config);
    assert!(
        output.contains("pub struct ElixirRequestHandlerBridge"),
        "expected `ElixirRequestHandlerBridge` struct:\n{output}"
    );
}

/// `gen_service_rs` emits the handler bridge trait impl.
#[test]
fn rust_output_contains_handler_bridge_impl() {
    let surface = make_fixture_surface();
    let config = make_test_config();
    let output = gen_service_rs(&surface, &config);
    assert!(
        output.contains("impl my_crate::RequestHandler for ElixirRequestHandlerBridge"),
        "expected trait impl:\n{output}"
    );
    assert!(
        output.contains("fn handle(") && output.contains("Pin<Box<dyn std::future::Future<Output"),
        "expected boxed-future dispatch method:\n{output}"
    );
}

/// `gen_service_rs` emits the `#[rustler::nif]` run entry point.
#[test]
fn rust_output_contains_nif_run() {
    let surface = make_fixture_surface();
    let config = make_test_config();
    let output = gen_service_rs(&surface, &config);
    assert!(
        output.contains("#[rustler::nif(schedule = \"DirtyCpu\")]"),
        "expected `#[rustler::nif(schedule = \"DirtyCpu\")]` attribute:\n{output}"
    );
    assert!(
        output.contains("pub fn test_service_run("),
        "expected `test_service_run` function:\n{output}"
    );
}

/// Full `generate()` call returns two files when services are non-empty.
#[test]
fn generate_returns_two_files_for_non_empty_services() {
    let surface = make_fixture_surface();
    let config = make_test_config();
    let files = generate(&surface, &config).expect("generate should not fail");
    assert_eq!(files.len(), 2, "expected 2 generated files, got {}", files.len());
    let paths: Vec<&str> = files
        .iter()
        .map(|f| f.path.file_name().unwrap().to_str().unwrap())
        .collect();
    assert!(paths.contains(&"service.rs"), "expected service.rs in output");
    assert!(paths.contains(&"service.ex"), "expected service.ex in output");
}

/// Full `generate()` returns empty for a surface with no services.
#[test]
fn generate_returns_empty_for_no_services() {
    let surface = ApiSurface::default();
    let config = make_test_config();
    let files = generate(&surface, &config).expect("generate should not fail");
    assert!(files.is_empty(), "expected no files for surface without services");
}

/// Elixir GenServer `handle_info` actually decodes args and calls handler.
///
/// Regression test: the Rust bridge sends `{:trait_call, ...}` via raw
/// `send`/`send_and_clear`, which BEAM delivers to `handle_info/2`, not
/// `handle_cast/2`. A `handle_cast`-based GenServer silently discards the
/// message (falls through to the default `handle_info` no-op), hanging the
/// request forever.
#[test]
fn elixir_genserver_handle_info_decodes_args_and_dispatches() {
    let surface = make_fixture_surface();
    let output = gen_service_ex(&surface, "");

    assert!(
        output.contains("def handle_info({:trait_call, method, args, reply_id}, registrations) do"),
        "expected trait_call dispatch on handle_info/2, not handle_cast/2:\n{output}"
    );
    assert!(
        !output.contains("handle_cast({:trait_call,"),
        "found trait_call dispatch on handle_cast/2 — raw send/2 is delivered to handle_info/2, not handle_cast/2:\n{output}"
    );

    assert!(
        output.contains("decode_args_and_dispatch(method, args, registrations)"),
        "expected decode_args_and_dispatch call in handle_info:\n{output}"
    );

    assert!(
        output.contains("Native.complete_trait_call(reply_id, response)"),
        "expected Native.complete_trait_call(reply_id, response) call:\n{output}"
    );

    assert!(
        !output.contains("simplified stub"),
        "found 'simplified stub' comment — dispatch should not be stubbed:\n{output}"
    );
    assert!(
        !output.contains("placeholder"),
        "found unsupported comment in dispatch logic:\n{output}"
    );
    assert!(
        !output.contains("# This is a simplified stub"),
        "found stub marker in dispatch:\n{output}"
    );
}

/// Elixir GenServer dispatch helper receives a native args map and calls the registered handler.
#[test]
fn elixir_genserver_dispatch_helper_invokes_handler() {
    let surface = make_fixture_surface();
    let output = gen_service_ex(&surface, "");

    assert!(
        output.contains("defp decode_args_and_dispatch(method, args, registrations) do"),
        "expected decode_args_and_dispatch helper function:\n{output}"
    );

    assert!(
        !output.contains("Jason.decode"),
        "args must arrive as a native map, not be Jason.decode'd:\n{output}"
    );

    assert!(
        output.contains("response = handler.(args)"),
        "expected handler.(args) invocation:\n{output}"
    );

    assert!(
        output.contains("Jason.encode(response)"),
        "expected Jason.encode(response) in dispatch:\n{output}"
    );

    assert!(
        output.contains("defp find_handler"),
        "expected find_handler helper function:\n{output}"
    );
}

/// Rust NIF parses registrations and constructs service owner.
#[test]
fn rust_nif_parses_registrations_and_constructs_owner() {
    let surface = make_fixture_surface();
    let config = make_test_config();
    let output = gen_service_rs(&surface, &config);

    assert!(
        output.contains("let registration_list: Vec<rustler::Term<'_>> = registrations"),
        "expected registration list parsing in NIF:\n{output}"
    );

    assert!(
        output.contains("let mut owner = my_crate::TestService::new()"),
        "expected owner construction in NIF:\n{output}"
    );

    assert!(
        output.contains("for reg_entry in registration_list"),
        "expected registration iteration in NIF:\n{output}"
    );

    assert!(
        !output.contains("placeholder: parse registrations"),
        "found placeholder in registration parsing — should be implemented:\n{output}"
    );
    assert!(
        !output.contains("For now, return a stub"),
        "found stub return in NIF — should be fully implemented:\n{output}"
    );
}

/// No empty-JSON or stub responses in generated code.
///
/// Verifies that the Rust NIF actually invokes `owner.run(...)` or `owner.finalize(...)`
/// and does not emit stub placeholder responses.
#[test]
fn no_stub_responses_in_generated_code() {
    let surface = make_fixture_surface();
    let config = make_test_config();

    let elixir_output = gen_service_ex(&surface, "");
    let rust_output = gen_service_rs(&surface, &config);

    assert!(
        !elixir_output.contains("response = {:ok, %{}}"),
        "found stub response {{:ok, %{{}}}} in Elixir generated code:\n{elixir_output}"
    );

    assert!(
        !elixir_output.contains("# Native.complete_trait_call"),
        "found commented-out complete_trait_call in Elixir:\n{elixir_output}"
    );

    assert!(
        !rust_output.contains("would be called here"),
        "found 'would be called here' stub comment in Rust NIF:\n{rust_output}"
    );
    assert!(
        !rust_output.contains("would happen here"),
        "found 'would happen here' stub comment in Rust NIF:\n{rust_output}"
    );

    assert!(
        rust_output.contains("owner.run(") || rust_output.contains("owner.finalize("),
        "Rust NIF should call owner.run(...) or owner.finalize(...), found neither:\n{rust_output}"
    );

    assert!(
        rust_output.contains("ElixirRequestHandlerBridge"),
        "Rust NIF should create handler bridge instances:\n{rust_output}"
    );

    assert!(
        !rust_output.contains("): Result<"),
        "found illegal if-let type ascription pattern '): Result<' in generated Rust:\n{rust_output}"
    );

    assert!(
        rust_output.contains("Term<'_>"),
        "expected lifetime-annotated Term<'_> in generated Rust NIF signature:\n{rust_output}"
    );
}

/// Verify that registration variant style is respected in generated Elixir code.
///
/// Regression test for issue #26: the rustler backend must pattern-match on
/// `RegistrationVariantStyle` and emit the appropriate Elixir registration forms.
#[test]
fn registration_variant_style_hybrid_emits_both_forms() {
    let mut surface = make_fixture_surface();
    let _config = make_test_config();

    surface.services[0].registrations[0]
        .variants
        .push(crate::core::ir::RegistrationVariant {
            name: "get".to_owned(),
            overrides: vec![crate::core::ir::RegistrationVariantOverride {
                param_name: "method".to_owned(),
                value_expr: "\"GET\"".to_owned(),
            }],
            wrapper_call: None,
            signature_params: vec![ParamDef {
                name: "path".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            doc: None,
            style: RegistrationVariantStyle::Hybrid,
            ..Default::default()
        });

    let elixir_output = gen_service_ex(&surface, "");

    assert!(
        elixir_output.contains("def get(app, path, handler) do"),
        "expected verb-decorator form 'def get(app, path, handler) do' in Elixir output:\n{elixir_output}"
    );

    assert!(
        elixir_output.contains("def get_decorator(app, path) do"),
        "expected builder form 'def get_decorator(app, path) do' in Elixir output:\n{elixir_output}"
    );
}

/// Verify that send_trait_call message is emitted in generated handler bridge.
///
/// Regression test for issue #119: the handler bridge must send the trait_call message
/// to the Elixir GenServer via OwnedEnv::send_and_clear, not just await silently.
#[test]
fn handler_bridge_sends_trait_call_message() {
    let surface = make_fixture_surface();
    let config = make_test_config();

    let rust_output = gen_service_rs(&surface, &config);

    assert!(
        rust_output.contains("OwnedEnv"),
        "expected OwnedEnv import in generated code"
    );

    assert!(
        rust_output.contains("env.send_and_clear(&pid"),
        "expected env.send_and_clear(&pid, ...) call in generated handler bridge:\n{rust_output}"
    );

    assert!(
        rust_output.contains("Atom::from_str(env, \"trait_call\")"),
        "expected atom::from_str for 'trait_call' in generated message:\n{rust_output}"
    );

    assert!(
        rust_output.contains("method_name"),
        "expected method_name variable in trait_call message"
    );

    assert!(
        rust_output.contains("request_json_clone"),
        "expected request JSON to be sent in trait_call message"
    );

    assert!(
        rust_output.contains("reply_id)"),
        "expected reply_id in trait_call tuple"
    );

    assert!(
        !rust_output.contains("// crate::nif_support::send_trait_call"),
        "found old commented-out send_trait_call in output — should be replaced with real call"
    );

    assert!(
        rust_output.contains("tokio::task::spawn_blocking(move || {"),
        "expected spawn_blocking to wrap the message send"
    );
}

/// Verify that Rust codegen emits core crate import + trait implementation.
/// This tests GAP 1 (core import) and GAP 3 (trait cast).
#[test]
fn rust_codegen_emits_core_import_and_trait_impl() {
    let surface = make_fixture_surface();
    let config = make_test_config();
    let rust_output = gen_service_rs(&surface, &config);

    assert!(
        rust_output.contains("use my_crate::*;"),
        "expected core crate wildcard import in gen_service_rs output:\n{rust_output}"
    );

    assert!(
        rust_output.contains("impl my_crate::RequestHandler for ElixirRequestHandlerBridge"),
        "expected trait impl for bridge in generated output:\n{rust_output}"
    );

    assert!(
        rust_output.contains("let handler: Arc<dyn my_crate::RequestHandler> = Arc::new(bridge);"),
        "expected handler trait cast in registration code:\n{rust_output}"
    );

    assert!(
        rust_output.contains("pub struct ElixirRequestHandlerBridge"),
        "expected ElixirRequestHandlerBridge struct definition:\n{rust_output}"
    );
}

/// Build on [`make_fixture_surface`] with a registration method named `"route"`
/// (the only name that triggers `HandlerWrapper` emission, see
/// `registration.rs:40`) whose sole metadata param is an **opaque** type
/// (`RouteBuilder`) present in `api.types`. `RouteBuilder` also carries one
/// chainable builder method (`&mut self -> Self`) so the `returns_self`
/// re-wrap path can be exercised.
///
/// Coverage gap this closes: `make_fixture_surface()` names its registration
/// `"add_handler"` with only string metadata params and an empty `api.types`,
/// so `service_api_handler_wrapper.ex.jinja` and the opaque-metadata `.ref`
/// unwrap path were entirely untested before this fixture existed.
fn make_route_fixture_surface() -> ApiSurface {
    let mut surface = make_fixture_surface();

    surface.services[0].registrations[0].method = "route".to_owned();
    // The wrapper gate dispatches on `handler_shape`, not the method name — set it
    // explicitly so this fixture keeps exercising `HandlerWrapper` emission. ~keep
    surface.services[0].registrations[0].handler_shape = crate::core::ir::HandlerShape::ContextObject;
    surface.services[0].registrations[0].metadata_params = vec![ParamDef {
        name: "builder".to_owned(),
        ty: TypeRef::Named("RouteBuilder".to_owned()),
        optional: false,
        default: None,
        ..ParamDef::default()
    }];

    let chainable_method = MethodDef {
        name: "request_timeout".to_owned(),
        params: vec![ParamDef {
            name: "ms".to_owned(),
            ty: TypeRef::Primitive(PrimitiveType::U64),
            optional: false,
            default: None,
            ..ParamDef::default()
        }],
        return_type: TypeRef::Named("RouteBuilder".to_owned()),
        is_async: false,
        is_static: false,
        error_type: None,
        doc: "Set the per-route request timeout.".to_owned(),
        receiver: Some(crate::core::ir::ReceiverKind::RefMut),
        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 route_builder_type = crate::core::ir::TypeDef {
        name: "RouteBuilder".to_owned(),
        rust_path: "my_crate::RouteBuilder".to_owned(),
        is_opaque: true,
        methods: vec![chainable_method],
        doc: "Builder for per-route metadata.".to_owned(),
        ..crate::core::ir::TypeDef::default()
    };
    surface.types.push(route_builder_type);

    surface
}

/// Opaque metadata params must be unwrapped with `.ref` in the registration
/// method's metadata tuple, matching the `rustler::ResourceArc<T>` the Rust
/// NIF side decodes (`rust.rs` / `registration_nif.rs`).
///
/// Regression test for defect 1: the Elixir side previously emitted the bare
/// param name (`{builder}`), passing the `%RouteBuilder{ref: ...}` wrapper
/// struct itself where Rustler expected the resource reference.
#[test]
fn elixir_opaque_metadata_param_unwraps_ref_in_registration_tuple() {
    let surface = make_route_fixture_surface();
    let output = gen_service_ex(&surface, "");

    assert!(
        output.contains("entry = {\"route\", {builder.ref}, handler_pid}"),
        "expected opaque metadata param unwrapped via `.ref` in the registration tuple:\n{output}"
    );
    assert!(
        !output.contains("entry = {\"route\", {builder}, handler_pid}"),
        "found raw wrapper struct (not `.ref`) passed as opaque metadata:\n{output}"
    );
}

/// A registration method named `"route"` emits the `HandlerWrapper` GenServer
/// and it dispatches `{:trait_call, ...}` on `handle_info/2`, matching the
/// raw-`send/2` wire contract used by `service_api_handler_bridge.rs.jinja`.
///
/// Regression test for defect 3: `HandlerWrapper` previously implemented
/// `handle_cast/2`, so the Rust bridge's `send_and_clear` message fell
/// through to the default `handle_info/2` and was silently discarded,
/// hanging every request that reached a closure-based handler forever.
#[test]
fn elixir_handler_wrapper_dispatches_on_handle_info() {
    let surface = make_route_fixture_surface();
    let output = gen_service_ex(&surface, "");

    assert!(
        output.contains("defmodule HandlerWrapper do"),
        "expected HandlerWrapper module for a `route`-named registration:\n{output}"
    );
    assert!(
        output.contains("def handle_info({:trait_call, _method, args_json, reply_id}, handler_fn) do"),
        "expected HandlerWrapper to dispatch trait_call on handle_info/2:\n{output}"
    );
    assert!(
        !output.contains("handle_cast({:trait_call,"),
        "found trait_call dispatch on handle_cast/2 in HandlerWrapper — raw send/2 lands on handle_info/2:\n{output}"
    );
}

/// Chainable opaque builder methods (`&mut self -> Self`) must re-wrap the
/// NIF's returned reference in `%__MODULE__{ref: ...}`, not return the bare
/// reference.
///
/// Regression test for defect 2: `returns_self` was gated on
/// `is_static && returns_self`, so every receiver-based chainable method
/// (the only kind builder chains actually use) fell through to the bare
/// `Native.<nif>(...)` call, degrading the struct to a raw `reference()` as
/// soon as any option was chained.
#[test]
fn elixir_opaque_builder_chain_method_rewraps_ref() {
    let surface = make_route_fixture_surface();
    let route_builder = surface.types.iter().find(|t| t.name == "RouteBuilder").unwrap();
    let config = make_test_config();

    let output = crate::backends::rustler::gen_bindings::helpers::gen_elixir_opaque_module(route_builder, "", &config);

    assert!(
        output.contains("ref = Native.routebuilder_request_timeout(obj.ref, ms)"),
        "expected chainable builder method to call the NIF and capture the returned ref:\n{output}"
    );
    assert!(
        output.contains("%__MODULE__{ref: ref}"),
        "expected chainable builder method to re-wrap the returned ref in the struct:\n{output}"
    );
    assert!(
        !output.contains("Native.routebuilder_request_timeout(obj.ref, ms)\n  end"),
        "found bare NIF call as the method body — chainable method must return the wrapped struct:\n{output}"
    );
}

/// The `HandlerWrapper` gate dispatches on `handler_shape`, not on the registration
/// method being literally named `"route"`. `make_fixture_surface()` names its
/// registration `"add_handler"` (matching alef's own dogfood config) — proving the
/// wrapper still renders here demonstrates the gate is decoupled from that
/// product-specific method name.
#[test]
fn elixir_handler_wrapper_emits_for_context_object_registration_named_add_handler() {
    let mut surface = make_fixture_surface();
    assert_eq!(surface.services[0].registrations[0].method, "add_handler");
    surface.services[0].registrations[0].handler_shape = crate::core::ir::HandlerShape::ContextObject;

    let output = gen_service_ex(&surface, "");

    assert!(
        output.contains("defmodule HandlerWrapper do"),
        "expected HandlerWrapper module for a context_object-shaped `add_handler` registration:\n{output}"
    );
    assert!(
        output.contains("def handle_info({:trait_call, _method, args_json, reply_id}, handler_fn) do"),
        "expected HandlerWrapper to dispatch trait_call on handle_info/2:\n{output}"
    );
}

/// A `bare_callable` registration (the default) must NOT emit `HandlerWrapper` —
/// only `context_object`-shaped registrations need the `Conn`-building adapter.
#[test]
fn elixir_handler_wrapper_absent_for_bare_callable_registration() {
    let surface = make_fixture_surface();
    assert_eq!(
        surface.services[0].registrations[0].handler_shape,
        crate::core::ir::HandlerShape::BareCallable
    );

    let output = gen_service_ex(&surface, "");

    assert!(
        !output.contains("defmodule HandlerWrapper do"),
        "bare_callable registration should not emit HandlerWrapper:\n{output}"
    );
}

fn make_test_config() -> ResolvedCrateConfig {
    use crate::core::config::resolved::ResolvedCrateConfig;
    ResolvedCrateConfig {
        name: "my-crate".to_owned(),
        ..ResolvedCrateConfig::default()
    }
}