alef 0.23.31

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
//! Service-API codegen for the Zig backend.
//!
//! Generates Zig glue that wraps the C FFI contract emitted by the FFI backend.
//!
//! **`service.zig`** — Zig service wrapper with:
//! - A service struct with constructor and registration methods.
//! - Extern function declarations matching the C FFI contract.
//! - A host-side handler wrapper marshaling JSON between Zig and C.
//! - Run and finalize methods that call the C entrypoints.
//!
//! Ownership: The Zig service owns a pointer to the C opaque handle.
//! The C side maintains lifetime semantics; Zig calls free() on cleanup.
//! Error handling: JSON serialization/deserialization errors are propagated.

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

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

/// Find the `HandlerContractDef` by trait name in the surface.
fn find_contract<'a>(api: &'a ApiSurface, trait_name: &str) -> Option<&'a HandlerContractDef> {
    api.handler_contracts.iter().find(|c| c.trait_name == trait_name)
}

/// Whether an entrypoint's return type can be represented over the C ABI as a function return.
/// Unit/primitive/string/bytes map to a status code or scalar; a `Named` type is representable only
/// when this surface wraps it (so it can cross as a `*{TypeName}` opaque). Anything else is not representable.
fn entrypoint_return_representable(ep: &crate::core::ir::EntrypointDef, api: &ApiSurface) -> bool {
    match &ep.return_type {
        TypeRef::Unit | TypeRef::String | TypeRef::Char | TypeRef::Primitive(_) | TypeRef::Bytes => true,
        TypeRef::Named(n) => api.types.iter().any(|t| t.name == *n),
        _ => false,
    }
}

/// Map a `TypeRef` to a Zig type string.
fn typeref_to_zig_type(ty: &TypeRef) -> String {
    match ty {
        TypeRef::String | TypeRef::Char => "[*:0]const u8".to_owned(),
        TypeRef::Primitive(p) => {
            use crate::core::ir::PrimitiveType;
            match p {
                PrimitiveType::Bool => "bool".to_owned(),
                PrimitiveType::U8 => "u8".to_owned(),
                PrimitiveType::U16 => "u16".to_owned(),
                PrimitiveType::U32 => "u32".to_owned(),
                PrimitiveType::U64 => "u64".to_owned(),
                PrimitiveType::I8 => "i8".to_owned(),
                PrimitiveType::I16 => "i16".to_owned(),
                PrimitiveType::I32 => "i32".to_owned(),
                PrimitiveType::I64 => "i64".to_owned(),
                PrimitiveType::F32 => "f32".to_owned(),
                PrimitiveType::F64 => "f64".to_owned(),
                PrimitiveType::Usize => "usize".to_owned(),
                PrimitiveType::Isize => "isize".to_owned(),
            }
        }
        TypeRef::Bytes => "[*:0]const u8".to_owned(),
        TypeRef::Unit => "void".to_owned(),
        TypeRef::Named(n) => n.clone(),
        TypeRef::Json => "[:0]const u8".to_owned(),
        TypeRef::Path => "[:0]const u8".to_owned(),
        TypeRef::Duration => "u64".to_owned(),
        TypeRef::Optional(_) => "?*anyopaque".to_owned(),
        TypeRef::Vec(_) => "[*]anyopaque".to_owned(),
        TypeRef::Map(_, _) => "*anyopaque".to_owned(),
    }
}

fn service_param_decl(name: &str, zig_type: &str, multiline: bool) -> String {
    if multiline {
        format!(",\n        {name}: {zig_type}")
    } else {
        format!(", {name}: {zig_type}")
    }
}

fn service_arg(name: &str, ty: &TypeRef, api: &ApiSurface) -> String {
    match ty {
        TypeRef::Named(n) if api.types.iter().any(|t| t.name == *n) => format!(",\n            {name}._handle"),
        _ => format!(",\n            {name}"),
    }
}

// ──────────────────────────────────────────────── Zig service struct ──

