alef 0.83.0

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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//! PyO3 (Python) backend: orchestration and `Backend` trait implementation.

pub(crate) mod binding_exclusions;
pub mod capsule;
mod capsule_methods;
mod cfg_fields;
#[cfg(test)]
mod cfg_variant_e2e_tests;
mod config;
mod config_opaque;
pub(in crate::backends::pyo3) mod constructors;
#[cfg(test)]
mod dataclass_closure_tests;
pub mod enums;
pub mod errors;
pub mod functions;
pub mod methods;
mod mutex;
mod opaque_helpers;
mod postprocess;
mod public_files;
mod serde_defaults;
pub mod service_api;
mod support_items;
#[cfg(test)]
mod tests;
pub mod types;
pub(in crate::backends::pyo3) use types::type_has_from_json;
// pub(crate): e2e::codegen::python calls `crate_has_serde` to mirror the pyo3 backend's
// crate-level serde detection, and `options_dataclass_type_names`/`options_return_dataclass_names`
// to know which type names `__init__.py` exports as the method-less `options.py` dataclass rather
// than the native `#[pyclass]` -- required before trusting the from_json eligibility predicate,
// which only knows what the native class carries, not which class the public name resolves to. ~keep
pub(crate) use types::{
    crate_has_serde, options_dataclass_type_names, options_return_dataclass_names, python_visible_field_name,
};
pub(in crate::backends::pyo3) mod wire_schema;

use crate::backends::pyo3::type_map::Pyo3Mapper;
use crate::codegen::builder::RustFileBuilder;
use crate::codegen::generators;
use crate::core::backend::{Backend, BuildConfig, BuildDependency, Capabilities, GeneratedFile};
use crate::core::config::{AdapterPattern, Language, ResolvedCrateConfig, resolve_output_dir};
use crate::core::ir::ApiSurface;
use ahash::AHashSet;
use std::path::PathBuf;

pub struct Pyo3Backend;

impl Backend for Pyo3Backend {
    fn name(&self) -> &str {
        "pyo3"
    }

    fn language(&self) -> Language {
        Language::Python
    }

    fn capabilities(&self) -> Capabilities {
        Capabilities {
            supports_async: true,
            supports_classes: true,
            supports_enums: true,
            supports_option: true,
            supports_result: true,
            supports_service_api: true,
            ..Capabilities::default()
        }
    }

