alef 0.58.3

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
//! PyO3-specific trait bridge code generation.
//!
//! Generates Rust wrapper structs that implement Rust traits by delegating
//! to Python objects via PyO3.

mod bridge_methods;
mod generator;
mod options_field;
mod registry;
mod visitor_bridge;

pub use crate::codegen::generators::trait_bridge::find_bridge_param;
pub use bridge_methods::gen_bridge_function;
pub use generator::Pyo3BridgeGenerator;
pub use options_field::gen_bridge_field_function;
pub use registry::{
    collect_bridge_clear_fns, collect_bridge_register_fns, collect_bridge_unregister_fns, trait_bridge_imports,
};

use crate::codegen::generators::trait_bridge::{BridgeOutput, TraitBridgeSpec, gen_bridge_all};
use crate::core::config::TraitBridgeConfig;
use crate::core::ir::{ApiSurface, TypeDef};
use std::collections::{HashMap, HashSet};
use visitor_bridge::gen_visitor_bridge;

pub fn gen_trait_bridge(
    trait_type: &TypeDef,
    bridge_cfg: &TraitBridgeConfig,
    core_import: &str,
    error_type: &str,
    error_constructor: &str,
    api: &ApiSurface,
    reexported_types: &[String],
) -> anyhow::Result<BridgeOutput> {
    let type_paths: HashMap<String, String> = api
        .types
        .iter()
        .map(|t| (t.name.clone(), t.rust_path.replace('-', "_")))
        .chain(
            api.enums
                .iter()
                .map(|e| (e.name.clone(), e.rust_path.replace('-', "_"))),
        )
        .chain(
            api.excluded_type_paths
                .iter()
                .map(|(name, path)| (name.clone(), path.replace('-', "_"))),
        )
        .collect();

    let is_visitor_bridge = bridge_cfg.type_alias.is_some()
        && bridge_cfg.register_fn.is_none()
        && bridge_cfg.super_trait.is_none()
        && trait_type.methods.iter().all(|m| m.has_default_impl);

    if is_visitor_bridge {
        let trait_path = trait_type.rust_path.replace('-', "_");
        let struct_name = crate::codegen::generators::trait_bridge::bridge_wrapper_name("Py", bridge_cfg);
        let code = gen_visitor_bridge(
            trait_type,
            bridge_cfg,
            &struct_name,
            &trait_path,
            core_import,
            &type_paths,
            api,
        )?;
        Ok(BridgeOutput { imports: vec![], code })
    } else {
        // Python object (the `#[pyclass]`, built via the same `From<core::T>` conversion used for
        let struct_param_types =
            crate::codegen::generators::trait_bridge::native_marshalled_struct_params(trait_type, api);
        let struct_return_types =
            crate::codegen::generators::trait_bridge::native_marshalled_struct_returns(trait_type, api);
        let forwardable_defaulted =
            crate::codegen::generators::trait_bridge::forwardable_defaulted_method_names(trait_type, api);
        let options_dataclass_types =
            crate::backends::pyo3::gen_bindings::options_dataclass_type_names(api, reexported_types);
        let unit_enum_return_types: HashSet<String> = api
            .enums
            .iter()
            .filter(|e| e.variants.iter().all(|v| v.fields.is_empty()))
            .map(|e| e.name.clone())
            .collect();
        let generator = Pyo3BridgeGenerator {
            core_import: core_import.to_string(),
            type_paths: type_paths.clone(),
            error_type: error_type.to_string(),
            struct_param_types,
            struct_return_types,
            forwardable_defaulted,
            options_dataclass_types,
            unit_enum_return_types,
        };
        let lifetime_type_names: HashSet<String> = api
            .types
            .iter()
            .filter(|t| t.has_lifetime_params)
            .map(|t| t.name.clone())
            .collect();
        let spec = TraitBridgeSpec {
            trait_def: trait_type,
            bridge_config: bridge_cfg,
            core_import,
            wrapper_prefix: "Py",
            type_paths,
            lifetime_type_names,
            error_type: error_type.to_string(),
            error_constructor: error_constructor.to_string(),
        };
        Ok(gen_bridge_all(&spec, &generator))
    }
}

