alef 0.79.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
use crate::backends::swift::naming::swift_rust_shim_ident as swift_ident;
use crate::backends::swift::type_map::SwiftMapper;
use crate::core::ir::{ApiSurface, EnumDef, FunctionDef, PrimitiveType, TypeRef};
use heck::ToLowerCamelCase;

pub(super) fn emit_json_string_overloads(
    api: &ApiSurface,
    exclude_types: &std::collections::HashSet<String>,
    out: &mut String,
) {
    use heck::AsSnakeCase;

    let json_overload_candidates: Vec<(&FunctionDef, usize, &str)> = api
        .functions
        .iter()
        .flat_map(|func| {
            if !func.is_async
                && func.name.ends_with("_sync")
                && api
                    .functions
                    .iter()
                    .any(|f| f.is_async && f.name == format!("{}_async", &func.name[..func.name.len() - 5]))
            {
                return vec![];
            }

            if super::forwarders::function_references_excluded_type(func, exclude_types) {
                return vec![];
            }

            func.params
                .iter()
                .enumerate()
                .filter_map(move |(idx, param)| {
                    if let TypeRef::Named(type_name) = &param.ty
                        && let Some(typ) = api.types.iter().find(|t| &t.name == type_name)
                        && typ.has_serde
                        && !typ.is_opaque
                    {
                        return Some((func, idx, type_name.as_str()));
                    }
                    None
                })
                .collect::<Vec<_>>()
        })
        .collect();

    if json_overload_candidates.is_empty() {
        return;
    }

    // A `&mut T` DTO writeback function's IR `return_type` still records the original
    // `Unit` -- extraction is unchanged -- but the free-function forwarder this overload
    // delegates to now returns `T` (see `forwarders::writeback`). The JSON-string overload
    // must declare the same return type or it would claim `Void` while its body's `return`
    // statement hands back a value. ~keep
    let opaque_types: ahash::AHashSet<String> = api
        .types
        .iter()
        .filter(|t| t.is_opaque)
        .map(|t| t.name.clone())
        .collect();

    out.push_str("// MARK: - JSON-String Convenience Overloads\n");
    out.push_str("// These overloads accept JSON-encoded config parameters and decode them automatically.\n");
    out.push_str("// Enables e2e tests to pass JSON strings directly without typed config construction.\n\n");

    emit_load_bytes_from_path_or_utf8(out);

    let mut emitted_funcs: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut func_to_configs: std::collections::HashMap<String, Vec<(usize, &str)>> = std::collections::HashMap::new();

    for (func, config_param_idx, config_type_name) in &json_overload_candidates {
        func_to_configs
            .entry(func.name.clone())
            .or_default()
            .push((*config_param_idx, *config_type_name));
    }

    for (func, _config_param_idx, _config_type_name) in json_overload_candidates {
        if !emitted_funcs.insert(func.name.clone()) {
            continue;
        }

        if !func.is_async {
            let sync_name = func.name.clone();
            let has_async = api
                .functions
                .iter()
                .any(|f| f.is_async && f.name == format!("{}_async", sync_name));
            if has_async {
                continue;
            }
        }

        let mut config_params = func_to_configs.get(&func.name).cloned().unwrap_or_default();
        config_params.sort_by_key(|(idx, _)| *idx);

        let swift_func_name = swift_ident(&func.name.to_lower_camel_case());

        let mut param_strs: Vec<String> = Vec::new();
        let mut json_local_names: std::collections::HashMap<usize, (String, String)> = std::collections::HashMap::new();

        for (i, param) in func.params.iter().enumerate() {
            let param_name = param.name.to_lower_camel_case();
            let config_json_name = config_params.iter().find(|(idx, _)| *idx == i).map(|(_, ty_name)| {
                let type_snake = AsSnakeCase(ty_name).to_string();
                format!("{type_snake}_from_json").to_lower_camel_case()
            });

            if let Some(json_fn_name) = config_json_name.clone() {
                if config_params.iter().any(|(idx, _)| *idx == i) {
                    let type_var_name = param_name.clone();
                    param_strs.push(format!("_ {type_var_name}Json: String"));
                    json_local_names.insert(i, (json_fn_name, type_var_name));
                }
            } else {
                let ty_str = if param.optional {
                    format!("{}?", swift_type_name(&param.ty))
                } else {
                    swift_type_name(&param.ty)
                };
                param_strs.push(format!("_ {param_name}: {ty_str}"));
            }
        }

        let params_sig = param_strs.join(", ");
        let effective_return_type =
            crate::codegen::mut_writeback::effective_return_type(&func.params, &func.return_type, &opaque_types)
                .unwrap_or_else(|| func.return_type.clone());
        let return_ty = swift_return_type(&effective_return_type);
        let async_clause = if func.is_async { " async" } else { "" };
        let throws_clause = " throws";
        let return_suffix = "";

        let mut call_args: Vec<String> = Vec::new();
        for (i, param) in func.params.iter().enumerate() {
            let param_name = param.name.to_lower_camel_case();
            let is_positional = param.name.starts_with('_');

            if is_positional {
                if let Some((_, type_var_name)) = json_local_names.get(&i) {
                    call_args.push(type_var_name.clone());
                } else {
                    call_args.push(param_name.clone());
                }
            } else {
                if let Some((_, type_var_name)) = json_local_names.get(&i) {
                    call_args.push(format!("{param_name}: {type_var_name}"));
                } else {
                    call_args.push(format!("{param_name}: {param_name}"));
                }
            }
        }
        let call_args_str = call_args.join(", ");

        let mut decode_lines = String::new();
        let mut sorted_positions: Vec<_> = json_local_names.keys().copied().collect();
        sorted_positions.sort();
        for pos in sorted_positions {
            if let Some((json_fn_name, type_var_name)) = json_local_names.get(&pos) {
                decode_lines.push_str(&crate::backends::swift::template_env::render(
                    "swift_json_decode_line.swift.jinja",
                    minijinja::context! {
                        json_fn_name => json_fn_name,
                        type_var_name => type_var_name,
                    },
                ));
            }
        }
        let await_kw = if func.is_async { "await " } else { "" };
        out.push_str(&crate::backends::swift::template_env::render(
            "swift_json_string_overload.swift.jinja",
            minijinja::context! {
                function_name => &swift_func_name,
                params => &params_sig,
                async_clause => async_clause,
                throws_clause => throws_clause,
                return_type => &return_ty,
                decode_lines => decode_lines,
                await_kw => await_kw,
                call_args => &call_args_str,
                return_suffix => &return_suffix,
            },
        ));
    }
}