/// Generate the Zig service wrapper module (`service.zig`).
///
/// For each service this emits:
/// - Extern declarations for the C FFI symbols (`_new`, `_free`, `_register_*`, `_ep_*`).
/// - A Zig `Service` struct with methods that call into C.
/// - Inline function wrappers for registration and run operations.
fn gen_service_zig(api: &ApiSurface, config: &ResolvedCrateConfig) -> String {
    let prefix = config.ffi_prefix();
    let prefix_lower = prefix.to_lowercase();
    let mut out = String::new();

    out.push_str("// Generated by alef. Do not edit by hand.\n\n");
    out.push_str("const std = @import(\"std\");\n");
    out.push_str("const c = @cImport(@cInclude(\"");
    out.push_str(&config.ffi_header_name());
    out.push_str("\"));\n\n");

    // The C FFI symbols are provided by the `@cImport`ed header (as `c.<symbol>`); no manual
    // `extern` redeclarations are needed (and they would duplicate / mistype the header's contract).

    // Emit Zig service structs and methods
    for service in &api.services {
        gen_service_struct(&mut out, service, api, &prefix, &prefix_lower);
    }

    out
}

/// Emit a Zig service struct and methods for one service.
fn gen_service_struct(out: &mut String, service: &ServiceDef, api: &ApiSurface, _prefix: &str, prefix_lower: &str) {
    let service_name = &service.name;
    let service_snake = service_name.to_snake_case();

    // Service struct wrapping the C opaque pointer. The owner is stored as an optional `*anyopaque`
    // (mirroring how this backend wraps every other opaque handle); the concrete C opaque type is
    // reached only through `@ptrCast` at each `c.<symbol>` call, so its cbindgen name is never named.
    out.push_str(&crate::backends::zig::template_env::render(
        "service_struct_open.jinja",
        minijinja::context! {
            service_name => service_name,
        },
    ));

    // Constructor
    out.push_str(&crate::backends::zig::template_env::render(
        "service_init.jinja",
        minijinja::context! {
            service_name => service_name,
            new_fn => format!("{prefix_lower}_{service_snake}_new"),
        },
    ));

    // Destructor
    out.push_str(&crate::backends::zig::template_env::render(
        "service_deinit.jinja",
        minijinja::context! {
            service_name => service_name,
            free_fn => format!("{prefix_lower}_{service_snake}_free"),
        },
    ));

    // Registration methods
    for reg in &service.registrations {
        gen_registration_method(out, service, reg, api, prefix_lower);
    }

    // Entrypoint methods
    for ep in &service.entrypoints {
        gen_entrypoint_method(out, service, ep, api, prefix_lower);
    }

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

/// Emit a Zig registration method wrapper.
fn gen_registration_method(
    out: &mut String,
    service: &ServiceDef,
    reg: &RegistrationDef,
    api: &ApiSurface,
    prefix_lower: &str,
) {
    let service_snake = service.name.to_snake_case();
    let reg_method_snake = reg.method.to_snake_case();
    let service_name = &service.name;

    // Find the contract
    let _contract = find_contract(api, &reg.callback_contract).expect("contract not found");

    // Metadata parameters (name-first Zig style)
    let mut params_decl = String::new();
    for meta_param in &reg.metadata_params {
        let zig_type = match &meta_param.ty {
            TypeRef::Named(n) if api.types.iter().any(|t| t.name == *n) => format!("*{}", n),
            ty => typeref_to_zig_type(ty),
        };
        params_decl.push_str(&service_param_decl(&meta_param.name, &zig_type, true));
    }

    // Metadata arguments: extract _handle from opaque Named params
    let mut args = String::new();
    for meta_param in &reg.metadata_params {
        args.push_str(&service_arg(&meta_param.name, &meta_param.ty, api));
    }
    out.push_str(&crate::backends::zig::template_env::render(
        "service_registration_method.jinja",
        minijinja::context! {
            doc => format!("Register a handler for method '{}'", reg.method),
            method_name => reg_method_snake,
            service_name => service_name,
            params_decl,
            c_fn => format!("{prefix_lower}_{service_snake}_register_{reg_method_snake}"),
            args,
        },
    ));

    // Emit registration variants (shortcut methods)
    for variant in &reg.variants {
        gen_registration_variant_method(out, service, variant, reg, api, prefix_lower);
    }
}

/// Emit a Zig registration variant shortcut method.
fn gen_registration_variant_method(
    out: &mut String,
    service: &ServiceDef,
    variant: &RegistrationVariant,
    _reg: &RegistrationDef,
    api: &ApiSurface,
    prefix_lower: &str,
) {
    let service_name = &service.name;
    let service_snake = service.name.to_snake_case();
    let variant_name = &variant.name;

    // Variant signature parameters
    let mut params_decl = String::new();
    for param in &variant.signature_params {
        let zig_type = match &param.ty {
            TypeRef::Named(n) if api.types.iter().any(|t| t.name == *n) => format!("*{}", n),
            ty => typeref_to_zig_type(ty),
        };
        params_decl.push_str(&service_param_decl(&param.name, &zig_type, true));
    }

    // Variant arguments: extract _handle from opaque Named params
    let mut args = String::new();
    for param in &variant.signature_params {
        args.push_str(&service_arg(&param.name, &param.ty, api));
    }
    let default_doc = format!("Register a handler for {variant_name}");
    out.push_str(&crate::backends::zig::template_env::render(
        "service_registration_method.jinja",
        minijinja::context! {
            doc => variant.doc.as_deref().unwrap_or(&default_doc),
            method_name => variant_name,
            service_name => service_name,
            params_decl,
            c_fn => format!("{prefix_lower}_{service_snake}_{variant_name}"),
            args,
        },
    ));
}

/// Emit a Zig entrypoint method wrapper.
fn gen_entrypoint_method(
    out: &mut String,
    service: &ServiceDef,
    ep: &crate::core::ir::EntrypointDef,
    api: &ApiSurface,
    prefix_lower: &str,
) {
    // Skip finalize entrypoints whose return type is not representable over the C ABI
    if matches!(ep.kind, EntrypointKind::Finalize) && !entrypoint_return_representable(ep, api) {
        return;
    }

    let service_snake = service.name.to_snake_case();
    let ep_name_snake = ep.method.to_snake_case();
    let ep_method = &ep.method;
    let service_name = &service.name;

    // Mirror the C ABI: the ffi entrypoint glue returns `*mut T` (an opaque pointer) only when its
    // return type is an opaque this surface wraps, otherwise an `i32` status code. So the Zig method
    // returns `?*anyopaque` for the opaque case and `c_int` for the status case.
    let returns_opaque = matches!(&ep.return_type, TypeRef::Named(n) if api.types.iter().any(|t| t.name == *n));
    let return_type = if returns_opaque { "?*anyopaque" } else { "c_int" };

    // Entrypoint parameters: opaque Named types are accepted as `*anyopaque` handles.
    let mut params_decl = String::new();
    for ep_param in &ep.params {
        let zig_type = match &ep_param.ty {
            TypeRef::Named(n) if api.types.iter().any(|t| t.name == *n) => "*anyopaque".to_owned(),
            ty => typeref_to_zig_type(ty),
        };
        params_decl.push_str(&service_param_decl(&ep_param.name, &zig_type, false));
    }

    // Entrypoint arguments: extract _handle from opaque Named params
    let mut args = String::new();
    for ep_param in &ep.params {
        args.push_str(&service_arg(&ep_param.name, &ep_param.ty, api));
    }
    out.push_str(&crate::backends::zig::template_env::render(
        "service_entrypoint_method.jinja",
        minijinja::context! {
            ep_method => ep_method,
            method_name => ep_name_snake,
            service_name => service_name,
            params_decl,
            return_type,
            null_return => if returns_opaque { "null" } else { "1" },
            returns_opaque,
            c_fn => format!("{prefix_lower}_{service_snake}_ep_{ep_name_snake}"),
            args,
        },
    ));
}

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

/// Generate all service-API files for the Zig backend.
///
/// Returns one `GeneratedFile` when services are present:
/// - `{output_dir}/service.zig`   — Zig service wrapper
pub fn generate(api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
    if api.services.is_empty() {
        return Ok(vec![]);
    }

    let module_name = config.name.replace('-', "_");
    let zig_code = gen_service_zig(api, config);

    let dir = crate::core::config::resolve_output_dir(None, &config.name, "packages/zig/src");
    let path = PathBuf::from(dir).join(format!("{}_service.zig", module_name));

    Ok(vec![GeneratedFile {
        path,
        content: zig_code,
        generated_header: true,
    }])
}

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

        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,
            },
            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_zig_produces_valid_zig() {
        let api = make_fixture_surface();
        let config = ResolvedCrateConfig {
            name: "test_crate".to_owned(),
            ..ResolvedCrateConfig::default()
        };

        let zig = gen_service_zig(&api, &config);

        // Verify that the generated Zig contains expected markers
        assert!(zig.contains("const std = @import(\"std\")"));
        assert!(zig.contains("const c = @cImport"));
        assert!(zig.contains("TestService"));
        assert!(zig.contains("pub fn init()"));
        assert!(
            zig.contains("pub fn deinit("),
            "Expected 'pub fn deinit(' but got:\n{}",
            zig
        );
    }

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

        let zig = gen_service_zig(&api, &config);

        // The service struct must be declared with an optional opaque owner
        assert!(zig.contains("pub const TestService = struct"));
        assert!(zig.contains("owner: ?*anyopaque"));
    }

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

        let zig = gen_service_zig(&api, &config);

        // No manual extern redeclarations — the C symbols come from the @cImport'd header as `c.<sym>`.
        assert!(!zig.contains("extern \"C\" fn"));
        assert!(zig.contains("c.test_crate_test_service_new()"));
        assert!(zig.contains("c.test_crate_test_service_free("));
        assert!(zig.contains("c.test_crate_test_service_register_add_handler("));

        // The callback parameter signature is still the FFI contract shape.
        assert!(zig.contains("fn (*anyopaque, [*:0]const u8) callconv(.C) [*:0]u8"));
    }

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

        let zig = gen_service_zig(&api, &config);

        // Registration method should be present
        assert!(zig.contains("pub fn add_handler("));
        assert!(zig.contains("self: *TestService"));
        assert!(zig.contains("callback: *const fn (*anyopaque, [*:0]const u8) callconv(.C) [*:0]u8"));
    }

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

        let zig = gen_service_zig(&api, &config);

        // Metadata param (path: string) should appear in the registration method signature
        assert!(
            zig.contains("path: [*:0]const u8"),
            "Expected 'path: [*:0]const u8' but got:\n{}",
            zig
        );
    }

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

        let zig = gen_service_zig(&api, &config);

        // Entrypoint method should be present
        assert!(zig.contains("pub fn run("));
        assert!(zig.contains("addr: [*:0]const u8"));
    }

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

        let files = generate(&api, &config).expect("generate should not fail");
        assert_eq!(files.len(), 1, "expected 1 generated file, got {}", files.len());

        let file = &files[0];
        assert!(file.path.to_string_lossy().ends_with("_service.zig"));
    }

    #[test]
    fn test_generate_returns_empty_for_no_services() {
        let surface = ApiSurface::default();
        let config = ResolvedCrateConfig {
            name: "test_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 test_registration_variants_emit_shortcut_methods() {
        let mut api = make_fixture_surface();

        // Add variants to the registration
        if let Some(reg) = api.services[0].registrations.get_mut(0) {
            reg.variants.push(RegistrationVariant {
                name: "get".to_owned(),
                overrides: vec![],
                wrapper_call: None,
                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(),
            });
            reg.variants.push(RegistrationVariant {
                name: "post".to_owned(),
                overrides: vec![],
                wrapper_call: None,
                signature_params: vec![ParamDef {
                    name: "path".to_owned(),
                    ty: TypeRef::String,
                    optional: false,
                    default: None,
                    ..ParamDef::default()
                }],
                doc: Some("Register a POST handler.".to_owned()),
                style: Default::default(),
            });
        }

        let config = ResolvedCrateConfig {
            name: "test_crate".to_owned(),
            ..ResolvedCrateConfig::default()
        };

        let zig = gen_service_zig(&api, &config);

        // Verify that variant methods are emitted
        assert!(zig.contains("pub fn get("), "Expected 'pub fn get(' in:\n{}", zig);
        assert!(zig.contains("pub fn post("), "Expected 'pub fn post(' in:\n{}", zig);
        assert!(zig.contains("Register a GET handler."));
        assert!(zig.contains("Register a POST handler."));
        // Verify that variant C symbols are called
        assert!(zig.contains("c.test_crate_test_service_get("));
        assert!(zig.contains("c.test_crate_test_service_post("));
    }
}