mod tests {
    /// Trait callbacks must run inside the caller's contextvars Context so any ContextVar
    /// set by the caller is visible inside the callback. The generated bridge body must capture
    /// `contextvars.copy_context()` and invoke the host method via `ctx.run(bound_method, ...)`
    /// (rendered as `call_method1("run", ...)`) rather than calling the method directly.
    /// Regression test for issue #137.
    #[test]
    fn trait_callback_runs_in_caller_contextvars_context() {
        use crate::codegen::generators::trait_bridge::{TraitBridgeGenerator, TraitBridgeSpec};
        use crate::core::config::TraitBridgeConfig;
        use crate::core::ir::{MethodDef, ParamDef, ReceiverKind, TypeDef, TypeRef};
        use std::collections::{HashMap, HashSet};

        let trait_def = TypeDef {
            name: "SampleService".to_owned(),
            rust_path: "sample_core::SampleService".to_owned(),
            is_trait: true,
            is_opaque: true,
            ..TypeDef::default()
        };
        let bridge_cfg = TraitBridgeConfig {
            trait_name: "SampleService".to_owned(),
            register_fn: Some("register_sample".to_owned()),
            registry_getter: Some("sample_core::registry::get".to_owned()),
            ..TraitBridgeConfig::default()
        };
        let spec = TraitBridgeSpec {
            trait_def: &trait_def,
            bridge_config: &bridge_cfg,
            core_import: "sample_core",
            wrapper_prefix: "Py",
            type_paths: HashMap::new(),
            lifetime_type_names: HashSet::new(),
            error_type: "SampleError".to_owned(),
            error_constructor: "SampleError::Message { message: {msg} }".to_owned(),
        };
        let generator = super::Pyo3BridgeGenerator {
            core_import: "sample_core".to_owned(),
            type_paths: HashMap::new(),
            error_type: "SampleError".to_owned(),
            struct_param_types: HashSet::new(),
            struct_return_types: HashSet::new(),
            forwardable_defaulted: HashSet::new(),
            options_dataclass_types: HashSet::new(),
            unit_enum_return_types: HashSet::new(),
        };

        let make_method = |is_async: bool| MethodDef {
            name: "process".to_owned(),
            params: vec![ParamDef {
                name: "text".to_owned(),
                ty: TypeRef::String,
                ..ParamDef::default()
            }],
            return_type: TypeRef::String,
            is_async,
            error_type: Some("SampleError".to_owned()),
            receiver: Some(ReceiverKind::Ref),
            ..MethodDef::default()
        };

        let async_body = generator.gen_async_method_body(&make_method(true), &spec);
        assert!(
            async_body.contains("copy_context"),
            "async bridge must capture the caller's contextvars context:\n{async_body}"
        );
        assert!(
            async_body.contains("call_method1(\"run\""),
            "async bridge must invoke the host method via ctx.run:\n{async_body}"
        );

        let sync_body = generator.gen_sync_method_body(&make_method(false), &spec);
        assert!(
            sync_body.contains("copy_context"),
            "sync bridge must capture the caller's contextvars context:\n{sync_body}"
        );
        assert!(
            sync_body.contains("call_method1(\"run\""),
            "sync bridge must invoke the host method via ctx.run:\n{sync_body}"
        );
    }

