alef 0.36.2

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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
//! Service-API codegen for the Swift backend (bridge-based via swift-bridge 0.1.59).
//!
//! Generates two outputs per [`ServiceDef`] with non-empty registrations:
//!
//! 1. **Rust extern "Rust" declarations** — added to the `#[swift_bridge::bridge] mod ffi`
//!    block in `packages/swift/rust/src/lib.rs`:
//!    - `extern "Rust" { type <ServiceName>; }` — opaque type declaration
//!    - `extern "Rust" { #[swift_bridge(init)] fn new(...) -> <ServiceName>; }`
//!    - `extern "Rust" { fn <configurator>(...); }` per configurator
//!    - `extern "Rust" { fn <register>_via_callback(..., ctx: *mut c_void, callback: extern "C" fn(...) -> *mut u8) -> i32; }`
//!      per registration (C-callback shim)
//!    - `extern "Rust" { fn <run>(...) -> Result<(), String>; }` per entrypoint (blocking, not async)
//!
//! 2. **Swift wrapper class** at `Sources/<ModuleName>/<ServiceName>.swift`:
//!    - Public class wrapping the swift-bridge opaque type
//!    - Idiomatic Swift methods for constructor, configurators, registration (with closure boxing), and entrypoints
//!    - Handler boxes (reference type) to cross closures via C context pointers
//!    - @convention(c) trampolines for C callback interop

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

fn find_contract<'a>(api: &'a ApiSurface, trait_name: &str) -> Option<&'a HandlerContractDef> {
    api.handler_contracts
        .iter()
        .find(|contract| contract.trait_name == trait_name)
}

/// Format a multi-line Rust doc as a Swift `///` block at the given column
/// indent. Every non-blank line is prefixed with `/// `; blank lines stay as
/// bare `///` so paragraph breaks survive. Includes the trailing newline.
fn format_swift_comment(text: &str, indent: usize) -> String {
    let trimmed = text.trim();
    if trimmed.is_empty() {
        return String::new();
    }
    let pad = " ".repeat(indent);
    let mut out = String::new();
    for line in trimmed.lines() {
        if line.trim().is_empty() {
            out.push_str(&pad);
            out.push_str("///\n");
        } else {
            out.push_str(&pad);
            out.push_str("/// ");
            out.push_str(line);
            out.push('\n');
        }
    }
    out
}

