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
//! Emits the Rust-side swift-bridge crate for Phase 2C.
//!
//! Three files are generated into `packages/swift/rust/`:
//! - `Cargo.toml` — declares the `cdylib`/`staticlib` crate with swift-bridge dependencies
//! - `src/lib.rs` — `#[swift_bridge::bridge] mod ffi { … }` plus wrapper newtypes and shims
//! - `build.rs` — calls `swift_bridge_build::parse_bridges` to run codegen at build time

mod callback_files;
pub(crate) mod cargo;
pub(crate) mod default_construction;
mod deferred_noop;
pub(crate) mod enums;
pub(crate) mod extern_block;
pub(crate) mod feature_gate;
mod json_bridge;
pub(crate) mod plugin_inbound;
pub(crate) mod service_app_wrappers;
pub(crate) mod shims;
pub mod trait_bridge;
pub(crate) mod type_bridge;
pub(crate) mod wrappers;

use crate::codegen::generators::type_paths::build_type_path_lookup;
use crate::core::backend::GeneratedFile;
use crate::core::config::extras::Language;
use crate::core::config::{BridgeBinding, ResolvedCrateConfig, TraitBridgeConfig};
use crate::core::ir::{ApiSurface, EnumDef, FunctionDef, TypeDef};
use crate::core::template_versions;
use heck::AsSnakeCase;
use std::collections::HashSet;
use std::path::PathBuf;

/// Top-level entry point: emit all three files for the swift-bridge crate.
pub fn emit(api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
    // mirror declares each function in a `#[cfg(...)] extern "Rust"` block; two same-named entries
    let deduped_api = api.with_deduped_functions();
    let api = &deduped_api;

    let base = PathBuf::from("packages/swift/rust");
    let crate_name = &api.crate_name;
    let version = &api.version;

    let swift_bridge_ver = crate::backends::swift::naming::swift_bridge_version(config);
    let swift_bridge_build_ver = template_versions::cargo::SWIFT_BRIDGE_BUILD;
    let core_crate_dir = config.core_crate_for_language(Language::Swift);
    let swift_override = config.swift.as_ref().and_then(|c| c.core_crate_override.as_deref());
    let same_as_workspace =
        swift_override.is_none() && core_crate_dir == *crate_name && config.workspace_root.is_none();
    let core_path = if same_as_workspace {
        "../../..".to_string()
    } else {
        format!("../../../crates/{core_crate_dir}")
    };
    let core_dep_key: String = match swift_override {
        Some(name) => name.to_string(),
        None => crate_name.replace('-', "_"),
    };

    let features_owned = feature_gate::configured_swift_features(config, &core_crate_dir);
    let features: &[String] = &features_owned;
    let mut exclude_functions: HashSet<String> = config
        .swift
        .as_ref()
        .map(|c| c.exclude_functions.iter().cloned().collect())
        .unwrap_or_default();
    let mut exclude_types: HashSet<String> = config
        .swift
        .as_ref()
        .map(|c| c.exclude_types.iter().cloned().collect())
        .unwrap_or_default();
    if let Some(ffi) = &config.ffi {
        exclude_functions.extend(ffi.exclude_functions.iter().cloned());
        exclude_types.extend(ffi.exclude_types.iter().cloned());
    }
    exclude_types.extend(api.types.iter().filter(|t| t.binding_excluded).map(|t| t.name.clone()));
    exclude_types.extend(api.enums.iter().filter(|e| e.binding_excluded).map(|e| e.name.clone()));
    for contract in &api.handler_contracts {
        if let Some(adapter) = contract.response_adapter.as_deref() {
            if let Some(short) = adapter.rsplit("::").next() {
                exclude_functions.insert(short.to_string());
            }
        }
    }
    let exclude_fields: HashSet<String> = config
        .swift
        .as_ref()
        .map(|c| c.exclude_fields.iter().cloned().collect())
        .unwrap_or_default();
    let license = config
        .scaffold
        .as_ref()
        .and_then(|s| s.license.as_deref())
        .unwrap_or("MIT");
    let has_streaming_adapters = config
        .adapters
        .iter()
        .any(|a| matches!(a.pattern, crate::core::config::AdapterPattern::Streaming));
    let extra_deps = crate::scaffold::render_extra_deps(config, Language::Swift);
    let target_overrides = config
        .swift
        .as_ref()
        .map(|c| c.target_dep_overrides.as_slice())
        .unwrap_or(&[]);
    let excluded_default_features = config
        .swift
        .as_ref()
        .map(|c| c.excluded_default_features.as_slice())
        .unwrap_or(&[]);
    let cargo_toml = cargo::emit_cargo_toml(
        crate_name,
        &core_dep_key,
        &core_crate_dir,
        version,
        &swift_bridge_ver,
        swift_bridge_build_ver,
        &core_path,
        features,
        &extra_deps,
        license,
        has_streaming_adapters,
        target_overrides,
        api,
        excluded_default_features,
    );
    let effective_features = feature_gate::effective_swift_codegen_features(api, config, &core_crate_dir);
    let configured_features: HashSet<&str> = effective_features.iter().map(String::as_str).collect();
    let lib_rs = emit_lib_rs(
        api,
        config,
        crate_name,
        &exclude_functions,
        &exclude_types,
        &exclude_fields,
        &configured_features,
    );
    let build_rs = cargo::emit_build_rs();

    let mut files = vec![
        GeneratedFile {
            path: base.join("Cargo.toml"),
            content: cargo_toml,
            generated_header: false,
        },
        GeneratedFile {
            path: base.join("src/lib.rs"),
            content: lib_rs,
            generated_header: false,
        },
        GeneratedFile {
            path: base.join("build.rs"),
            content: build_rs,
            generated_header: false,
        },
    ];
    if let Some(callback_file) = callback_files::emit_callback_registration_file(api, &base) {
        files.push(callback_file);
    }
    Ok(files)
}