    /// When a host returns a value that does not match a struct return type, the bridge
    /// deserializes it via `serde_json::from_str::<ReturnType>(...)`. The failure message must
    /// name the expected return TYPE and hint that the value must be a mapping matching the
    /// type's fields, so the host can fix their return value. The serde error (`{e}`) already
    /// carries the offending field/path. Regression test for issue #138.
    #[test]
    fn trait_callback_deserialize_error_names_return_type() {
        use crate::codegen::generators::trait_bridge::{TraitBridgeGenerator, TraitBridgeSpec};
        use crate::core::config::TraitBridgeConfig;
        use crate::core::ir::{MethodDef, ReceiverKind, TypeDef, TypeRef};
        use std::collections::{HashMap, HashSet};

        let trait_def = TypeDef {
            name: "SampleService".to_owned(),
            rust_path: "sample_core::SampleService".to_owned(),
            is_trait: true,
            is_opaque: true,
            ..TypeDef::default()
        };
        let bridge_cfg = TraitBridgeConfig {
            trait_name: "SampleService".to_owned(),
            register_fn: Some("register_sample".to_owned()),
            registry_getter: Some("sample_core::registry::get".to_owned()),
            ..TraitBridgeConfig::default()
        };
        let spec = TraitBridgeSpec {
            trait_def: &trait_def,
            bridge_config: &bridge_cfg,
            core_import: "sample_core",
            wrapper_prefix: "Py",
            type_paths: HashMap::new(),
            lifetime_type_names: HashSet::new(),
            error_type: "SampleError".to_owned(),
            error_constructor: "SampleError::Message { message: {msg} }".to_owned(),
        };
        let generator = super::Pyo3BridgeGenerator {
            core_import: "sample_core".to_owned(),
            type_paths: HashMap::new(),
            error_type: "SampleError".to_owned(),
            struct_param_types: HashSet::new(),
            struct_return_types: HashSet::new(),
            forwardable_defaulted: HashSet::new(),
            options_dataclass_types: HashSet::new(),
            unit_enum_return_types: HashSet::new(),
        };

        let make_method = |is_async: bool| MethodDef {
            name: "build".to_owned(),
            params: vec![],
            return_type: TypeRef::Named("Doc".to_owned()),
            is_async,
            error_type: Some("SampleError".to_owned()),
            receiver: Some(ReceiverKind::Ref),
            ..MethodDef::default()
        };

        for is_async in [true, false] {
            let body = if is_async {
                generator.gen_async_method_body(&make_method(true), &spec)
            } else {
                generator.gen_sync_method_body(&make_method(false), &spec)
            };
            assert!(
                body.contains("expected return type `Doc`"),
                "deserialize error must name the expected return type `Doc` (is_async={is_async}):\n{body}"
            );
            assert!(
                body.contains("must be a mapping"),
                "deserialize error must hint the value must be a mapping matching the type's fields (is_async={is_async}):\n{body}"
            );
        }
    }

    /// When the return type is a native-marshalled struct, the bridge tries to extract the host's
    /// native binding object first (and convert via `From<Binding>`), falling back to the JSON
    /// mapping path. Return-side counterpart to the native-arg marshalling. See issue #153.
    #[test]
    fn trait_callback_native_struct_return_extracts_native_object_first() {
        use crate::codegen::generators::trait_bridge::{TraitBridgeGenerator, TraitBridgeSpec};
        use crate::core::config::TraitBridgeConfig;
        use crate::core::ir::{MethodDef, ReceiverKind, TypeDef, TypeRef};
        use std::collections::{HashMap, HashSet};

        let trait_def = TypeDef {
            name: "SampleService".to_owned(),
            rust_path: "sample_core::SampleService".to_owned(),
            is_trait: true,
            is_opaque: true,
            ..TypeDef::default()
        };
        let bridge_cfg = TraitBridgeConfig {
            trait_name: "SampleService".to_owned(),
            register_fn: Some("register_sample".to_owned()),
            registry_getter: Some("sample_core::registry::get".to_owned()),
            ..TraitBridgeConfig::default()
        };
        let spec = TraitBridgeSpec {
            trait_def: &trait_def,
            bridge_config: &bridge_cfg,
            core_import: "sample_core",
            wrapper_prefix: "Py",
            type_paths: HashMap::new(),
            lifetime_type_names: HashSet::new(),
            error_type: "SampleError".to_owned(),
            error_constructor: "SampleError::Message { message: {msg} }".to_owned(),
        };
        let generator = super::Pyo3BridgeGenerator {
            core_import: "sample_core".to_owned(),
            type_paths: HashMap::new(),
            error_type: "SampleError".to_owned(),
            struct_param_types: HashSet::new(),
            struct_return_types: HashSet::from(["Doc".to_owned()]),
            forwardable_defaulted: HashSet::new(),
            options_dataclass_types: HashSet::new(),
            unit_enum_return_types: HashSet::new(),
        };

        let make_method = |is_async: bool| MethodDef {
            name: "build".to_owned(),
            params: vec![],
            return_type: TypeRef::Named("Doc".to_owned()),
            is_async,
            error_type: Some("SampleError".to_owned()),
            receiver: Some(ReceiverKind::Ref),
            ..MethodDef::default()
        };

        for is_async in [true, false] {
            let body = if is_async {
                generator.gen_async_method_body(&make_method(true), &spec)
            } else {
                generator.gen_sync_method_body(&make_method(false), &spec)
            };
            assert!(
                body.contains("extract::<Doc>()"),
                "native return must try extracting the binding object `Doc` first (is_async={is_async}):\n{body}"
            );
            assert!(
                body.contains("::from(native)"),
                "native return must convert the extracted object via From<Binding> (is_async={is_async}):\n{body}"
            );
            assert!(
                body.contains("serde_json::from_str"),
                "the JSON/mapping fallback must remain (is_async={is_async}):\n{body}"
            );
        }
    }