/// 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 an opaque handle). Anything else is not representable.
///
/// Also rejects entrypoints whose source method was sanitized — the IR sanitizer maps unknown
/// foreign return types (e.g. `axum::Router`) to `TypeRef::String`, which would otherwise pass
/// the surface check but produce a bridge signature that doesn't match the real Rust method.
fn entrypoint_return_representable(
    ep: &crate::core::ir::EntrypointDef,
    service: &ServiceDef,
    api: &ApiSurface,
) -> bool {
    if let Some(svc_type) = api.types.iter().find(|t| t.name == service.name)
        && let Some(method) = svc_type.methods.iter().find(|m| m.name == ep.method)
        && method.sanitized
    {
        return false;
    }
    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 Swift type string for function parameters.
fn typeref_to_swift_type(ty: &TypeRef) -> String {
    match ty {
        TypeRef::String => "String".to_owned(),
        TypeRef::Char => "Character".to_owned(),
        TypeRef::Primitive(p) => {
            use crate::core::ir::PrimitiveType;
            match p {
                PrimitiveType::Bool => "Bool".to_owned(),
                PrimitiveType::U8 => "UInt8".to_owned(),
                PrimitiveType::U16 => "UInt16".to_owned(),
                PrimitiveType::U32 => "UInt32".to_owned(),
                PrimitiveType::U64 => "UInt64".to_owned(),
                PrimitiveType::I8 => "Int8".to_owned(),
                PrimitiveType::I16 => "Int16".to_owned(),
                PrimitiveType::I32 => "Int32".to_owned(),
                PrimitiveType::I64 => "Int64".to_owned(),
                PrimitiveType::F32 => "Float".to_owned(),
                PrimitiveType::F64 => "Double".to_owned(),
                PrimitiveType::Usize => "UInt".to_owned(),
                PrimitiveType::Isize => "Int".to_owned(),
            }
        }
        TypeRef::Bytes => "Data".to_owned(),
        TypeRef::Unit => "Void".to_owned(),
        TypeRef::Named(n) => n.clone(),
        _ => "String".to_owned(),
    }
}

/// Map TypeRef to a Rust FFI type string.
fn typeref_to_rust_ffi_type(ty: &TypeRef) -> String {
    match ty {
        TypeRef::String => "String".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::Named(n) => n.clone(),
        _ => "String".to_owned(),
    }
}

/// Collect unique wrapper-constructor extern declarations from all registration variants.
///
/// For each `WrapperConstructorCall` on a `RegistrationVariant` (e.g. `RouteBuilder::new(method, path)`),
/// this emits an extern "Rust" free function declaration like:
///   `fn route_builder_new(method: &Method, path: String) -> RouteBuilder`
///
/// This is needed because swift-bridge represents enums as opaque classes (not mirrored Swift enums),
/// so `Method.Get` is invalid Swift syntax. Instead, the variant shorthand methods call
/// `routeBuilderNew(try methodFromJson("\"Get\""), path)` and delegate to the base registration.
///
/// Returns a deduplicated list of minijinja context values for the template.
fn collect_wrapper_constructor_externs(service: &ServiceDef) -> Vec<minijinja::Value> {
    use crate::core::ir::WrapperConstructorArg;
    use std::collections::HashSet;

    let mut seen: HashSet<String> = HashSet::new();
    let mut result: Vec<minijinja::Value> = Vec::new();

    for reg in &service.registrations {
        for variant in &reg.variants {
            let Some(wc) = &variant.wrapper_call else { continue };
            let fn_snake = format!("{}_new", wc.wrapper_type_name.to_snake_case());
            if !seen.insert(fn_snake.clone()) {
                continue;
            }
            let fn_camel = fn_snake.to_lower_camel_case();

            let args: Vec<minijinja::Value> = wc
                .args
                .iter()
                .map(|arg| match arg {
                    WrapperConstructorArg::Fixed { param_name, value_expr } => {
                        let rust_type = if let Some(last_colon) = value_expr.rfind("::") {
                            if let Some(second_colon) = value_expr[..last_colon].rfind("::") {
                                value_expr[second_colon + 2..last_colon].to_string()
                            } else {
                                value_expr[..last_colon].to_string()
                            }
                        } else {
                            value_expr.clone()
                        };
                        minijinja::context! {
                            name => param_name,
                            rust_type => format!("&{rust_type}"),
                        }
                    }
                    WrapperConstructorArg::Free { param } => {
                        let rust_type = typeref_to_rust_ffi_type(&param.ty);
                        minijinja::context! {
                            name => &param.name,
                            rust_type => rust_type,
                        }
                    }
                })
                .collect();

            result.push(minijinja::context! {
                fn_snake => &fn_snake,
                fn_camel => fn_camel,
                wrapper_type_name => &wc.wrapper_type_name,
                wrapper_type_path => &wc.wrapper_type_path,
                constructor_method => &wc.constructor_method,
                args => args,
            });
        }
    }

    result
}

/// Generate Rust extern "Rust" declarations for a service (INSIDE the bridge module).
/// These are appended to the `#[swift_bridge::bridge] mod ffi { ... }` block in lib.rs.
/// Registration callbacks are excluded — they go outside the bridge via `generate_rust_callback_c_functions`.
///
/// Split into TWO blocks to work around swift-bridge 0.1.59 parse error ("expected path"):
/// Block 1: Type declaration + constructor
/// Block 2: Instance methods (configurators, entrypoints) using `associated_to` attribute
fn gen_service_rust_extern_blocks(service: &ServiceDef, api: &ApiSurface) -> String {
    let configurators: Vec<minijinja::Value> = service
        .configurators
        .iter()
        .map(|config| {
            let config_snake = config.name.to_snake_case();
            let config_camel = config_snake.to_lower_camel_case();
            minijinja::context! {
                name => &config_snake,
                camel => &config_camel,
            }
        })
        .collect();

    let entrypoints: Vec<minijinja::Value> = service
        .entrypoints
        .iter()
        .filter(|ep| {
            !matches!(ep.kind, crate::core::ir::EntrypointKind::Finalize)
                || entrypoint_return_representable(ep, service, api)
        })
        .map(|ep| {
            let ep_snake = ep.method.to_snake_case();
            let ep_camel = ep_snake.to_lower_camel_case();
            let params: Vec<minijinja::Value> = ep
                .params
                .iter()
                .map(|p| {
                    minijinja::context! {
                        name => &p.name,
                        rust_type => typeref_to_rust_ffi_type(&p.ty),
                    }
                })
                .collect();

            let return_type = match &ep.return_type {
                TypeRef::Unit => {
                    if ep.error_type.is_some() {
                        "String".to_owned()
                    } else {
                        "()".to_owned()
                    }
                }
                TypeRef::String => "String".to_owned(),
                _ => "String".to_owned(),
            };

            minijinja::context! {
                snake => &ep_snake,
                camel => &ep_camel,
                params => params,
                return_type => return_type,
            }
        })
        .collect();

    let mut out = crate::backends::swift::template_env::render(
        "rust_extern_service_type_and_constructor.rs.jinja",
        minijinja::context! {
            service_name => &service.name,
        },
    );

    let service_snake = service.name.to_snake_case();
    let service_camel = service_snake.to_lower_camel_case();

    let wrapper_constructors = collect_wrapper_constructor_externs(service);

    out.push_str(&crate::backends::swift::template_env::render(
        "rust_extern_service_methods.rs.jinja",
        minijinja::context! {
            service_name => &service.name,
            service_snake => &service_snake,
            service_camel => &service_camel,
            configurators => configurators,
            entrypoints => entrypoints,
            wrapper_constructors => wrapper_constructors,
        },
    ));

    out
}

/// Generate plain C functions for callback registration (OUTSIDE the bridge module).
/// These are emitted after the `#[swift_bridge::bridge] mod ffi { ... }` block closes.
fn gen_rust_callback_c_functions_for_service(api: &ApiSurface, service: &ServiceDef) -> String {
    let mut out = String::new();
    let source_crate = api.crate_name.replace('-', "_");
    let service_snake = service.name.to_snake_case();

    for reg in &service.registrations {
        let reg_snake = reg.method.to_snake_case();
        let contract = find_contract(api, &reg.callback_contract);
        let trait_path = contract
            .map(|c| {
                if c.rust_path.is_empty() {
                    format!("{source_crate}::{}", c.trait_name)
                } else {
                    c.rust_path.clone()
                }
            })
            .unwrap_or_else(|| format!("{source_crate}::{}", reg.callback_contract));
        let request_path = contract
            .and_then(|c| c.wire_request_type.as_deref())
            .map(|name| qualify_rust_type(name, &source_crate))
            .unwrap_or_else(|| "serde_json::Value".to_string());
        let response_path = contract
            .and_then(|c| c.wire_response_type.as_deref())
            .map(|name| qualify_rust_type(name, &source_crate))
            .unwrap_or_else(|| "serde_json::Value".to_string());
        let output_type = contract
            .and_then(|c| c.dispatch_return_type.as_deref())
            .map(str::to_owned)
            .unwrap_or_else(|| format!("Result<{response_path}, Box<dyn std::error::Error + Send + Sync>>"));
        let response_adapter = contract
            .and_then(|c| c.response_adapter.as_deref())
            .map(|adapter| format!("{adapter}(outcome)"))
            .unwrap_or_else(|| "outcome".to_string());
        let metadata_params: Vec<minijinja::Value> = reg
            .metadata_params
            .iter()
            .map(|mp| {
                let is_opaque_wrapper = matches!(&mp.ty, TypeRef::Named(_));
                minijinja::context! {
                    name => &mp.name,
                    rust_type => typeref_to_rust_ffi_type(&mp.ty),
                    is_opaque_wrapper => is_opaque_wrapper,
                }
            })
            .collect();

        out.push_str(&crate::backends::swift::template_env::render(
            "rust_extern_c_register_via_callback.rs.jinja",
            minijinja::context! {
                service_snake => &service_snake,
                reg_snake => &reg_snake,
                method_name => &reg.method,
                service_name => &service.name,
                source_crate => &source_crate,
                trait_path => &trait_path,
                request_path => &request_path,
                response_path => &response_path,
                output_type => &output_type,
                response_adapter => &response_adapter,
                metadata_params => metadata_params,
            },
        ));
    }

    out
}

/// Generate the idiomatic Swift service class (`Service.swift`).
///
/// Produces a Swift class that wraps the swift-bridge opaque type and exposes:
/// - A constructor that calls the swift-bridge `_new` function
/// - Configurator methods that chain (return self)
/// - Registration methods that accept Swift closures and wrap them via @convention(c) trampolines
/// - A `run(...)` method that calls the swift-bridge entrypoint
pub(super) fn gen_service_swift(api: &ApiSurface, service: &ServiceDef, config: &ResolvedCrateConfig) -> String {
    let mut out = String::new();

    let class_name = &service.name;
    let service_snake = class_name.to_snake_case();
    let service_camel = service_snake.to_lower_camel_case();

    out.push_str(&crate::backends::swift::template_env::render(
        "swift_file_header.swift.jinja",
        minijinja::Value::from(()),
    ));
    out.push_str("import RustBridge\n\n");

    let ffi_prefix = config
        .ffi
        .as_ref()
        .and_then(|f| f.prefix.as_deref())
        .unwrap_or(&config.name)
        .to_string();
    let ffi_decls = format!(
        "@_silgen_name(\"{}_server_config_from_json\")\n\
         private func _{}_server_config_from_json(_ json: UnsafePointer<CChar>) -> UnsafeMutableRawPointer?\n\n\
         @_silgen_name(\"{}_server_config_free\")\n\
         private func _{}_server_config_free(_ ptr: UnsafeMutableRawPointer?)\n\n\
         @_silgen_name(\"{}_app_config\")\n\
         private func _{}_app_config(_ app: UnsafeMutablePointer<OpaquePointer>, _ config: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?\n\n",
        ffi_prefix, ffi_prefix, ffi_prefix, ffi_prefix, ffi_prefix, ffi_prefix
    );
    out.push_str(&ffi_decls);

    out.push_str(
        "/// Errors thrown by service wrapper methods.\n\
         public enum ServiceError: Error {\n\
         \x20\x20\x20\x20/// The service handle was already consumed or never initialised.\n\
         \x20\x20\x20\x20case invalidHandle\n\
         \x20\x20\x20\x20/// The C-side registration call returned a non-zero status code.\n\
         \x20\x20\x20\x20case registrationFailed\n\
         \x20\x20\x20\x20/// The service runtime returned the given error envelope.\n\
         \x20\x20\x20\x20case runtime(String)\n\
         }\n\n",
    );

    for reg in &service.registrations {
        let reg_snake = reg.method.to_snake_case();
        let metadata_params: Vec<minijinja::Value> = reg
            .metadata_params
            .iter()
            .map(|mp| {
                let swift_ty = typeref_to_swift_type(&mp.ty);
                let bridge_ty = match &mp.ty {
                    TypeRef::Named(n) => format!("RustBridge.{n}"),
                    _ => swift_ty.clone(),
                };
                minijinja::context! {
                    name => &mp.name,
                    swift_type => bridge_ty,
                }
            })
            .collect();

        out.push_str(&crate::backends::swift::template_env::render(
            "swift_silgen_callback.swift.jinja",
            minijinja::context! {
                service_snake => &service_snake,
                reg_snake => &reg_snake,
                metadata_params => metadata_params,
            },
        ));
    }

    let doc = if !service.doc.is_empty() {
        format_swift_comment(&service.doc, 0)
    } else {
        String::new()
    };
    out.push_str(&crate::backends::swift::template_env::render(
        "swift_class_header.swift.jinja",
        minijinja::context! {
            class_name => class_name,
            doc => &doc,
        },
    ));

    out.push_str(&crate::backends::swift::template_env::render(
        "swift_init.swift.jinja",
        minijinja::context! {
            service_snake => &service_snake,
            service_camel => &service_camel,
            service_name => class_name,
        },
    ));

    out.push_str(&crate::backends::swift::template_env::render(
        "swift_deinit.swift.jinja",
        minijinja::Value::from(()),
    ));

    for config in &service.configurators {
        let config_name = &config.name;
        let config_camel = config_name.to_lower_camel_case();
        let doc = if !config.doc.is_empty() {
            format_swift_comment(&config.doc, 4)
        } else {
            String::new()
        };

        out.push_str(&crate::backends::swift::template_env::render(
            "swift_configurator.swift.jinja",
            minijinja::context! {
                service_snake => &service_snake,
                config_name => config_name,
                config_camel => &config_camel,
                doc => &doc,
            },
        ));
    }

    let ffi_prefix = config
        .ffi
        .as_ref()
        .and_then(|f| f.prefix.as_deref())
        .unwrap_or(&config.name)
        .to_string();
    out.push_str(&crate::backends::swift::template_env::render(
        "swift_config_method.swift.jinja",
        minijinja::context! {
            service_snake => &service_snake,
            ffi_prefix => &ffi_prefix,
        },
    ));

    for reg in &service.registrations {
        gen_registration_method(&mut out, service, reg, api, &service_snake);
    }

    for ep in &service.entrypoints {
        if matches!(ep.kind, crate::core::ir::EntrypointKind::Finalize)
            && !entrypoint_return_representable(ep, service, api)
        {
            continue;
        }
        gen_entrypoint_method(&mut out, service, ep, &service_snake);
    }

    out.push_str(&crate::backends::swift::template_env::render(
        "swift_class_footer.swift.jinja",
        minijinja::Value::from(()),
    ));

    out
}

fn gen_registration_method(
    out: &mut String,
    _service: &ServiceDef,
    reg: &RegistrationDef,
    _api: &ApiSurface,
    service_snake: &str,
) {
    let method_name = &reg.method;
    let method_camel = method_name.to_lower_camel_case();

    let meta_params: Vec<String> = reg
        .metadata_params
        .iter()
        .map(|p| {
            let swift_type = match &p.ty {
                TypeRef::Named(n) => format!("RustBridge.{n}"),
                _ => typeref_to_swift_type(&p.ty),
            };
            format!("{}: {}", p.name, swift_type)
        })
        .collect();

    let meta_sig = meta_params.join(", ");

    let doc = if !reg.doc.is_empty() {
        format_swift_comment(&reg.doc, 4)
    } else {
        String::new()
    };

    let metadata_params: Vec<minijinja::Value> = reg
        .metadata_params
        .iter()
        .map(|mp| {
            minijinja::context! {
                name => &mp.name,
            }
        })
        .collect();

    let service_camel = service_snake.to_lower_camel_case();
    out.push_str(&crate::backends::swift::template_env::render(
        "swift_registration.swift.jinja",
        minijinja::context! {
            doc => &doc,
            method_camel => &method_camel,
            meta_params => &meta_sig,
            service_snake => service_snake,
            service_camel => &service_camel,
            method_name => method_name,
            metadata_params => metadata_params,
        },
    ));

    for variant in &reg.variants {
        gen_registration_variant(out, service_snake, reg, variant);
    }
}

fn gen_registration_variant(
    out: &mut String,
    service_snake: &str,
    reg: &RegistrationDef,
    variant: &crate::core::ir::RegistrationVariant,
) {
    use crate::core::ir::WrapperConstructorArg;

    let variant_name = &variant.name;
    let service_camel = service_snake.to_lower_camel_case();

    let signature_params: Vec<minijinja::Value> = variant
        .signature_params
        .iter()
        .map(|p| {
            let swift_type = match &p.ty {
                TypeRef::Named(n) => format!("RustBridge.{n}"),
                _ => typeref_to_swift_type(&p.ty),
            };
            minijinja::context! {
                name => &p.name,
                swift_type => swift_type,
            }
        })
        .collect();

    let doc = if let Some(doc_str) = &variant.doc {
        format_swift_comment(doc_str, 4)
    } else {
        let default_doc = format!("Shortcut for `{}`.", reg.method);
        format_swift_comment(&default_doc, 4)
    };

    if let Some(wrapper_call) = &variant.wrapper_call {
        let factory_fn_camel = format!("{}_new", wrapper_call.wrapper_type_name.to_snake_case()).to_lower_camel_case();
        let factory_args: Vec<String> = wrapper_call
            .args
            .iter()
            .map(|arg| match arg {
                WrapperConstructorArg::Fixed {
                    param_name: _,
                    value_expr,
                } => {
                    if let Some(last_colon) = value_expr.rfind("::") {
                        let variant_str = &value_expr[last_colon + 2..];
                        if let Some(second_colon) = value_expr[..last_colon].rfind("::") {
                            let type_name = &value_expr[second_colon + 2..last_colon];
                            let factory_name = format!(
                                "{}FromJson",
                                type_name
                                    .chars()
                                    .next()
                                    .map(|c| c.to_lowercase().to_string())
                                    .unwrap_or_default()
                                    + &type_name[1..]
                            );
                            format!("try {factory_name}(\"\\\"{variant_str}\\\"\")")
                        } else {
                            format!("\"{variant_str}\"")
                        }
                    } else {
                        value_expr.clone()
                    }
                }
                WrapperConstructorArg::Free { param } => param.name.clone(),
            })
            .collect();
        let factory_args_str = factory_args.join(", ");
        let base_param_name = &wrapper_call.metadata_param;
        let base_method_camel = reg.method.to_lower_camel_case();

        out.push_str(&crate::backends::swift::template_env::render(
            "swift_registration_variant_delegate.swift.jinja",
            minijinja::context! {
                doc => &doc,
                variant_name => variant_name,
                signature_params => signature_params,
                factory_fn_camel => factory_fn_camel,
                factory_args_str => factory_args_str,
                wrapper_type_name => &wrapper_call.wrapper_type_name,
                base_param_name => base_param_name,
                base_method_camel => base_method_camel,
            },
        ));
    } else {
        let wrapper_call_args: Vec<String> = variant.signature_params.iter().map(|p| p.name.clone()).collect();

        out.push_str(&crate::backends::swift::template_env::render(
            "swift_registration_variant.swift.jinja",
            minijinja::context! {
                doc => &doc,
                variant_name => variant_name,
                signature_params => signature_params,
                service_snake => service_snake,
                service_camel => &service_camel,
                base_method_name => &reg.method,
                wrapper_call_args => wrapper_call_args,
            },
        ));
    }
}

fn gen_entrypoint_method(
    out: &mut String,
    _service: &ServiceDef,
    ep: &crate::core::ir::EntrypointDef,
    service_snake: &str,
) {
    let ep_method = &ep.method;
    let ep_camel = ep_method.to_lower_camel_case();

    let doc = if !ep.doc.is_empty() {
        format_swift_comment(&ep.doc, 4)
    } else {
        String::new()
    };

    let params: Vec<String> = ep
        .params
        .iter()
        .map(|p| {
            let swift_type = typeref_to_swift_type(&p.ty);
            format!("{}: {}", p.name, swift_type)
        })
        .collect();

    let param_sig = if params.is_empty() {
        String::new()
    } else {
        params.join(", ")
    };

    let return_type = if ep.return_type == TypeRef::Unit {
        "Void".to_owned()
    } else {
        typeref_to_swift_type(&ep.return_type)
    };

    let throws_kw = if ep.error_type.is_some() { " throws" } else { "" };

    let ep_params: Vec<minijinja::Value> = ep
        .params
        .iter()
        .map(|p| {
            minijinja::context! {
                name => &p.name,
            }
        })
        .collect();

    out.push_str(&crate::backends::swift::template_env::render(
        "swift_entrypoint.swift.jinja",
        minijinja::context! {
            doc => &doc,
            ep_camel => &ep_camel,
            param_sig => &param_sig,
            throws_kw => throws_kw,
            return_type => &return_type,
            service_snake => service_snake,
            ep_method => ep_method,
            params => ep_params,
            has_error => ep.error_type.is_some(),
            has_return_value => ep.return_type != TypeRef::Unit,
        },
    ));
}

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

    let mut files = Vec::new();

    for service in &api.services {
        if service.registrations.is_empty() {
            continue;
        }

        let module_name = config.swift_module();
        let base_dir =
            crate::core::config::resolve_output_dir(config.output_paths.get("swift"), &config.name, "packages/swift");
        let base_path = PathBuf::from(&base_dir);

        let path = if config.explicit_output.swift.is_some() {
            base_path.join(format!("{}.swift", service.name))
        } else {
            base_path
                .join("Sources")
                .join(&module_name)
                .join(format!("{}.swift", service.name))
        };

        let content = gen_service_swift(api, service, config);

        files.push(GeneratedFile {
            path,
            content,
            generated_header: true,
        });
    }

    Ok(files)
}

/// Generate Rust extern "Rust" blocks for service-API declarations.
/// These are inserted into the swift-bridge bridge module in the rust crate.
pub fn generate_rust_extern_blocks(api: &ApiSurface) -> anyhow::Result<Vec<String>> {
    let mut blocks = Vec::new();

    for service in &api.services {
        if service.registrations.is_empty() {
            continue;
        }
        blocks.push(gen_service_rust_extern_blocks(service, api));
    }

    Ok(blocks)
}

/// Generate plain C functions for callback registration (OUTSIDE the bridge module).
/// These are emitted after the `#[swift_bridge::bridge] mod ffi { ... }` block closes in lib.rs.
pub fn generate_rust_callback_c_functions(api: &ApiSurface) -> anyhow::Result<Vec<String>> {
    let mut funcs = Vec::new();

    for service in &api.services {
        if service.registrations.is_empty() {
            continue;
        }
        funcs.push(gen_rust_callback_c_functions_for_service(api, service));
    }

    Ok(funcs)
}

fn qualify_rust_type(type_name: &str, source_crate: &str) -> String {
    if type_name.contains("::") {
        type_name.to_string()
    } else {
        format!("{source_crate}::{type_name}")
    }
}

#[cfg(test)]
mod tests;