fn emit_lib_rs(
    api: &ApiSurface,
    config: &ResolvedCrateConfig,
    crate_name: &str,
    exclude_functions: &HashSet<String>,
    exclude_types: &HashSet<String>,
    exclude_fields: &HashSet<String>,
    configured_features: &HashSet<&str>,
) -> String {
    let source_crate = crate_name.replace('-', "_");

    let type_paths = build_type_path_lookup(api);

    let mut out = String::new();
    out.push_str("// Generated by alef. Do not edit by hand.\n\n");
    out.push_str("#![allow(unused_variables, unreachable_code, unreachable_patterns, missing_docs)]\n");
    out.push_str("#![allow(\n");
    out.push_str("    clippy::collapsible_if,\n");
    out.push_str("    clippy::collapsible_match,\n");
    out.push_str("    clippy::needless_borrows_for_generic_args,\n");
    out.push_str("    clippy::field_reassign_with_default,\n");
    out.push_str("    clippy::too_many_arguments,\n");
    out.push_str("    clippy::clone_on_copy,\n");
    out.push_str("    clippy::unnecessary_cast,\n");
    out.push_str("    clippy::manual_flatten,\n");
    out.push_str("    clippy::match_single_binding,\n");
    out.push_str("    clippy::redundant_closure,\n");
    out.push_str("    clippy::useless_conversion,\n");
    out.push_str("    clippy::inherent_to_string,\n");
    out.push_str("    clippy::new_without_default,\n");
    out.push_str(")]\n");
    if let Some(extra_attr) = crate::codegen::shared::format_extra_clippy_allows(&config.extra_clippy_allows, &out) {
        out.push_str(&format!("#![{extra_attr}]\n"));
    }
    out.push('\n');

    out.push_str(shims::ALEF_TOKIO_RUNTIME_DEFINITION);
    out.push('\n');

    let visible_types: Vec<&TypeDef> = api
        .types
        .iter()
        .filter(|t| !exclude_types.contains(&t.name) && !t.is_trait)
        .filter(|t| feature_gate::cfg_satisfied(t.cfg.as_deref(), configured_features))
        .collect();
    let visible_enums: Vec<&EnumDef> = api
        .enums
        .iter()
        .filter(|e| !exclude_types.contains(&e.name))
        .filter(|e| feature_gate::cfg_satisfied(e.cfg.as_deref(), configured_features))
        .collect();

    let enum_names: HashSet<&str> = visible_enums.iter().map(|e| e.name.as_str()).collect();

    let unit_enum_names: HashSet<&str> = visible_enums
        .iter()
        .filter(|e| e.variants.iter().all(|v| v.fields.is_empty()))
        .map(|e| e.name.as_str())
        .collect();

    let tagged_enum_names: HashSet<&str> = visible_enums
        .iter()
        .filter(|e| e.variants.iter().any(|v| !v.fields.is_empty()))
        .map(|e| e.name.as_str())
        .collect();

    let visible_type_names: HashSet<&str> = visible_types
        .iter()
        .map(|t| t.name.as_str())
        .chain(enum_names.iter().copied())
        .collect();

    let no_serde_names: HashSet<&str> = api
        .types
        .iter()
        .filter(|t| !t.has_serde)
        .map(|t| t.name.as_str())
        .collect();
    let first_class_owned =
        crate::backends::swift::gen_bindings::dto::compute_first_class_dto_names(api, exclude_types);
    let first_class_names: HashSet<&str> = first_class_owned.iter().map(|s| s.as_str()).collect();
    let no_serde_enum_names: HashSet<&str> = api
        .enums
        .iter()
        .filter(|e| !e.has_serde)
        .map(|e| e.name.as_str())
        .collect();

    let handle_returned_types: HashSet<String> = type_bridge::compute_handle_returned_types(api);

    let visible_functions: Vec<&FunctionDef> = api
        .functions
        .iter()
        .filter(|f| !exclude_functions.contains(&f.name))
        .filter(|f| feature_gate::cfg_satisfied(f.cfg.as_deref(), configured_features))
        .filter(|f| {
            !crate::codegen::generators::trait_bridge::is_trait_bridge_managed_fn(&f.name, &config.trait_bridges)
        })
        .filter(|f| {
            shims::is_bridgeable_fn(
                f,
                &unit_enum_names,
                &type_paths,
                &no_serde_names,
                &no_serde_enum_names,
                &handle_returned_types,
            )
        })
        .collect();

    let active_bridges: Vec<(&TraitBridgeConfig, &TypeDef)> = config
        .trait_bridges
        .iter()
        .filter(|b| !b.exclude_languages.iter().any(|l| l == "swift"))
        .filter_map(|b| {
            api.types
                .iter()
                .find(|t| t.is_trait && t.name == b.trait_name)
                .map(|t| (b, t))
        })
        .collect();

    let result_type_enums: std::collections::HashSet<String> = active_bridges
        .iter()
        .filter_map(|(bridge_cfg, _)| bridge_cfg.result_type.as_deref().map(|s| s.to_string()))
        .collect();

    let enum_names_owned: std::collections::HashSet<String> = enum_names.iter().map(|s| s.to_string()).collect();
    let mut extern_blocks: Vec<String> = Vec::new();
    let mut deferred_empty_handle_types: std::collections::HashSet<String> = std::collections::HashSet::new();
    for ty in &visible_types {
        let is_handle_returned = handle_returned_types.contains(&ty.name);
        let would_be_empty_type_block = ty.fields.is_empty()
            && !extern_block::has_constructor_extern(ty, exclude_fields, configured_features)
            && ty
                .methods
                .iter()
                .all(|m| m.binding_excluded || m.sanitized || m.is_static);
        if is_handle_returned && would_be_empty_type_block {
            deferred_empty_handle_types.insert(ty.name.clone());
            continue;
        }

        // Wrap each extern block in `#[cfg(feature = "...")]` when the type carries a
        // cfg condition.  swift-bridge 0.1.59 cannot parse `#[cfg(...)]` *inside* an
        // extern block, but `#[cfg(...)] extern "Rust" { ... }` at the module item
        // `#[cfg(feature = "...")]`-gated in the shims — causing "no type named 'T' in
        let cfg_open = ty
            .cfg
            .as_deref()
            .map(|c| format!("    #[cfg({c})]\n"))
            .unwrap_or_default();
        let raw_block = extern_block::emit_extern_block_for_type(
            ty,
            exclude_fields,
            &type_paths,
            &no_serde_names,
            &first_class_names,
            &enum_names_owned,
            configured_features,
        );
        extern_blocks.push(format!("{cfg_open}{raw_block}"));
        if ty.is_opaque && !ty.methods.iter().all(|m| m.sanitized) && !ty.methods.is_empty() {
            let has_ctor_override = config
                .swift
                .as_ref()
                .is_some_and(|c| c.client_constructor_body.contains_key(&ty.name));
            if has_ctor_override && let Some(ctor_block) = extern_block::emit_extern_block_for_type_constructor(ty) {
                extern_blocks.push(format!("{cfg_open}{ctor_block}"));
            }
            if let Some(method_block) =
                extern_block::emit_extern_block_for_type_methods(ty, &handle_returned_types, &enum_names)
            {
                extern_blocks.push(format!("{cfg_open}{method_block}"));
            }
        }
        if let Some(dto_method_block) =
            extern_block::emit_extern_block_for_first_class_dto_methods(ty, &handle_returned_types, &enum_names)
        {
            extern_blocks.push(format!("{cfg_open}{dto_method_block}"));
        }
    }
    for en in &visible_enums {
        // Wrap cfg-gated enums in `#[cfg(...)]` for the same reason as types above.
        if !result_type_enums.contains(&en.name) {
            let raw_block = extern_block::emit_extern_block_for_enum(en);
            if let Some(cfg) = en.cfg.as_deref() {
                extern_blocks.push(format!("    #[cfg({cfg})]\n{raw_block}"));
            } else {
                extern_blocks.push(raw_block);
            }
        }
    }
    let swift_capsule_types: std::collections::HashMap<String, crate::core::config::HostCapsuleTypeConfig> = config
        .swift
        .as_ref()
        .map(|c| c.capsule_types.clone())
        .unwrap_or_default();

    if !visible_functions.is_empty() {
        // cfg-gated functions are emitted into per-cfg `#[cfg(...)] extern "Rust" { }`
        // proc macro runs when the feature is off.  The shim body is also `#[cfg(...)]`-
        let non_cfg_fns: Vec<FunctionDef> = visible_functions
            .iter()
            .filter(|f| f.cfg.is_none())
            .map(|f| (*f).clone())
            .collect();
        if !non_cfg_fns.is_empty() {
            extern_blocks.push(extern_block::emit_extern_block_for_functions(
                &non_cfg_fns,
                &handle_returned_types,
                &enum_names_owned,
                &deferred_empty_handle_types,
                &swift_capsule_types,
            ));
        }
        // `#[cfg(...)] extern "Rust" { }` block per distinct condition.
        let mut cfg_groups: std::collections::BTreeMap<String, Vec<FunctionDef>> = std::collections::BTreeMap::new();
        for f in visible_functions.iter().filter(|f| f.cfg.is_some()) {
            cfg_groups.entry(f.cfg.clone().unwrap()).or_default().push((*f).clone());
        }
        for (cfg_cond, fns) in &cfg_groups {
            let empty_set = std::collections::HashSet::new();
            let block = extern_block::emit_extern_block_for_functions(
                fns,
                &handle_returned_types,
                &enum_names_owned,
                &empty_set,
                &swift_capsule_types,
            );
            extern_blocks.push(format!("    #[cfg({cfg_cond})]\n{block}"));
        }
    }
    for (_bridge_cfg, trait_def) in &active_bridges {
        extern_blocks.push(trait_bridge::emit_extern_block_for_trait_bridge(
            trait_def,
            &visible_type_names,
        ));
    }
    for (bridge_cfg, trait_def) in &active_bridges {
        if bridge_cfg.bind_via != BridgeBinding::FunctionParam {
            continue;
        }
        let reg_block = plugin_inbound::emit_extern_block_for_inbound_registration(trait_def, bridge_cfg);
        if !reg_block.is_empty() {
            extern_blocks.push(reg_block);
        }
    }
    for (bridge_cfg, trait_def) in &active_bridges {
        extern_blocks.push(plugin_inbound::emit_extern_block_for_inbound(trait_def, bridge_cfg));
    }
    for (bridge_cfg, trait_def) in &active_bridges {
        if bridge_cfg.bind_via != BridgeBinding::OptionsField {
            continue;
        }
        let (factory_extern, _factory_body) =
            plugin_inbound::emit_options_field_factory(trait_def, bridge_cfg, api, &source_crate);
        if !factory_extern.is_empty() {
            extern_blocks.push(factory_extern);
        }
        let (helper_extern, _helper_body) =
            plugin_inbound::emit_options_field_options_helper(bridge_cfg, api, &source_crate);
        if !helper_extern.is_empty() {
            extern_blocks.push(helper_extern);
        }
    }

    let declared_owner_types: std::collections::HashSet<String> = visible_types
        .iter()
        .filter(|ty| ty.is_opaque)
        .map(|ty| ty.name.clone())
        .collect();
    if let Some(streaming_block) =
        extern_block::emit_extern_block_for_streaming_adapters(&config.adapters, &declared_owner_types)
    {
        extern_blocks.push(streaming_block);
    }

    let service_api_blocks = super::gen_bindings::service_api::generate_rust_extern_blocks(api).unwrap_or_default();
    extern_blocks.extend(service_api_blocks);

    let service_api_callback_funcs: Vec<String> =
        super::gen_bindings::service_api::generate_rust_callback_c_functions(api).unwrap_or_default();

    let extra_serde_param_types: Vec<&TypeDef> =
        json_bridge::collect_serde_param_types(api, &visible_types, &visible_functions, &[]);

    let extra_serde_param_names: std::collections::HashSet<&str> =
        extra_serde_param_types.iter().map(|t| t.name.as_str()).collect();
    let streaming_item_types: Vec<&TypeDef> = {
        let streaming_item_names: std::collections::HashSet<&str> = config
            .adapters
            .iter()
            .filter(|a| matches!(a.pattern, crate::core::config::AdapterPattern::Streaming))
            .filter_map(|a| a.item_type.as_deref())
            .collect();
        visible_types
            .iter()
            .copied()
            .filter(|ty| streaming_item_names.contains(ty.name.as_str()))
            .filter(|ty| ty.has_serde && !ty.is_opaque && !ty.is_trait)
            .filter(|ty| !extra_serde_param_names.contains(ty.name.as_str()))
            .collect()
    };

    let streaming_item_names: std::collections::HashSet<&str> =
        streaming_item_types.iter().map(|t| t.name.as_str()).collect();
    let json_fallback_types: Vec<&TypeDef> = visible_types
        .iter()
        .copied()
        .filter(|ty| ty.has_serde && !ty.is_opaque && !ty.is_trait)
        .filter(|ty| !extra_serde_param_names.contains(ty.name.as_str()))
        .filter(|ty| !streaming_item_names.contains(ty.name.as_str()))
        .collect();

    let json_fallback_enums: Vec<&EnumDef> = visible_enums.iter().copied().filter(|e| e.has_serde).collect();

    out.push_str("#[swift_bridge::bridge]\nmod ffi {\n");
    for block in &extern_blocks {
        out.push_str(block);
    }
    json_bridge::emit_type_from_json_extern_block(&mut out, &extra_serde_param_types);
    json_bridge::emit_type_from_json_extern_block(&mut out, &streaming_item_types);
    json_bridge::emit_type_from_json_extern_block(&mut out, &json_fallback_types);
    let json_fallback_enums_filtered: Vec<&EnumDef> = json_fallback_enums
        .iter()
        .filter(|en| !result_type_enums.contains(&en.name))
        .copied()
        .collect();
    json_bridge::emit_enum_from_json_extern_block(&mut out, &json_fallback_enums_filtered);

    // cfg-gated types are split into per-type `#[cfg(...)] extern "Rust" { }` blocks
    let vec_accessible_enums: Vec<&EnumDef> = visible_enums
        .iter()
        .filter(|en| !result_type_enums.contains(&en.name))
        .copied()
        .collect();
    // Skip types marked `#[swift_bridge(already_declared)]` (streaming-adapter
    let already_declared =
        crate::backends::swift::gen_bindings::opaque_handles::collect_already_declared_owner_types(config);
    let non_cfg_types: Vec<&TypeDef> = visible_types
        .iter()
        .copied()
        .filter(|t| t.cfg.is_none() && !already_declared.contains(&t.name))
        .collect();
    let non_cfg_enums: Vec<&EnumDef> = vec_accessible_enums
        .iter()
        .copied()
        .filter(|e| e.cfg.is_none())
        .collect();
    let vec_accessors_block = extern_block::emit_extern_block_for_vec_accessors(&non_cfg_types, &non_cfg_enums);
    if !vec_accessors_block.is_empty() {
        out.push_str(&vec_accessors_block);
    }
    // cfg-gated types each get their own `#[cfg(...)] extern "Rust" { }` block.
    for ty in visible_types
        .iter()
        .filter(|t| t.cfg.is_some() && !already_declared.contains(&t.name))
    {
        let cfg = ty.cfg.as_deref().unwrap();
        let block = extern_block::emit_extern_block_for_vec_accessors(&[ty], &[]);
        if !block.is_empty() {
            out.push_str(&format!("    #[cfg({cfg})]\n{block}"));
        }
    }
    for en in vec_accessible_enums.iter().filter(|e| e.cfg.is_some()) {
        let cfg = en.cfg.as_deref().unwrap();
        let block = extern_block::emit_extern_block_for_vec_accessors(&[], &[en]);
        if !block.is_empty() {
            out.push_str(&format!("    #[cfg({cfg})]\n{block}"));
        }
    }

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

    let vec_impl_types: Vec<&TypeDef> = visible_types
        .iter()
        .copied()
        .filter(|t| !already_declared.contains(&t.name))
        .collect();
    let phantom_impl = extern_block::emit_phantom_vec_impl(&vec_impl_types, &vec_accessible_enums);
    if !phantom_impl.is_empty() {
        out.push_str(&phantom_impl);
    }

    out.push_str(&service_app_wrappers::emit_service_app_wrappers(api, &source_crate));
    out.push('\n');

    // `#[unsafe(no_mangle)]` attribute. swift-bridge only parses `src/lib.rs`,
    if !service_api_callback_funcs.is_empty() {
        out.push_str("mod extern_callbacks;\n\n");
    }

    for ty in &visible_types {
        out.push_str(&wrappers::emit_type_wrapper(
            ty,
            &source_crate,
            &type_paths,
            &enum_names,
            &unit_enum_names,
            &no_serde_names,
            &first_class_names,
            exclude_fields,
            configured_features,
        ));
        out.push('\n');
        if ty.is_opaque && !ty.methods.iter().all(|m| m.sanitized) && !ty.methods.is_empty() {
            let custom_body = config
                .swift
                .as_ref()
                .and_then(|c| c.client_constructor_body.get(&ty.name))
                .map(String::as_str);
            if custom_body.is_some() {
                out.push_str(&wrappers::emit_type_constructor_shim(
                    ty,
                    &source_crate,
                    &type_paths,
                    custom_body,
                ));
                out.push('\n');
            }
            out.push_str(&wrappers::emit_type_method_shims(
                ty,
                &source_crate,
                &type_paths,
                &handle_returned_types,
                &enum_names,
            ));
            out.push('\n');
        }

        let dto_wrappers =
            wrappers::emit_first_class_dto_method_wrappers(ty, &source_crate, &type_paths, &unit_enum_names);
        if !dto_wrappers.is_empty() {
            out.push_str(&dto_wrappers);
        }
    }

    let mut noop_def_types = deferred_empty_handle_types.clone();
    for ty in &visible_types {
        if extern_block::type_needs_own_block_noop(ty) {
            noop_def_types.insert(ty.name.clone());
        }
    }
    out.push_str(&deferred_noop::emit_shims(&noop_def_types, &visible_types));

    for en in &visible_enums {
        out.push_str(&enums::emit_enum_wrapper(en, &source_crate, &type_paths));
        out.push('\n');
    }
    let function_shim_context = shims::FunctionShimContext {
        source_crate: &source_crate,
        type_paths: &type_paths,
        unit_enum_names: &unit_enum_names,
        tagged_enum_names: &tagged_enum_names,
        no_serde_names: &no_serde_names,
        handle_returned_types: &handle_returned_types,
        capsule_types: &swift_capsule_types,
    };
    for f in &visible_functions {
        out.push_str(&shims::emit_function_shim(f, &function_shim_context));
        out.push('\n');
    }
    for (_bridge_cfg, trait_def) in &active_bridges {
        out.push_str(&trait_bridge::emit_trait_bridge_wrapper(
            trait_def,
            &source_crate,
            &unit_enum_names,
            &visible_type_names,
            &type_paths,
        ));
        out.push('\n');
    }

    if !active_bridges.is_empty() {
        out.push_str(&plugin_inbound::emit_plugin_error_helper(
            &source_crate,
            &config.error_type_name(),
            &config.error_constructor_expr(),
        ));
    }
    for (bridge_cfg, trait_def) in &active_bridges {
        out.push_str(&plugin_inbound::emit_inbound_wrapper(
            trait_def,
            bridge_cfg,
            api,
            &source_crate,
            &type_paths,
            &config.error_type_name(),
            &config.error_constructor_expr(),
        ));
        out.push('\n');
    }
    let mut options_field_from_emitted: std::collections::HashSet<String> = std::collections::HashSet::new();
    for (bridge_cfg, trait_def) in &active_bridges {
        if bridge_cfg.bind_via != BridgeBinding::OptionsField {
            continue;
        }
        let from_impls = plugin_inbound::emit_options_field_from_impls(
            bridge_cfg,
            api,
            &source_crate,
            &mut options_field_from_emitted,
        );
        if !from_impls.is_empty() {
            out.push_str(&from_impls);
            out.push('\n');
        }
        let (_factory_extern, factory_body) =
            plugin_inbound::emit_options_field_factory(trait_def, bridge_cfg, api, &source_crate);
        if !factory_body.is_empty() {
            out.push_str(&factory_body);
            out.push('\n');
        }
        let (_helper_extern, helper_body) =
            plugin_inbound::emit_options_field_options_helper(bridge_cfg, api, &source_crate);
        if !helper_body.is_empty() {
            out.push_str(&helper_body);
            out.push('\n');
        }
    }

    let streaming_shims = wrappers::emit_streaming_adapter_shims(&config.adapters, &source_crate);
    if !streaming_shims.is_empty() {
        out.push_str(&streaming_shims);
    }

    for ty in &extra_serde_param_types {
        let type_snake = AsSnakeCase(ty.name.as_str()).to_string();
        let type_name = &ty.name;
        let source_path_base =
            crate::codegen::generators::type_paths::resolve_type_path(type_name, &source_crate, &type_paths);
        let source_path = if ty.has_lifetime_params {
            format!("{source_path_base}<'static>")
        } else {
            source_path_base
        };
        json_bridge::emit_from_json_shim(&mut out, &type_snake, type_name, &source_path, type_name);
    }

    for ty in &streaming_item_types {
        let type_snake = AsSnakeCase(ty.name.as_str()).to_string();
        let type_name = &ty.name;
        let source_path_base =
            crate::codegen::generators::type_paths::resolve_type_path(type_name, &source_crate, &type_paths);
        let source_path = if ty.has_lifetime_params {
            format!("{source_path_base}<'static>")
        } else {
            source_path_base
        };
        json_bridge::emit_from_json_shim(&mut out, &type_snake, type_name, &source_path, type_name);
    }

    for ty in &json_fallback_types {
        let type_snake = AsSnakeCase(ty.name.as_str()).to_string();
        let type_name = &ty.name;
        let source_path_base =
            crate::codegen::generators::type_paths::resolve_type_path(type_name, &source_crate, &type_paths);
        let source_path = if ty.has_lifetime_params {
            format!("{source_path_base}<'static>")
        } else {
            source_path_base
        };
        json_bridge::emit_from_json_shim(&mut out, &type_snake, type_name, &source_path, type_name);
    }

    for en in &json_fallback_enums_filtered {
        let enum_snake = AsSnakeCase(en.name.as_str()).to_string();
        let enum_name = &en.name;
        let source_path =
            crate::codegen::generators::type_paths::resolve_type_path(enum_name, &source_crate, &type_paths);
        let map_expr = format!("{enum_name}::from");
        json_bridge::emit_from_json_shim(&mut out, &enum_snake, enum_name, &source_path, &map_expr);
    }

    out
}