    fn generate_bindings(&self, api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
        // to the core crate — which resolves the cfg itself — and emits no `#[cfg]` gate on the
        // wrapper, so two same-named entries would otherwise produce duplicate `#[pyfunction]`
        let deduped_api = crate::backends::ir_order::with_sorted_items(api).with_deduped_functions();
        let api = &deduped_api;

        // should store them as `Option<Py<PyAny>>` with `#[serde(skip)]` so the visitor can
        let mut trait_type_names: ahash::AHashSet<String> = api
            .types
            .iter()
            .filter(|t| t.is_trait)
            .map(|t| t.name.clone())
            .collect();
        for bridge in &config.trait_bridges {
            if crate::backends::pyo3::trait_bridge::active_bridge_trait(bridge, api).is_none() {
                continue;
            }
            if bridge.bind_via == crate::core::config::BridgeBinding::OptionsField
                && let Some(alias) = &bridge.type_alias
            {
                trait_type_names.insert(alias.clone());
            }
        }
        let mapper = Pyo3Mapper { trait_type_names };
        let core_import = config.core_import_name();
        // This binding's own configured feature set (already expanded through the core crate's
        // `[features]` graph), used to decide whether a FOREIGN-owned cfg-gated enum variant is
        // provably unreachable for this binding -- see
        // `codegen::conversions::enums::enum_conversion_needs_catch_all_for_features`. ~keep
        let enabled_features = crate::codegen::cfg::enabled_features_for_language(config, Language::Python);

        let output_dir = resolve_output_dir(config.output_paths.get("python"), &config.name, "crates/{name}-py/src/");
        let has_serde = crate_has_serde(config);
        let mut cfg = config::binding_config(&core_import, has_serde);
        let mut cfg_unsendable = config::unsendable_binding_config(&core_import, has_serde);

        let adapter_bodies = crate::adapters::build_adapter_bodies(config, Language::Python)?;

        let mut builder = RustFileBuilder::new().with_generated_header();
        support_items::add_generated_module_attributes(
            &mut builder,
            &config.extra_clippy_allows,
            &config.crate_attributes,
        );
        builder.add_import("pyo3::prelude::*");
        // import is needed — that would trigger clippy::single_component_path_imports.

        if has_serde {
            builder.add_import("serde_json");
        }

        for trait_path in generators::collect_trait_imports(api) {
            builder.add_import(&trait_path);
        }

        let has_async = api.functions.iter().any(|f| f.is_async && !f.sanitized)
            || api
                .types
                .iter()
                .any(|t| t.methods.iter().any(|m| m.is_async && !m.sanitized));
        if has_async {
            builder.add_import("pyo3_async_runtimes");
            let has_async_error = api
                .functions
                .iter()
                .any(|f| f.is_async && !f.sanitized && f.error_type.is_some())
                || api.types.iter().any(|t| {
                    t.methods
                        .iter()
                        .any(|m| m.is_async && !m.sanitized && m.error_type.is_some())
                });
            if has_async_error {
                builder.add_import("pyo3::exceptions::PyRuntimeError");
            }
        }

        // binding-side #[pyclass] wrapper structs and must be treated as opaque in return wrapping
        let mut opaque_types: AHashSet<String> = api
            .types
            .iter()
            .filter(|t| t.is_opaque)
            .map(|t| t.name.clone())
            .collect();
        // Capsule types bypass #[pyclass] generation entirely; opaque types that
        let early_capsule_types = config
            .python
            .as_ref()
            .map(|c| c.capsule_types.clone())
            .unwrap_or_default();
        for name in config.opaque_types.keys() {
            if !early_capsule_types.contains_key(name) {
                opaque_types.insert(name.clone());
            }
        }
        let data_enum_names: Vec<String> = api
            .enums
            .iter()
            .filter(|e| generators::enum_has_data_variants(e))
            .map(|e| e.name.clone())
            .collect();
        let bridge_type_aliases: Vec<String> = config
            .trait_bridges
            .iter()
            .filter(|b| crate::backends::pyo3::trait_bridge::active_bridge_trait(b, api).is_some())
            .filter_map(|b| b.type_alias.clone())
            .collect();
        let conversion_opaque_set: AHashSet<String> =
            opaque_types.iter().chain(bridge_type_aliases.iter()).cloned().collect();
        let mut opaque_names_vec: Vec<String> = opaque_types.iter().cloned().collect();
        let serializable_opaque_names_vec: Vec<String> = data_enum_names.clone();
        opaque_names_vec.extend(data_enum_names);
        opaque_names_vec.extend(bridge_type_aliases);
        let mut opaque_names_set: AHashSet<String> = opaque_names_vec.iter().cloned().collect();
        let mut changed = true;
        while changed {
            changed = false;
            for typ in api.types.iter().filter(|t| !t.is_opaque) {
                if opaque_names_set.contains(&typ.name) {
                    continue;
                }
                let has_opaque = typ
                    .fields
                    .iter()
                    .any(|f| generators::structs::field_references_opaque_type(&f.ty, &opaque_names_vec));
                if has_opaque {
                    opaque_names_vec.push(typ.name.clone());
                    opaque_names_set.insert(typ.name.clone());
                    changed = true;
                }
            }
        }
        cfg.opaque_type_names = &opaque_names_vec;
        cfg_unsendable.opaque_type_names = &opaque_names_vec;
        cfg.serializable_opaque_type_names = &serializable_opaque_names_vec;
        cfg_unsendable.serializable_opaque_type_names = &serializable_opaque_names_vec;
        // emitted `#[new]` filters out fields with `f.cfg.is_some()`, but the python
        let never_skip_cfg_field_names = cfg_fields::never_skip_cfg_field_names(api, config);
        cfg.never_skip_cfg_field_names = &never_skip_cfg_field_names;
        cfg_unsendable.never_skip_cfg_field_names = &never_skip_cfg_field_names;
        let mutex_types: AHashSet<String> = api
            .types
            .iter()
            .filter(|t| t.is_opaque && generators::type_needs_mutex(t))
            .map(|t| t.name.clone())
            .collect();
        let tokio_mutex_types: AHashSet<String> = api
            .types
            .iter()
            .filter(|t| t.is_opaque && generators::type_needs_tokio_mutex(t))
            .map(|t| t.name.clone())
            .collect();
        if !opaque_types.is_empty() {
            builder.add_import("std::sync::Arc");
            if mutex_types.iter().any(|n| !tokio_mutex_types.contains(n)) {
                builder.add_import("std::sync::Mutex");
            }
        }

        let type_ref_is_map = |ty: &crate::core::ir::TypeRef| matches!(ty, crate::core::ir::TypeRef::Map(_, _));
        let has_maps = api.types.iter().any(|t| {
            t.fields.iter().any(|f| type_ref_is_map(&f.ty))
                || t.methods
                    .iter()
                    .any(|m| m.params.iter().any(|p| type_ref_is_map(&p.ty)) || type_ref_is_map(&m.return_type))
        }) || api
            .functions
            .iter()
            .any(|f| f.params.iter().any(|p| type_ref_is_map(&p.ty)) || type_ref_is_map(&f.return_type));
        if has_maps {
            builder.add_import("std::collections::HashMap");
        }

        support_items::add_py_visitor_ref(&mut builder);

        support_items::add_json_helpers(&mut builder);

        let custom_mods = config.custom_modules.for_language(Language::Python);
        for module in custom_mods {
            builder.add_item(&format!("pub mod {module};"));
        }

        // `#[pyfunction]` entrypoints are compiled and can be registered in the module init.
        if !api.services.is_empty() {
            builder.add_item("pub mod service;");
        }

        for adapter in &config.adapters {
            match adapter.pattern {
                AdapterPattern::Streaming => {
                    let key = crate::adapters::stream_struct_key(adapter);
                    if let Some(struct_code) = adapter_bodies.get(&key) {
                        builder.add_item(struct_code);
                    }
                }
                AdapterPattern::CallbackBridge => {
                    let struct_key = format!("{}.__bridge_struct__", adapter.name);
                    let impl_key = format!("{}.__bridge_impl__", adapter.name);
                    if let Some(struct_code) = adapter_bodies.get(&struct_key) {
                        builder.add_item(struct_code);
                    }
                    if let Some(impl_code) = adapter_bodies.get(&impl_key) {
                        builder.add_item(impl_code);
                    }
                }
                _ => {}
            }
        }

        let py_exclude_functions: ahash::AHashSet<String> = config
            .python
            .as_ref()
            .map(|c| c.exclude_functions.iter().cloned().collect())
            .unwrap_or_default();
        // otherwise emit as a SECOND `#[pyfunction]` of the same Rust name — a redefinition
        let bridge_duck_register_fns: AHashSet<&str> = config
            .trait_bridges
            .iter()
            .filter(|b| crate::backends::pyo3::trait_bridge::active_bridge_trait(b, api).is_some())
            .filter_map(|b| crate::codegen::generators::trait_bridge::bridge_register_symbol(b))
            .collect();
        // Shared with the visitor trait bridge and the `.pyi` protocol stub, both of which write
        // a generated class name and must not name one this loop skips. ~keep
        let py_exclude_types = binding_exclusions::pyclass_absent_type_names(config, &api.types, &api.errors);
        // Types listed in capsule_types bypass #[pyclass] generation entirely — they are
        let capsule_types = config
            .python
            .as_ref()
            .map(|c| c.capsule_types.clone())
            .unwrap_or_default();

        let mut error_type_names: AHashSet<String> = AHashSet::new();
        for error in &api.errors {
            error_type_names.insert(error.name.clone());
            for variant in &error.variants {
                let exc_name = crate::codegen::error_gen::python_exception_name(&variant.name, &error.name);
                error_type_names.insert(exc_name);
            }
        }

        let error_converters: Vec<String> = api
            .errors
            .iter()
            .map(|e| {
                use heck::ToSnakeCase;
                format!("{}_to_py_err", e.name.to_snake_case())
            })
            .collect();

        // Track emitted #[pyclass] struct names to prevent duplicate definitions (E0255/E0428).
        let mut emitted_pyclass_names: AHashSet<&str> = AHashSet::new();
        // core types whose `impl Default` is `#[alef(skip)]`'d (so `has_default` is false on the
        let default_required_types = cfg_fields::default_required_types(api);
        // whose type is not in the convertible set) must keep #[derive(Default)] instead of
        let core_to_binding_for_default = crate::codegen::conversions::core_to_binding_convertible_types(api, &[]);
        cfg.emit_delegating_default_for_types = Some(&core_to_binding_for_default);
        cfg_unsendable.emit_delegating_default_for_types = Some(&core_to_binding_for_default);
        // Same convertible set already gates `gen_from_core_to_binding_cfg` below (see
        // `core_to_binding` a few hundred lines down) -- reusing it here guarantees the
        // `From<core::Type>` a delegating `Deserialize` needs is always emitted too. ~keep
        cfg.delegate_deserialize_to_core_for_types = Some(&core_to_binding_for_default);
        cfg_unsendable.delegate_deserialize_to_core_for_types = Some(&core_to_binding_for_default);
        for typ in api
            .types
            .iter()
            .filter(|typ| !typ.is_trait && !py_exclude_types.contains(&typ.name))
        {
            if error_type_names.contains(typ.name.as_str()) {
                continue;
            }
            // Capsule types bypass #[pyclass] entirely — they travel as raw PyCapsule handles
            // produce an unused #[pyclass] that conflicts with the capsule-based call sites.
            if capsule_types.contains_key(typ.name.as_str()) {
                continue;
            }
            if !emitted_pyclass_names.insert(typ.name.as_str()) {
                continue;
            }
            let type_cfg = if opaque_types.contains(typ.name.as_str()) {
                &cfg_unsendable
            } else {
                &cfg
            };
            if typ.is_opaque {
                let mut struct_code = generators::gen_opaque_struct(typ, type_cfg);
                let mut impl_block = generators::gen_opaque_impl_block(
                    typ,
                    &mapper,
                    type_cfg,
                    &opaque_types,
                    &mutex_types,
                    &adapter_bodies,
                );
                if tokio_mutex_types.contains(&typ.name) {
                    struct_code = mutex::rewrite_to_tokio_mutex_struct(&struct_code);
                    impl_block = mutex::rewrite_to_tokio_mutex_impl(&impl_block);
                }
                // PyCapsule objects instead of the (non-existent) #[pyclass] wrapper structs.
                if !capsule_types.is_empty() {
                    impl_block =
                        capsule_methods::rewrite_capsule_methods(impl_block, typ, &capsule_types, &error_converters);
                }
                // the type into a Python-level constructor by appending a `#[new]
                // block. pyo3 forbids multiple `#[pymethods] impl T` blocks (without
                // alongside the existing `#[staticmethod] pub fn new`. The two
                // `#[new]` attribute regardless of the Rust name.
                if typ.is_variant_wrapper
                    && !impl_block.is_empty()
                    && let Some(ctor_body) = opaque_helpers::variant_wrapper_constructor_body(typ, &mapper)
                {
                    impl_block = opaque_helpers::inject_into_impl_block(&impl_block, &ctor_body);
                }
                builder.add_item(&struct_code);
                if !impl_block.is_empty() {
                    builder.add_item(&impl_block);
                }
                if opaque_helpers::should_emit_default_impl(typ, &impl_block, &default_required_types) {
                    builder.add_item(&opaque_helpers::emit_default_impl(typ));
                }
                // Client constructor — emit a separate #[pymethods] impl with #[new]
                if let Some(ctor) = config.client_constructors.get(&typ.name) {
                    let ctor_body = generators::gen_opaque_constructor(ctor, &typ.name, &core_import, "#[new]");
                    let ctor_impl = format!("#[pymethods]\nimpl {} {{\n{}}}", typ.name, ctor_body);
                    builder.add_item(&ctor_impl);
                }
            } else {
                // gen_struct adds #[derive(Default)] when typ.has_default is true,
                // attribute (e.g. `#[pyo3(get, name = "class")]`) and the serde rename
                // attribute (`#[serde(rename = "class")]`) so the user-facing API is unchanged.
                let type_name = typ.name.clone();
                let config_ref = config;
                builder.add_item(&generators::gen_struct_with_rename(
                    typ,
                    &mapper,
                    type_cfg,
                    |field| {
                        let is_json_field = matches!(field.ty, crate::core::ir::TypeRef::Json);
                        let is_opt_json_field = field.optional && is_json_field
                            || matches!(&field.ty, crate::core::ir::TypeRef::Optional(inner) if matches!(inner.as_ref(), crate::core::ir::TypeRef::Json));
                        let json_attr = if is_opt_json_field {
                            Some("serde(default, deserialize_with = \"alef_json_str_opt::deserialize\")".to_string())
                        } else if is_json_field {
                            Some("serde(default, deserialize_with = \"alef_json_str::deserialize\")".to_string())
                        } else {
                            None
                        };

                        let mut attrs = if config_ref
                            .resolve_field_name(crate::core::config::Language::Python, &type_name, &field.name)
                            .is_some()
                        {
                            // `resolve_field_name` folds two renames that need opposite treatment
                            // here; `python_visible_field_name` owns that rule so every reader of
                            // the published attribute name gets the same answer.
                            //
                            // `serde(rename)` stays on the *wire* name in both cases, and prefers
                            // the core type's own `#[serde(rename)]` when it has one -- deriving
                            // the JSON key from the escaped Rust field name instead would silently
                            // move it. ~keep
                            let python_name = types::python_visible_field_name(config_ref, &type_name, field);
                            let wire_name = field.serde_rename.clone().unwrap_or_else(|| field.name.clone());
                            let mut attrs = vec![
                                format!("pyo3(get, name = \"{python_name}\")"),
                                format!("serde(rename = \"{wire_name}\")"),
                            ];
                            if let Some(a) = json_attr {
                                attrs.push(a);
                            }
                            attrs
                        } else if let Some(a) = json_attr {
                            vec![a]
                        } else {
                            vec![]
                        };
                        // A field whose core `#[serde(default = "path")]` names a private,
                        // unresolvable free function (e.g. `default_true`), or whose folded
                        // default is a resolved core function on an `Option<T>` field, cannot
                        // have that path mirrored verbatim -- `serde_default_field_attr`'s
                        // fallback in `codegen::generators::structs` correctly declines it and
                        // would leave the field required. Synthesize our own named function from
                        // the same folded `Default` value the extractor already proved for this
                        // field instead. Pushed here, before that fallback runs inside
                        // `gen_struct_with_rename`, whose `already_emitted_attrs` guard skips a
                        // field that already carries a `serde(default...)` attribute. ~keep
                        if !attrs.iter().any(|a| a.starts_with("serde(default"))
                            && let Some(fn_name) = serde_defaults::serde_default_fn_name(typ, field)
                        {
                            attrs.push(format!("serde(default = \"crate::serde_defaults::{fn_name}\")"));
                        }
                        attrs
                    },
                    |field| config_ref.resolve_field_name(crate::core::config::Language::Python, &type_name, &field.name),
                ));
                let py_field_renames: std::collections::HashMap<String, String> = typ
                    .fields
                    .iter()
                    .filter_map(|field| {
                        config_ref
                            .resolve_field_name(crate::core::config::Language::Python, &type_name, &field.name)
                            .map(|renamed| (field.name.clone(), renamed))
                    })
                    .collect();
                let renames_ref = if py_field_renames.is_empty() {
                    None
                } else {
                    Some(&py_field_renames)
                };

                // A `#[pyo3(get)]` field getter and a `#[pymethods]` wrapper with the same
                // Python name both bind that name on the class; pyo3 registers the method last,
                // which silently kills the getter and makes the attribute a bound method. Drop
                // the wrapper so the field stays readable, matching every other backend. ~keep
                let py_visible_field_names: std::collections::HashSet<&str> =
                    crate::codegen::shared::binding_fields(&typ.fields)
                        .map(|field| {
                            py_field_renames
                                .get(&field.name)
                                .map_or(field.name.as_str(), String::as_str)
                        })
                        .collect();
                let typ_without_field_collisions;
                let impl_typ = if typ
                    .methods
                    .iter()
                    .any(|method| !method.is_static && py_visible_field_names.contains(method.name.as_str()))
                {
                    let mut filtered = typ.clone();
                    filtered
                        .methods
                        .retain(|method| method.is_static || !py_visible_field_names.contains(method.name.as_str()));
                    typ_without_field_collisions = filtered;
                    &typ_without_field_collisions
                } else {
                    typ
                };

                let mut impl_block = generators::gen_impl_block_with_renames(
                    impl_typ,
                    &mapper,
                    type_cfg,
                    &adapter_bodies,
                    &opaque_types,
                    renames_ref,
                );

                impl_block = constructors::replace_constructor_with_serde_rename(
                    &impl_block,
                    typ,
                    &mapper,
                    type_cfg,
                    renames_ref,
                    &config.trait_bridges,
                    type_cfg.never_skip_cfg_field_names,
                    api,
                );
                // Inject from_json staticmethod into the existing #[pymethods] block when serde
                if types::type_has_from_json(typ, api, has_serde) {
                    let from_json_method = "    #[staticmethod]\n    \
                         fn from_json(json_str: String) -> pyo3::PyResult<Self> {\n        \
                         serde_json::from_str::<Self>(&json_str)\n            \
                         .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))\n    \
                         }"
                    .to_string();
                    if impl_block.is_empty() {
                        let type_name = &typ.name;
                        impl_block = format!("#[pymethods]\nimpl {type_name} {{\n{from_json_method}\n}}");
                    } else {
                        if let Some(close_pos) = impl_block.rfind('}') {
                            impl_block.insert_str(close_pos, &format!("\n{from_json_method}\n"));
                        }
                    }
                }
                if !impl_block.is_empty() {
                    builder.add_item(&impl_block);
                }
            }
        }
        config_opaque::emit_wrappers(
            &mut builder,
            config,
            &capsule_types,
            &emitted_pyclass_names,
            &error_type_names,
            opaque_types.is_empty(),
        );

        // Referenced by #[serde(default = "crate::serde_defaults::...")] on struct fields.
        if has_serde && let Some(serde_module) = serde_defaults::gen_serde_defaults_module(api) {
            builder.add_item(&serde_module);
        }

        // `@dataclass`/`dict`, not the compiled `#[pyclass]`) so enum-variant payloads of those
        let coercible_dto_names = wire_schema::coercible_dto_names(api, config);
        let coercion_section =
            wire_schema::emit_dto_coercion_section(api, has_serde, &coercible_dto_names, &core_import);
        if !coercion_section.is_empty() {
            builder.add_item(&coercion_section);
        }

        for e in &api.enums {
            if generators::enum_has_data_variants(e) {
                // Emit a `#[staticmethod]` constructor for each data-carrying struct variant
                // magic `type="..."` string. The `#[new]` dict/kwargs/string constructor stays as-is
                let data_enum_code =
                    generators::gen_pyo3_data_enum_with_coercion(e, &core_import, Some(&mapper), &coercible_dto_names);
                // in `default_required_types`) but the core `impl Default` is `#[alef(skip)]`'d
                let needs_default = default_required_types.contains(e.name.as_str())
                    && !data_enum_code.contains(&format!("impl Default for {}", e.name));
                builder.add_item(&data_enum_code);
                if needs_default {
                    builder.add_item(&opaque_helpers::emit_inner_default_impl(&e.name));
                }
            } else {
                builder.add_item(&generators::gen_enum(e, &cfg, Some(enabled_features.as_slice())));
            }
        }
        for f in &api.functions {
            if py_exclude_functions.contains(&f.name) {
                continue;
            }
            if bridge_duck_register_fns.contains(f.name.as_str()) {
                continue;
            }
            crate::codegen::mut_writeback::reject_unsupported_writeback(
                &f.name,
                &f.params,
                &f.return_type,
                &opaque_types,
            )?;
            let bridge_param = crate::backends::pyo3::trait_bridge::find_bridge_param(f, &config.trait_bridges);
            let bridge_field =
                crate::codegen::generators::trait_bridge::find_bridge_field(f, &api.types, &config.trait_bridges);
            if let Some((param_idx, bridge_cfg)) = bridge_param {
                builder.add_item(&crate::backends::pyo3::trait_bridge::gen_bridge_function(
                    api,
                    f,
                    param_idx,
                    bridge_cfg,
                    &mapper,
                    &cfg,
                    &adapter_bodies,
                    &opaque_types,
                    &core_import,
                    &error_converters,
                ));
            } else if let Some(ref bm) = bridge_field {
                builder.add_item(&crate::backends::pyo3::trait_bridge::gen_bridge_field_function(
                    api,
                    f,
                    bm,
                    bm.bridge,
                    &mapper,
                    &cfg,
                    &opaque_types,
                    &core_import,
                    &error_converters,
                ));
            } else if !capsule_types.is_empty() && capsule::function_involves_capsule(f, &capsule_types) {
                builder.add_item(&capsule::gen_capsule_function(
                    f,
                    &capsule_types,
                    &core_import,
                    &error_converters,
                ));
            } else {
                let mut fn_code =
                    generators::gen_function_with_mutex(f, &mapper, &cfg, &adapter_bodies, &opaque_types, &mutex_types);
                if !tokio_mutex_types.is_empty()
                    && fn_code.contains("Arc::new(std::sync::Mutex::new(")
                    && mutex::returns_tokio_mutex_type(f, &tokio_mutex_types)
                {
                    fn_code = fn_code.replace("Arc::new(std::sync::Mutex::new(", "Arc::new(tokio::sync::Mutex::new(");
                }
                builder.add_item(&fn_code);
            }
        }

        // Trait marker classes — emit empty #[pyclass] structs for plugin traits so they can be
        for bridge_cfg in &config.trait_bridges {
            if crate::backends::pyo3::trait_bridge::active_bridge_trait(bridge_cfg, api).is_none() {
                continue;
            }
            let trait_name = &bridge_cfg.trait_name;
            if !emitted_pyclass_names.insert(trait_name) {
                continue;
            }
            let marker_class = format!("#[pyclass(name = \"{trait_name}\")]\npub struct Py{trait_name}Marker;\n");
            builder.add_item(&marker_class);
        }

        if !config.trait_bridges.is_empty() {
            let needs_async_trait = config.trait_bridges.iter().any(|bridge_cfg| {
                api.types
                    .iter()
                    .find(|t| t.is_trait && t.name == bridge_cfg.trait_name)
                    .is_some_and(|trait_type| trait_type.methods.iter().any(|m| m.is_async))
            });
            if needs_async_trait {
                builder.add_import("async_trait::async_trait");
            }
            if opaque_types.is_empty() {
                builder.add_import("std::sync::Arc");
            }
            let reexported_types = config
                .python
                .as_ref()
                .map(|c| c.reexported_types.clone())
                .unwrap_or_default();
            let bridge_pyclass_absent_types =
                binding_exclusions::pyclass_absent_type_names(config, &api.types, &api.errors);
            // Precomputed once for this trait-bridge loop rather than inside
            // `context_binding_class` per bridge -- the fixpoint is transitive over every type and
            // field in `api`, so a per-bridge recompute scales as bridges x fixpoint instead of
            // once. ~keep
            let bridge_core_to_binding_convertible_types =
                crate::codegen::conversions::core_to_binding_convertible_types(api, &[]);
            builder.add_item(&crate::backends::pyo3::template_env::render(
                "trait_bridge/options_from_native_helper.jinja",
                minijinja::context! {
                    options_module => format!("{}.options", config.python_module_name()),
                },
            ));
            for bridge_cfg in &config.trait_bridges {
                if let Some(trait_type) = crate::backends::pyo3::trait_bridge::active_bridge_trait(bridge_cfg, api) {
                    let bridge = crate::backends::pyo3::trait_bridge::gen_trait_bridge_with_absent_types(
                        trait_type,
                        bridge_cfg,
                        &core_import,
                        &config.error_type_name(),
                        &config.error_constructor_expr(),
                        api,
                        &reexported_types,
                        &bridge_pyclass_absent_types,
                        &bridge_core_to_binding_convertible_types,
                    )?;
                    for imp in &bridge.imports {
                        builder.add_import(imp);
                    }
                    builder.add_item(&bridge.code);
                }
            }
        }

        let module_name = config.python_module_name();
        let mut seen_exceptions = AHashSet::new();
        for error in &api.errors {
            builder.add_item(&crate::codegen::error_gen::gen_pyo3_error_types(
                error,
                &module_name,
                &mut seen_exceptions,
            ));
            builder.add_item(&crate::codegen::error_gen::gen_pyo3_error_converter(
                error,
                &core_import,
            ));
            // Emit #[pymethods] impl block when the error exposes introspection methods.
            // The impl adds #[getter] properties that read from the exception args tuple
            let methods_impl = crate::codegen::error_gen::gen_pyo3_error_methods_impl(error);
            if !methods_impl.is_empty() {
                builder.add_item(&methods_impl);
            }
        }

        let binding_to_core = crate::codegen::conversions::convertible_types(api);
        let core_to_binding = crate::codegen::conversions::core_to_binding_convertible_types(api, &[]);
        let input_types = crate::codegen::conversions::input_type_names(api);
        let py_field_renames = cfg_fields::py_field_renames(api, config);
        let pyo3_conversion_cfg = crate::codegen::conversions::ConversionConfig {
            option_duration_on_defaults: true,
            binding_field_renames: if py_field_renames.is_empty() {
                None
            } else {
                Some(&py_field_renames)
            },
            opaque_types: Some(&conversion_opaque_set),
            never_skip_cfg_field_names: &never_skip_cfg_field_names,
            configured_features: Some(enabled_features.as_slice()),
            // `generators::gen_enum` (the fieldless-enum wrapper declaration below) now drops a
            // FOREIGN cfg-gated variant this binding's own feature set proves unreachable, so the
            // binding->core catch-all decision must know the declaration can leave a gap-free
            // match on its own -- mirroring NAPI, the only other backend that sets this. Scoped
            // correctly: this flag only affects `gen_enum_from_binding_to_core_cfg`, and pyo3
            // reaches that only for the same fieldless enums `generators::gen_enum` declares (data
            // enums use the struct-wrapper path below instead, which never calls either function).
            // ~keep
            declaration_drops_unreachable_foreign_variants: true,
            ..Default::default()
        };
        for typ in api
            .types
            .iter()
            .filter(|typ| !typ.is_trait && !py_exclude_types.contains(&typ.name))
        {
            if input_types.contains(&typ.name)
                && crate::codegen::conversions::can_generate_conversion(typ, &binding_to_core)
            {
                builder.add_item(&crate::codegen::conversions::gen_from_binding_to_core_cfg(
                    typ,
                    &core_import,
                    &pyo3_conversion_cfg,
                ));
            }
            if crate::codegen::conversions::core_to_binding_from_impl_emitted(typ, &core_to_binding) {
                builder.add_item(&crate::codegen::conversions::gen_from_core_to_binding_cfg(
                    typ,
                    &core_import,
                    &conversion_opaque_set,
                    &pyo3_conversion_cfg,
                ));
            }
        }
        // Fieldless enums only: a data-carrying enum (`enum_has_data_variants`) never reaches a
        // `From<core::Enum> for BindingEnum>` match at all in PyO3 -- it is represented as a
        // per-variant `#[pyclass]` union instead, so there is no catch-all arm for
        // `configured_features` to prune here. `_cfg` variants (not the plain
        // `gen_enum_from_binding_to_core`/`gen_enum_from_core_to_binding`, which default
        // `configured_features` to `None`) are required so a foreign cfg-gated fieldless variant
        // this binding's own feature set proves unreachable does not leave behind an unreachable
        // `_ => Default::default()` catch-all under `-D warnings` (alef #544). Reusing
        // `pyo3_conversion_cfg` is safe here: every field it sets besides `configured_features`
        // (`option_duration_on_defaults`, `binding_field_renames`, `opaque_types`,
        // `never_skip_cfg_field_names`) is unread by the enum conversion path. ~keep
        for e in &api.enums {
            if generators::enum_has_data_variants(e) {
                continue;
            }
            if input_types.contains(&e.name) && crate::codegen::conversions::can_generate_enum_conversion(e) {
                builder.add_item(&crate::codegen::conversions::gen_enum_from_binding_to_core_cfg(
                    e,
                    &core_import,
                    &pyo3_conversion_cfg,
                ));
            }
            if crate::codegen::conversions::can_generate_enum_conversion_from_core(e) {
                builder.add_item(&crate::codegen::conversions::gen_enum_from_core_to_binding_cfg(
                    e,
                    &core_import,
                    &pyo3_conversion_cfg,
                ));
            }
        }

        if has_async {
            builder.add_item(&methods::gen_async_runtime_init());
        }

        builder.add_item(&methods::gen_module_init(&config.python_module_name(), api, config));

        let mut content = builder.build();
        postprocess::clear_bridge_builder_opaque_params(&mut content, config);
        postprocess::add_options_field_visitor_fallback(&mut content, api, config, &core_import);
        postprocess::wrap_optional_default_args(&mut content, api);

        Ok(vec![GeneratedFile {
            path: PathBuf::from(&output_dir).join("lib.rs"),
            content,
            generated_header: false,
        }])
    }