pub(super) fn emit_load_bytes_from_path_or_utf8(out: &mut String) {
    out.push_str("/// Resolves a string argument as either a file path or literal UTF-8 content.\n");
    out.push_str("/// Searches: current working directory, ALEF_TEST_DOCUMENTS_DIR env var,\n");
    out.push_str("/// and ancestor `test_documents/` or `fixtures/` directories (up to 16 levels).\n");
    out.push_str("/// If no file is found, treats the string as UTF-8 content and returns its bytes.\n");
    out.push_str("private func _loadBytesFromPathOrUtf8(_ pathOrContent: String) throws -> [UInt8] {\n");
    out.push_str("    let fm = FileManager.default\n");
    out.push_str("    var roots: [String] = [fm.currentDirectoryPath]\n");
    out.push_str("    if let envRoot = ProcessInfo.processInfo.environment[\"ALEF_TEST_DOCUMENTS_DIR\"] {\n");
    out.push_str("        roots.append(envRoot)\n");
    out.push_str("    }\n");
    out.push_str("    var walker = URL(fileURLWithPath: fm.currentDirectoryPath)\n");
    out.push_str("    for _ in 0..<16 {\n");
    out.push_str("        roots.append(walker.appendingPathComponent(\"test_documents\").path)\n");
    out.push_str("        roots.append(walker.appendingPathComponent(\"fixtures\").path)\n");
    out.push_str("        let parent = walker.deletingLastPathComponent()\n");
    out.push_str("        if parent.path == walker.path { break }\n");
    out.push_str("        walker = parent\n");
    out.push_str("    }\n");
    out.push_str(
        "    let candidates = [pathOrContent] + roots.map { ($0 as NSString).appendingPathComponent(pathOrContent) }\n",
    );
    out.push_str("    for path in candidates {\n");
    out.push_str(
        "        if fm.fileExists(atPath: path), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {\n",
    );
    out.push_str("            return [UInt8](data)\n");
    out.push_str("        }\n");
    out.push_str("    }\n");
    out.push_str("    return [UInt8](pathOrContent.utf8)\n");
    out.push_str("}\n\n");
}