    /// Regression: an owned (by-value) native-struct callback param — e.g. the URI-based
    /// `ExtractInput` envelope, which the core API now passes by value — must be marshalled to
    /// the binding's native Python object via `From<core::T>`, not handed to the host raw. A raw
    /// core value has no `IntoPyObject` and fails to compile (E0277). Borrowed native-struct
    /// params were already marshalled; owned ones regressed when the param lost its `&`.
    #[test]
    fn trait_callback_owned_native_struct_param_is_marshalled() {
        use crate::codegen::generators::trait_bridge::{TraitBridgeGenerator, TraitBridgeSpec};
        use crate::core::config::TraitBridgeConfig;
        use crate::core::ir::{MethodDef, ParamDef, ReceiverKind, TypeDef, TypeRef};
        use std::collections::{HashMap, HashSet};

        let trait_def = TypeDef {
            name: "SampleExtractor".to_owned(),
            rust_path: "sample_core::SampleExtractor".to_owned(),
            is_trait: true,
            is_opaque: true,
            ..TypeDef::default()
        };
        let bridge_cfg = TraitBridgeConfig {
            trait_name: "SampleExtractor".to_owned(),
            register_fn: Some("register_sample".to_owned()),
            registry_getter: Some("sample_core::registry::get".to_owned()),
            ..TraitBridgeConfig::default()
        };
        let spec = TraitBridgeSpec {
            trait_def: &trait_def,
            bridge_config: &bridge_cfg,
            core_import: "sample_core",
            wrapper_prefix: "Py",
            type_paths: HashMap::new(),
            lifetime_type_names: HashSet::new(),
            error_type: "SampleError".to_owned(),
            error_constructor: "SampleError::Message { message: {msg} }".to_owned(),
        };
        let generator = super::Pyo3BridgeGenerator {
            core_import: "sample_core".to_owned(),
            type_paths: HashMap::new(),
            error_type: "SampleError".to_owned(),
            struct_param_types: HashSet::from(["Input".to_owned()]),
            struct_return_types: HashSet::new(),
            forwardable_defaulted: HashSet::new(),
            options_dataclass_types: HashSet::new(),
            unit_enum_return_types: HashSet::new(),
        };

        let make_method = |is_async: bool| MethodDef {
            name: "handle".to_owned(),
            params: vec![ParamDef {
                name: "input".to_owned(),
                ty: TypeRef::Named("Input".to_owned()),
                is_ref: false,
                ..ParamDef::default()
            }],
            return_type: TypeRef::Unit,
            is_async,
            error_type: Some("SampleError".to_owned()),
            receiver: Some(ReceiverKind::Ref),
            ..MethodDef::default()
        };

        for is_async in [true, false] {
            let body = if is_async {
                generator.gen_async_method_body(&make_method(true), &spec)
            } else {
                generator.gen_sync_method_body(&make_method(false), &spec)
            };
            assert!(
                body.contains("Input::from("),
                "owned native-struct param must be marshalled via From<core::T> (is_async={is_async}):\n{body}"
            );
            assert!(
                !body.contains("(bound_method, input)") && !body.contains("(bound_method, input,"),
                "owned native-struct param must not be handed to the host raw (is_async={is_async}):\n{body}"
            );
        }
    }