    fn generate_type_stubs(
        &self,
        api: &ApiSurface,
        config: &ResolvedCrateConfig,
    ) -> anyhow::Result<Vec<GeneratedFile>> {
        // Rust binding does — Python has no `#[cfg]`, so two same-named defs in the `.pyi`
        let deduped_api = crate::backends::ir_order::with_sorted_items(api).with_deduped_functions();
        public_files::generate_type_stubs(&deduped_api, config)
    }

    fn generate_public_api(
        &self,
        api: &ApiSurface,
        config: &ResolvedCrateConfig,
    ) -> anyhow::Result<Vec<GeneratedFile>> {
        let deduped_api = crate::backends::ir_order::with_sorted_items(api).with_deduped_functions();
        public_files::generate_public_api(&deduped_api, config)
    }

    fn generate_service_api(
        &self,
        api: &ApiSurface,
        config: &ResolvedCrateConfig,
    ) -> anyhow::Result<Vec<GeneratedFile>> {
        service_api::generate(&crate::backends::ir_order::with_sorted_items(api), config)
    }

    fn build_config(&self) -> Option<BuildConfig> {
        Some(BuildConfig {
            tool: "maturin",
            crate_suffix: "-py",
            build_dep: BuildDependency::None,
            post_build: vec![],
        })
    }

    fn trait_bridge_registration_surface(
        &self,
        api: &ApiSurface,
        config: &ResolvedCrateConfig,
    ) -> Vec<crate::core::backend::TraitBridgeRegistrationSurface> {
        config
            .trait_bridges
            .iter()
            .filter_map(|bridge| {
                crate::backends::pyo3::trait_bridge::active_bridge_trait(bridge, api)?;
                let surface = crate::core::backend::TraitBridgeRegistrationSurface {
                    trait_name: bridge.trait_name.clone(),
                    register_symbol: crate::codegen::generators::trait_bridge::bridge_register_symbol(bridge)
                        .map(str::to_owned),
                    unregister_symbol: bridge.unregister_fn.clone(),
                    clear_symbol: bridge.clear_fn.clone(),
                };
                let emits_nothing = surface.register_symbol.is_none()
                    && surface.unregister_symbol.is_none()
                    && surface.clear_symbol.is_none();
                (!emits_nothing).then_some(surface)
            })
            .collect()
    }
}