pub(super) fn emit_from_json_forwarders(
    api: &ApiSurface,
    exclude_types: &std::collections::HashSet<String>,
    mapper: &SwiftMapper,
    exclude_fields: &std::collections::HashSet<String>,
    known_dto_names: &std::collections::HashSet<String>,
    out: &mut String,
) {
    use heck::AsSnakeCase;

    let visible_types: Vec<_> = api.types.iter().filter(|t| !exclude_types.contains(&t.name)).collect();
    let visible_functions: Vec<_> = api.functions.iter().collect();
    let struct_candidates: Vec<&str> = visible_types
        .iter()
        .copied()
        .filter(|t| !t.is_trait && t.has_serde)
        .filter(|t| {
            !t.is_opaque
                || crate::backends::swift::signatures_reference_named(
                    visible_types.iter().copied(),
                    visible_functions.iter().copied(),
                    &t.name,
                )
        })
        .map(|t| t.name.as_str())
        .collect();

    let enum_candidates: Vec<&str> = api
        .enums
        .iter()
        .filter(|e| e.has_serde && !exclude_types.contains(&e.name))
        .map(|e| e.name.as_str())
        .collect();

    if struct_candidates.is_empty() && enum_candidates.is_empty() {
        return;
    }

    out.push_str("// MARK: - From-JSON Helpers\n");
    out.push_str("// Public helpers that decode JSON into first-class Swift types.\n");
    out.push_str("// First-class struct types (Codable) use JSONDecoder directly.\n");
    out.push_str("// Opaque RustBridge types forward to RustBridge.\n\n");

    let first_class_set: std::collections::HashSet<&str> = api
        .types
        .iter()
        .filter(|t| !t.is_trait && super::dto::can_emit_first_class_struct(t, mapper, exclude_fields, known_dto_names))
        .map(|t| t.name.as_str())
        .collect();

    for type_name in struct_candidates {
        let type_snake = AsSnakeCase(type_name).to_string();
        let swift_name = format!("{type_snake}_from_json").to_lower_camel_case();
        if first_class_set.contains(type_name) {
            out.push_str(&crate::backends::swift::template_env::render(
                "swift_from_json_decode.swift.jinja",
                minijinja::context! {
                    function_name => &swift_name,
                    type_name => type_name,
                },
            ));
        } else {
            out.push_str(&crate::backends::swift::template_env::render(
                "swift_from_json_bridge.swift.jinja",
                minijinja::context! {
                    function_name => &swift_name,
                    type_name => type_name,
                },
            ));
        }
    }

    let codable_enum_set: std::collections::HashSet<&str> = api
        .enums
        .iter()
        .filter(|e| e.has_serde && enum_emits_codable(e, known_dto_names))
        .map(|e| e.name.as_str())
        .collect();
    for enum_name in enum_candidates {
        let enum_snake = AsSnakeCase(enum_name).to_string();
        let swift_name = format!("{enum_snake}_from_json").to_lower_camel_case();
        if codable_enum_set.contains(enum_name) {
            out.push_str(&crate::backends::swift::template_env::render(
                "swift_from_json_decode.swift.jinja",
                minijinja::context! {
                    function_name => &swift_name,
                    type_name => enum_name,
                },
            ));
        } else {
            out.push_str(&crate::backends::swift::template_env::render(
                "swift_from_json_bridge.swift.jinja",
                minijinja::context! {
                    function_name => &swift_name,
                    type_name => enum_name,
                },
            ));
        }
    }
}