    /// Regression: a sync (infallible) callback returning a unit-only enum (e.g.
    /// `ProcessingStage`) must accept the bare variant name (`"Early"`) that a host naturally
    /// returns from a plain Python string, in addition to the JSON-quoted form the generic
    /// mapping path required (`"\"Early\""`). Previously the bridge only tried
    /// `serde_json::from_str`, which rejects a bare/unquoted variant name as invalid JSON and
    /// silently substitutes the default via `unwrap_or_else` — turning a real host return value
    /// into a wrong-but-plausible default. The error message for this shape must also stop
    /// claiming the value "must be a mapping", since unit enums have no fields to map.
    #[test]
    fn sync_unit_enum_return_accepts_bare_variant_name() {
        use crate::codegen::generators::trait_bridge::{TraitBridgeGenerator, TraitBridgeSpec};
        use crate::core::config::TraitBridgeConfig;
        use crate::core::ir::{MethodDef, ReceiverKind, TypeDef, TypeRef};
        use std::collections::{HashMap, HashSet};

        let trait_def = TypeDef {
            name: "SamplePostProcessor".to_owned(),
            rust_path: "sample_core::SamplePostProcessor".to_owned(),
            is_trait: true,
            is_opaque: true,
            ..TypeDef::default()
        };
        let bridge_cfg = TraitBridgeConfig {
            trait_name: "SamplePostProcessor".to_owned(),
            register_fn: Some("register_sample".to_owned()),
            registry_getter: Some("sample_core::registry::get".to_owned()),
            ..TraitBridgeConfig::default()
        };
        let spec = TraitBridgeSpec {
            trait_def: &trait_def,
            bridge_config: &bridge_cfg,
            core_import: "sample_core",
            wrapper_prefix: "Py",
            type_paths: HashMap::new(),
            lifetime_type_names: HashSet::new(),
            error_type: "SampleError".to_owned(),
            error_constructor: "SampleError::Message { message: {msg} }".to_owned(),
        };
        let generator = super::Pyo3BridgeGenerator {
            core_import: "sample_core".to_owned(),
            type_paths: HashMap::new(),
            error_type: "SampleError".to_owned(),
            struct_param_types: HashSet::new(),
            struct_return_types: HashSet::new(),
            forwardable_defaulted: HashSet::new(),
            options_dataclass_types: HashSet::new(),
            unit_enum_return_types: HashSet::from(["ProcessingStage".to_owned()]),
        };

        let method = MethodDef {
            name: "processing_stage".to_owned(),
            params: vec![],
            return_type: TypeRef::Named("ProcessingStage".to_owned()),
            is_async: false,
            error_type: None,
            receiver: Some(ReceiverKind::Ref),
            ..MethodDef::default()
        };

        let body = generator.gen_sync_method_body(&method, &spec);
        assert!(
            body.contains("serde_json::from_value(serde_json::Value::String"),
            "unit-enum return must fall back to treating the string as a bare variant name:\n{body}"
        );
        assert!(
            !body.contains("must be a mapping"),
            "unit-enum deserialize error must not claim the value must be a mapping:\n{body}"
        );
        assert!(
            body.contains("variant names"),
            "unit-enum deserialize error should mention variant names:\n{body}"
        );
    }

    /// Regression: a struct return (as opposed to a unit-only enum) must keep the strict
    /// mapping-only deserialization and error wording — a bare string can't represent a
    /// struct's fields, so the fallback added for unit enums must not apply here.
    #[test]
    fn sync_struct_return_keeps_strict_mapping_error() {
        use crate::codegen::generators::trait_bridge::{TraitBridgeGenerator, TraitBridgeSpec};
        use crate::core::config::TraitBridgeConfig;
        use crate::core::ir::{MethodDef, ReceiverKind, TypeDef, TypeRef};
        use std::collections::{HashMap, HashSet};

        let trait_def = TypeDef {
            name: "SampleService".to_owned(),
            rust_path: "sample_core::SampleService".to_owned(),
            is_trait: true,
            is_opaque: true,
            ..TypeDef::default()
        };
        let bridge_cfg = TraitBridgeConfig {
            trait_name: "SampleService".to_owned(),
            register_fn: Some("register_sample".to_owned()),
            registry_getter: Some("sample_core::registry::get".to_owned()),
            ..TraitBridgeConfig::default()
        };
        let spec = TraitBridgeSpec {
            trait_def: &trait_def,
            bridge_config: &bridge_cfg,
            core_import: "sample_core",
            wrapper_prefix: "Py",
            type_paths: HashMap::new(),
            lifetime_type_names: HashSet::new(),
            error_type: "SampleError".to_owned(),
            error_constructor: "SampleError::Message { message: {msg} }".to_owned(),
        };
        let generator = super::Pyo3BridgeGenerator {
            core_import: "sample_core".to_owned(),
            type_paths: HashMap::new(),
            error_type: "SampleError".to_owned(),
            struct_param_types: HashSet::new(),
            struct_return_types: HashSet::new(),
            forwardable_defaulted: HashSet::new(),
            options_dataclass_types: HashSet::new(),
            unit_enum_return_types: HashSet::new(),
        };

        let method = MethodDef {
            name: "build".to_owned(),
            params: vec![],
            return_type: TypeRef::Named("Doc".to_owned()),
            is_async: false,
            error_type: Some("SampleError".to_owned()),
            receiver: Some(ReceiverKind::Ref),
            ..MethodDef::default()
        };

        let body = generator.gen_sync_method_body(&method, &spec);
        assert!(
            body.contains("must be a mapping"),
            "struct deserialize error must keep the mapping-fields wording:\n{body}"
        );
        assert!(
            !body.contains("serde_json::from_value(serde_json::Value::String"),
            "struct return must not gain the unit-enum bare-string fallback:\n{body}"
        );
    }