pub(super) fn enum_emits_codable(en: &EnumDef, known_dto_names: &std::collections::HashSet<String>) -> bool {
    if !en.has_serde {
        return false;
    }
    let all_unit = en.variants.iter().all(|v| v.fields.is_empty());
    if all_unit {
        return true;
    }
    super::enums::all_variants_codable_safe(en, known_dto_names)
}

pub(super) fn emit_bytes_overloads(func: &FunctionDef, _all_names: &std::collections::HashSet<&str>, out: &mut String) {
    let swift_inner = swift_ident(&func.name.to_lower_camel_case());
    let wrapper_name = if swift_inner.ends_with("Sync") {
        swift_inner[..swift_inner.len() - 4].to_string()
    } else {
        swift_inner.clone()
    };
    let inner_call = swift_inner.clone();

    let trailing_params: Vec<&crate::core::ir::ParamDef> = func.params.iter().skip(1).collect();

    let return_ty = swift_return_type(&func.return_type);
    let throws_clause = if func.error_type.is_some() { " throws" } else { "" };
    let return_suffix = swift_return_conversion_suffix(&func.return_type);

    let trailing_param_text = render_trailing_params(trailing_params.iter().copied());
    let trailing_args = render_trailing_args(trailing_params.iter().copied());

    out.push_str(&crate::backends::swift::template_env::render(
        "swift_bytes_string_overload.jinja",
        minijinja::context! {
            wrapper_name => &wrapper_name,
            trailing_params => &trailing_param_text,
            throws_clause => throws_clause,
            return_ty => &return_ty,
            inner_call => &inner_call,
            trailing_args => &trailing_args,
            return_suffix => &return_suffix,
        },
    ));

    out.push_str(&crate::backends::swift::template_env::render(
        "swift_bytes_array_overload.jinja",
        minijinja::context! {
            wrapper_name => &wrapper_name,
            trailing_params => &trailing_param_text,
            throws_clause => throws_clause,
            return_ty => &return_ty,
            inner_call => &inner_call,
            trailing_args => &trailing_args,
            return_suffix => &return_suffix,
        },
    ));
}

pub(super) fn emit_path_overload(func: &FunctionDef, _all_names: &std::collections::HashSet<&str>, out: &mut String) {
    let swift_inner = swift_ident(&func.name.to_lower_camel_case());
    let wrapper_name = if swift_inner.ends_with("Sync") {
        swift_inner[..swift_inner.len() - 4].to_string()
    } else {
        swift_inner.clone()
    };
    let inner_call = swift_inner.clone();

    let trailing_params: Vec<&crate::core::ir::ParamDef> = func.params.iter().skip(1).collect();
    let return_ty = swift_return_type(&func.return_type);
    let throws_clause = if func.error_type.is_some() { " throws" } else { "" };
    let return_suffix = swift_return_conversion_suffix(&func.return_type);

    let trailing_param_text = render_trailing_params_with_defaults(trailing_params.iter().copied());
    let trailing_args = render_trailing_args(trailing_params.iter().copied());

    out.push_str(&crate::backends::swift::template_env::render(
        "swift_path_overload.jinja",
        minijinja::context! {
            wrapper_name => &wrapper_name,
            trailing_params => &trailing_param_text,
            throws_clause => throws_clause,
            return_ty => &return_ty,
            inner_call => &inner_call,
            trailing_args => &trailing_args,
            return_suffix => &return_suffix,
        },
    ));
}

pub(super) fn render_trailing_params<'a>(params: impl Iterator<Item = &'a crate::core::ir::ParamDef>) -> String {
    let mut out = String::new();
    for p in params {
        let swift_name = p.name.to_lower_camel_case();
        let ty_str = if p.optional {
            format!("{}?", swift_type_name(&p.ty))
        } else {
            swift_type_name(&p.ty)
        };
        out.push_str(&crate::backends::swift::template_env::render(
            "swift_trailing_param.jinja",
            minijinja::context! {
                swift_name => &swift_name,
                ty_str => &ty_str,
            },
        ));
    }
    out
}

pub(super) fn render_trailing_params_with_defaults<'a>(
    params: impl Iterator<Item = &'a crate::core::ir::ParamDef>,
) -> String {
    let mut out = String::new();
    for p in params {
        let swift_name = p.name.to_lower_camel_case();
        if p.optional {
            let ty_str = swift_type_name(&p.ty);
            out.push_str(&crate::backends::swift::template_env::render(
                "swift_trailing_param_optional_default.jinja",
                minijinja::context! {
                    swift_name => &swift_name,
                    ty_str => &ty_str,
                },
            ));
        } else {
            let ty_str = swift_type_name(&p.ty);
            out.push_str(&crate::backends::swift::template_env::render(
                "swift_trailing_param.jinja",
                minijinja::context! {
                    swift_name => &swift_name,
                    ty_str => &ty_str,
                },
            ));
        }
    }
    out
}

pub(super) fn render_trailing_args<'a>(params: impl Iterator<Item = &'a crate::core::ir::ParamDef>) -> String {
    let mut out = String::new();
    for p in params {
        let swift_name = p.name.to_lower_camel_case();
        out.push_str(&crate::backends::swift::template_env::render(
            "swift_trailing_arg.jinja",
            minijinja::context! {
                swift_name => &swift_name,
            },
        ));
    }
    out
}

pub(super) fn swift_type_name(ty: &TypeRef) -> String {
    match ty {
        TypeRef::String => "String".to_string(),
        TypeRef::Bytes => "[UInt8]".to_string(),
        TypeRef::Path => "String".to_string(),
        TypeRef::Named(name) => name.clone(),
        TypeRef::Optional(inner) => format!("{}?", swift_type_name(inner)),
        TypeRef::Vec(inner) => format!("[{}]", swift_type_name(inner)),
        TypeRef::Map(k, v) => format!("[{}: {}]", swift_type_name(k), swift_type_name(v)),
        TypeRef::Primitive(p) => match p {
            PrimitiveType::Bool => "Bool",
            PrimitiveType::U8 => "UInt8",
            PrimitiveType::U16 => "UInt16",
            PrimitiveType::U32 => "UInt32",
            PrimitiveType::U64 => "UInt64",
            PrimitiveType::I8 => "Int8",
            PrimitiveType::I16 => "Int16",
            PrimitiveType::I32 => "Int32",
            PrimitiveType::I64 => "Int64",
            PrimitiveType::Usize => "UInt",
            PrimitiveType::Isize => "Int",
            PrimitiveType::F32 => "Float",
            PrimitiveType::F64 => "Double",
        }
        .to_string(),
        TypeRef::Unit => "Void".to_string(),
        TypeRef::Json => "String".to_string(),
        TypeRef::Duration => "Duration".to_string(),
        TypeRef::Char => "Character".to_string(),
    }
}

pub(super) fn swift_return_type(ty: &TypeRef) -> String {
    swift_type_name(ty)
}

pub(super) fn swift_return_conversion_suffix(ty: &TypeRef) -> String {
    match ty {
        TypeRef::String => ".toString()".to_string(),
        TypeRef::Bytes => ".map { $0 }".to_string(),
        TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Primitive(_)) => ".map { $0 }".to_string(),
        _ => String::new(),
    }
}