    /// Regression: `PostProcessor::process(&self, result: &mut ExtractedDocument, ..)` cannot be
    /// implemented from Python at all under the naive bridge — it cloned `result`, handed the
    /// clone to the host, and discarded whatever the host returned via `.map(|_| ())`, so the
    /// `&mut` parameter was unfulfillable no matter what the Python plugin did. The bridge must
    /// instead treat the callback's return value as the (optionally) updated document and write
    /// it back into `*result` after the call, so Python `PostProcessor` plugins can actually
    /// modify the extraction result.
    #[test]
    fn async_mut_param_writes_back_host_return_value() {
        use crate::codegen::generators::trait_bridge::{TraitBridgeGenerator, TraitBridgeSpec};
        use crate::core::config::TraitBridgeConfig;
        use crate::core::ir::{MethodDef, ParamDef, ReceiverKind, TypeDef, TypeRef};
        use std::collections::{HashMap, HashSet};

        let trait_def = TypeDef {
            name: "SamplePostProcessor".to_owned(),
            rust_path: "sample_core::SamplePostProcessor".to_owned(),
            is_trait: true,
            is_opaque: true,
            ..TypeDef::default()
        };
        let bridge_cfg = TraitBridgeConfig {
            trait_name: "SamplePostProcessor".to_owned(),
            register_fn: Some("register_sample".to_owned()),
            registry_getter: Some("sample_core::registry::get".to_owned()),
            ..TraitBridgeConfig::default()
        };
        let spec = TraitBridgeSpec {
            trait_def: &trait_def,
            bridge_config: &bridge_cfg,
            core_import: "sample_core",
            wrapper_prefix: "Py",
            type_paths: HashMap::from([("Doc".to_owned(), "sample_core::Doc".to_owned())]),
            lifetime_type_names: HashSet::new(),
            error_type: "SampleError".to_owned(),
            error_constructor: "SampleError::Message { message: {msg} }".to_owned(),
        };
        let generator = super::Pyo3BridgeGenerator {
            core_import: "sample_core".to_owned(),
            type_paths: HashMap::from([("Doc".to_owned(), "sample_core::Doc".to_owned())]),
            error_type: "SampleError".to_owned(),
            struct_param_types: HashSet::from(["Doc".to_owned()]),
            struct_return_types: HashSet::new(),
            forwardable_defaulted: HashSet::new(),
            options_dataclass_types: HashSet::new(),
            unit_enum_return_types: HashSet::new(),
        };

        let method = MethodDef {
            name: "process".to_owned(),
            params: vec![
                ParamDef {
                    name: "result".to_owned(),
                    ty: TypeRef::Named("Doc".to_owned()),
                    is_ref: true,
                    is_mut: true,
                    ..ParamDef::default()
                },
                ParamDef {
                    name: "config".to_owned(),
                    ty: TypeRef::String,
                    is_ref: true,
                    ..ParamDef::default()
                },
            ],
            return_type: TypeRef::Unit,
            is_async: true,
            error_type: Some("SampleError".to_owned()),
            receiver: Some(ReceiverKind::Ref),
            ..MethodDef::default()
        };

        let body = generator.gen_async_method_body(&method, &spec);
        assert!(
            body.contains("*result = "),
            "the host's return value must be written back into the &mut param:\n{body}"
        );
        assert!(
            !body.contains(".map(|_| ())"),
            "the old discard-everything bridge shape must be gone for this method:\n{body}"
        );
        assert!(
            body.contains("py_result.is_none()"),
            "the host must be allowed to return None to mean \"unchanged\":\n{body}"
        );
    }

    #[test]
    fn visitor_bridge_uses_configured_context_and_result_metadata() {
        let (api, trait_type, bridge) = crate::codegen::visitor_context::test_support::neutral_visitor_fixture();
        let output = super::gen_trait_bridge(
            &trait_type,
            &bridge,
            "sample_core",
            "SampleError",
            "SampleError::Message { message: {msg} }",
            &api,
            &[],
        )
        .expect("visitor bridge should generate");

        crate::codegen::visitor_context::test_support::assert_neutral_visitor_output(&output.code);
        assert!(output.code.contains("\"display_name\""));
    }
}