pub(super) fn convenience_name_shadows_bridge(func: &FunctionDef) -> bool {
    let swift_inner = swift_ident(&func.name.to_lower_camel_case());
    let wrapper_name = if swift_inner.ends_with("Sync") {
        swift_inner[..swift_inner.len() - 4].to_string()
    } else {
        swift_inner.clone()
    };
    wrapper_name == swift_inner
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::ir::{ParamDef, TypeDef};

    /// A non-opaque serde DTO whose fields are not all first-class-supported (e.g. a
    /// `Map` field) is NOT a first-class Codable struct, so its `*FromJson` helper
    /// delegates to `RustBridge.{type}FromJson`. That bridge symbol only exists when
    /// the Rust bridge crate compiled the type for the active feature set. After
    /// `with_cfg_filtered` drops a cfg-gated type whose feature is off, the high-level
    /// `emit_from_json_forwarders` pass must NOT emit a dangling `RustBridge` reference
    /// for it — while a non-gated bridge type must still get its forwarder.
    #[test]
    fn from_json_forwarders_skip_cfg_filtered_bridge_types() {
        use crate::core::ir::FieldDef;

        fn bridge_serde_ty(name: &str, cfg: Option<&str>) -> TypeDef {
            TypeDef {
                name: name.to_string(),
                is_opaque: false,
                has_serde: true,
                cfg: cfg.map(str::to_string),
                fields: vec![FieldDef {
                    name: "table".to_string(),
                    ty: TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::String)),
                    ..FieldDef::default()
                }],
                ..TypeDef::default()
            }
        }

        let mut api = ApiSurface::default();
        api.types.push(bridge_serde_ty("PdfMetadata", None));
        api.types.push(bridge_serde_ty("Preset", Some("feature = \"presets\"")));

        let configured: std::collections::HashSet<&str> = ["pdf"].into_iter().collect();
        let filtered = api.with_cfg_filtered(&configured);

        let mapper = SwiftMapper;
        let exclude_types = std::collections::HashSet::new();
        let exclude_fields = std::collections::HashSet::new();
        let known_dto_names = std::collections::HashSet::new();
        let mut out = String::new();
        emit_from_json_forwarders(
            &filtered,
            &exclude_types,
            &mapper,
            &exclude_fields,
            &known_dto_names,
            &mut out,
        );

        assert!(
            out.contains("RustBridge.pdfMetadataFromJson"),
            "satisfied opaque type must keep its bridge forwarder. Got:\n{out}"
        );
        assert!(
            !out.contains("presetFromJson") && !out.contains("RustBridge.Preset"),
            "cfg-filtered type must not emit a dangling RustBridge reference. Got:\n{out}"
        );
    }

    #[test]
    fn from_json_forwarders_cover_referenced_opaque_serde_types() {
        use crate::core::ir::FieldDef;

        let mut api = ApiSurface::default();
        api.types.push(TypeDef {
            name: "CredentialConfig".to_owned(),
            is_opaque: true,
            has_serde: true,
            ..TypeDef::default()
        });
        api.types.push(TypeDef {
            name: "UnusedConfig".to_owned(),
            is_opaque: true,
            has_serde: true,
            ..TypeDef::default()
        });
        api.types.push(TypeDef {
            name: "RequestOptions".to_owned(),
            fields: vec![FieldDef {
                name: "credential".to_owned(),
                ty: TypeRef::Named("CredentialConfig".to_owned()),
                ..FieldDef::default()
            }],
            ..TypeDef::default()
        });
        let mut out = String::new();

        emit_from_json_forwarders(
            &api,
            &std::collections::HashSet::new(),
            &SwiftMapper,
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &mut out,
        );

        assert!(out.contains("credentialConfigFromJson"), "{out}");
        assert!(out.contains("RustBridge.credentialConfigFromJson"), "{out}");
        assert!(!out.contains("unusedConfigFromJson"), "{out}");
    }

    /// Regression test: a function with two JSON-decoded params used to decode BOTH via
    /// the FIRST param's type, and emitted duplicate `configJson` labels/local names. Each
    /// param must decode via its own type's `*FromJson` helper, keyed by param position, not
    /// by a single shared type. ~keep
    #[test]
    fn json_overload_dispatches_decode_by_param_type_not_position() {
        let mut api = ApiSurface::default();
        api.types.push(TypeDef {
            name: "ConfigA".to_string(),
            has_serde: true,
            is_opaque: false,
            ..TypeDef::default()
        });
        api.types.push(TypeDef {
            name: "ConfigB".to_string(),
            has_serde: true,
            is_opaque: false,
            ..TypeDef::default()
        });
        api.functions.push(FunctionDef {
            name: "process".to_string(),
            rust_path: "sample::process".to_string(),
            params: vec![
                ParamDef {
                    name: "configA".to_string(),
                    ty: TypeRef::Named("ConfigA".to_string()),
                    ..ParamDef::default()
                },
                ParamDef {
                    name: "configB".to_string(),
                    ty: TypeRef::Named("ConfigB".to_string()),
                    ..ParamDef::default()
                },
            ],
            return_type: TypeRef::Unit,
            ..FunctionDef::default()
        });

        let mut out = String::new();
        emit_json_string_overloads(&api, &std::collections::HashSet::new(), &mut out);

        assert!(
            out.contains("let configA = try configAFromJson(configAJson)"),
            "first param must decode via its own type's *FromJson helper. Got:\n{out}"
        );
        assert!(
            out.contains("let configB = try configBFromJson(configBJson)"),
            "second param must decode via its own type's *FromJson helper (regression: both \
             used to decode via the FIRST param's type). Got:\n{out}"
        );
        assert!(
            !out.contains("configAFromJson(configBJson)") && !out.contains("configBFromJson(configAJson)"),
            "a decode function must never be applied to the wrong param's JSON string. Got:\n{out}"
        );
        assert!(
            out.contains("_ configAJson: String") && out.contains("_ configBJson: String"),
            "both parameter labels must be distinct, not duplicated. Got:\n{out}"
        );
    }

    /// Regression test: the IR carries a `_sync` stub alongside a real `_async` twin (e.g.
    /// `download_model_sync` / `download_model_async`, where the sync variant is a stub). A
    /// JSON overload used to be emitted for the sync stub too, calling a typed wrapper that
    /// does not exist -- "no exact matches in call to global function". The sync stub must
    /// get no overload while the async twin still gets one. ~keep
    #[test]
    fn json_overload_skips_sync_stub_when_async_twin_exists() {
        let mut api = ApiSurface::default();
        api.types.push(TypeDef {
            name: "DownloadConfig".to_string(),
            has_serde: true,
            is_opaque: false,
            ..TypeDef::default()
        });
        let param = ParamDef {
            name: "config".to_string(),
            ty: TypeRef::Named("DownloadConfig".to_string()),
            ..ParamDef::default()
        };
        api.functions.push(FunctionDef {
            name: "download_model_sync".to_string(),
            rust_path: "sample::download_model_sync".to_string(),
            params: vec![param.clone()],
            return_type: TypeRef::Unit,
            ..FunctionDef::default()
        });
        api.functions.push(FunctionDef {
            name: "download_model_async".to_string(),
            rust_path: "sample::download_model_async".to_string(),
            params: vec![param],
            return_type: TypeRef::Unit,
            is_async: true,
            ..FunctionDef::default()
        });

        let mut out = String::new();
        emit_json_string_overloads(&api, &std::collections::HashSet::new(), &mut out);

        assert!(
            !out.contains("public func downloadModelSync("),
            "sync stub must not get a JSON overload when an async twin exists. Got:\n{out}"
        );
        assert!(
            out.contains("public func downloadModelAsync("),
            "async twin must still get its JSON overload. Got:\n{out}"
        );
    }

    /// Regression test: the typed wrapper already converts `RustString` -> `String`, but the
    /// JSON overload used to append a second `.toString()` -- "value of type 'String' has no
    /// member 'toString'". The overload's return statement must not append a conversion suffix. ~keep
    #[test]
    fn json_overload_for_string_return_does_not_double_convert() {
        let mut api = ApiSurface::default();
        api.types.push(TypeDef {
            name: "GreetConfig".to_string(),
            has_serde: true,
            is_opaque: false,
            ..TypeDef::default()
        });
        api.functions.push(FunctionDef {
            name: "greet".to_string(),
            rust_path: "sample::greet".to_string(),
            params: vec![ParamDef {
                name: "config".to_string(),
                ty: TypeRef::Named("GreetConfig".to_string()),
                ..ParamDef::default()
            }],
            return_type: TypeRef::String,
            ..FunctionDef::default()
        });

        let mut out = String::new();
        emit_json_string_overloads(&api, &std::collections::HashSet::new(), &mut out);

        assert!(
            out.contains("public func greet(_ configJson: String) throws -> String {"),
            "expected a JSON overload to be emitted for greet. Got:\n{out}"
        );
        assert!(
            out.contains("return try greet(config: config)\n}"),
            "the overload must return the typed wrapper's result verbatim, with no conversion \
             suffix appended after the call. Got:\n{out}"
        );
        assert!(
            !out.contains(".toString()"),
            "JSON overload for a String-returning function must not double-convert with .toString(). Got:\n{out}"
        );
    }
}