alef 0.34.11

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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
//! R (extendr) specific trait bridge code generation.
//!
//! Generates Rust wrapper structs that implement Rust traits by delegating
//! to R objects (named lists of functions) via extendr.

pub use crate::codegen::generators::trait_bridge::find_bridge_param;
use crate::codegen::generators::trait_bridge::{
    BridgeOutput, TraitBridgeGenerator, TraitBridgeSpec, bridge_param_type as param_type, format_type_ref,
    gen_bridge_all, visitor_param_type,
};
use crate::core::config::TraitBridgeConfig;
use crate::core::ir::{ApiSurface, MethodDef, TypeDef, TypeRef};
use std::collections::HashMap;

/// Extendr-specific trait bridge generator.
/// Implements code generation for bridging R objects to Rust traits.
pub struct ExtendrBridgeGenerator {
    /// Core crate import path (e.g., `"sample_core"`).
    pub core_import: String,
    /// Map of type name → fully-qualified Rust path for type references.
    pub type_paths: HashMap<String, String>,
    pub error_type: String,
    /// Callback-param type names that get NATIVE-object marshalling — known serde structs
    /// (per the shared [`crate::codegen::generators::trait_bridge::is_native_marshalled_struct`]
    /// rule) that are also registered as extendr classes (so the `#[extendr]`-generated
    /// `From<Binding> for Robj` exists). For such a param the bridge builds the binding's native
    /// R object (an `ExternalPtr` class env, via the same `From<core::T>` conversion used for
    /// return values) and hands THAT to the host closure, instead of serializing the param to a
    /// JSON string. Enums, opaque/handle types, extendr-incompatible structs, and excluded/unknown
    /// `Named` params are absent and keep their prior JSON-string representation.
    pub struct_param_types: std::collections::HashSet<String>,
    /// Callback-RETURN type names that get NATIVE-object marshalling — extendr-representable serde
    /// structs with a generated `From<Binding> for core`. For such a return the bridge first tries
    /// to unwrap the host's native `ExternalPtr` and convert via `From<Binding>` (mirroring the
    /// options decoder), falling back to the `as_str()` + serde JSON-string path.
    pub struct_return_types: std::collections::HashSet<String>,
    /// Rust-defaulted trait methods the bridge forwards to the host when the R
    /// object provides them. Presence is cached as `has_<method>` bool fields at
    /// construction (on the R main thread) because R objects cannot be probed
    /// from worker threads. Methods absent here keep the trait's Rust default
    /// unconditionally.
    pub forwardable_defaulted: std::collections::HashSet<String>,
}

impl ExtendrBridgeGenerator {
    /// True when a `Named(name)` callback param should be handed to the host as the binding's
    /// native R object rather than a JSON string — i.e. it is a known serde struct that is also
    /// registered as an extendr class. The native object is the `ExternalPtr` class env,
    /// constructed from the core value via the same `From<core::T>` conversion the binding uses
    /// for function return values.
    fn is_native_struct_param(&self, name: &str) -> bool {
        self.struct_param_types.contains(name)
    }

    /// Binding struct name to unwrap for a native-object return, when the return is a bare `Named`
    /// struct on the (representability- and conversion-gated) native-marshalled return allowlist.
    /// The bridge tries `ExternalPtr::<Binding>::try_from(&val)` and converts via `From<Binding>`;
    /// `None` keeps the JSON-string path.
    fn native_struct_return<'a>(&self, ty: &'a TypeRef) -> Option<&'a str> {
        match ty {
            TypeRef::Named(n) if self.struct_return_types.contains(n) => Some(n.as_str()),
            _ => None,
        }
    }
}

impl TraitBridgeGenerator for ExtendrBridgeGenerator {
    fn foreign_object_type(&self) -> &str {
        "extendr_api::Robj"
    }

    fn gen_method_presence_check(&self, method: &MethodDef, _spec: &TraitBridgeSpec) -> Option<String> {
        self.forwardable_defaulted
            .contains(&method.name)
            .then(|| format!("self.has_{}", method.name))
    }

    fn gen_lifecycle_presence_check(&self, method: &MethodDef, _spec: &TraitBridgeSpec) -> Option<String> {
        Some(format!("self.has_{}", method.name))
    }

    fn extra_bridge_fields(&self, spec: &TraitBridgeSpec) -> Vec<(String, String)> {
        let mut fields: Vec<(String, String)> = spec
            .trait_def
            .methods
            .iter()
            .filter(|m| self.forwardable_defaulted.contains(&m.name))
            .map(|m| (format!("has_{}", m.name), "bool".to_string()))
            .collect();
        if spec.bridge_config.super_trait.is_some() {
            fields.push(("has_initialize".to_string(), "bool".to_string()));
            fields.push(("has_shutdown".to_string(), "bool".to_string()));
        }
        fields
    }

    fn bridge_imports(&self) -> Vec<String> {
        vec!["extendr_api::prelude::*".to_string(), "std::sync::Arc".to_string()]
    }

    fn gen_sync_method_body(&self, method: &MethodDef, spec: &TraitBridgeSpec) -> String {
        let name = &method.name;
        let has_error = method.error_type.is_some();

        let (empty_args, args_pairs) = if method.params.is_empty() {
            (true, String::new())
        } else {
            let args: Vec<String> = method
                .params
                .iter()
                .map(|p| match &p.ty {
                    // The `#[extendr]`-generated `From<Binding> for Robj` wraps it as an
                    TypeRef::Named(n) if self.is_native_struct_param(n) => {
                        let owned = if p.is_ref {
                            format!("(*{}).clone()", p.name)
                        } else {
                            format!("{}.clone()", p.name)
                        };
                        format!("extendr_api::Robj::from({n}::from({owned}))")
                    }
                    _ => build_extendr_arg(p, spec.bridge_config.context_type.as_deref()),
                })
                .collect();
            let pairs: Vec<String> = method
                .params
                .iter()
                .zip(args.iter())
                .map(|(p, expr)| format!("(\"{}\", {})", p.name.trim_start_matches('_'), expr))
                .collect();
            (false, pairs.join(", "))
        };

        let is_primitive_return = matches!(&method.return_type, TypeRef::Primitive(_));
        let template_name = match &method.return_type {
            TypeRef::Unit => "sync_method_unit_return.jinja",
            TypeRef::String | TypeRef::Char => "sync_method_string_return.jinja",
            _ => "sync_method_complex_return.jinja",
        };

        let ret_ty = match &method.return_type {
            TypeRef::Named(n) => self
                .type_paths
                .get(n.as_str())
                .map(|p| p.replace('-', "_"))
                .unwrap_or_else(|| n.clone()),
            other => format_type_ref(other, &self.type_paths),
        };

        crate::backends::extendr::template_env::render(
            template_name,
            minijinja::context! {
                wrapper => spec.wrapper_name(),
                method_name => name,
                has_error => has_error,
                has_error_check => if has_error { "true" } else { "false" },
                empty_args => empty_args,
                args_pairs => args_pairs,
                return_type => ret_ty,
                native_return_binding => self.native_struct_return(&method.return_type),
                is_primitive_return => is_primitive_return,
                missing_method_error => method_error_expr(
                    &spec.error_constructor,
                    name,
                    "self.cached_name",
                    "missing method",
                ),
                failed_method_error => method_error_expr(
                    &spec.error_constructor,
                    name,
                    "self.cached_name",
                    "failed",
                ),
                invalid_type_error => method_error_expr(
                    &spec.error_constructor,
                    name,
                    "self.cached_name",
                    "returned invalid type",
                ),
                deserialization_error => method_error_expr(
                    &spec.error_constructor,
                    name,
                    "self.cached_name",
                    "deserialization failed",
                ),
                parse_error => make_error_expr(
                    &spec.error_constructor,
                    r#"format!("Failed to parse return value: {}", e)"#,
                ),
            },
        )
    }

    fn gen_async_method_body(&self, method: &MethodDef, spec: &TraitBridgeSpec) -> String {
        let name = &method.name;

        let mut params_to_clone = Vec::new();
        for p in &method.params {
            let template_name = match (&p.ty, p.is_ref) {
                (TypeRef::Bytes, true) => "async_param_clone_bytes_ref.jinja",
                (TypeRef::Path, true) => "async_param_clone_path_ref.jinja",
                (TypeRef::Named(n), true) if self.is_native_struct_param(n) => {
                    "async_param_clone_native_struct_ref.jinja"
                }
                (TypeRef::Named(_), true) => "async_param_clone_named_ref.jinja",
                (_, true) => "async_param_clone_ref.jinja",
                _ => "async_param_clone_value.jinja",
            };
            let clone_stmt = crate::backends::extendr::template_env::render(
                template_name,
                minijinja::context! {
                    name => &p.name,
                },
            );
            params_to_clone.push(clone_stmt);
        }

        let (empty_args, args_pairs) = if method.params.is_empty() {
            (true, String::new())
        } else {
            let args: Vec<String> = method
                .params
                .iter()
                .map(|p| match (&p.ty, p.is_ref) {
                    (TypeRef::Bytes, true) => format!("extendr_api::Robj::from(&{0}[..])", p.name),
                    (TypeRef::Path, true) => format!("extendr_api::Robj::from({0}_str.as_str())", p.name),
                    // conversion used for return values. The `#[extendr]`-generated
                    (TypeRef::Named(n), true) if self.is_native_struct_param(n) => {
                        format!("extendr_api::Robj::from({n}::from({0}_owned.clone()))", p.name)
                    }
                    (TypeRef::Named(_), true) => format!("extendr_api::Robj::from({0}_json.as_str())", p.name),
                    _ => format!("extendr_api::Robj::from({})", p.name),
                })
                .collect();
            let pairs: Vec<String> = method
                .params
                .iter()
                .zip(args.iter())
                .map(|(p, expr)| format!("(\"{}\", {})", p.name.trim_start_matches('_'), expr))
                .collect();
            (false, pairs.join(", "))
        };

        let template_name = match &method.return_type {
            TypeRef::Unit => "async_method_unit_return.jinja",
            TypeRef::String | TypeRef::Char => "async_method_string_return.jinja",
            _ => "async_method_complex_return.jinja",
        };

        let ret_ty = match &method.return_type {
            TypeRef::Named(n) => self
                .type_paths
                .get(n.as_str())
                .map(|p| p.replace('-', "_"))
                .unwrap_or_else(|| n.clone()),
            other => format_type_ref(other, &self.type_paths),
        };

        crate::backends::extendr::template_env::render(
            template_name,
            minijinja::context! {
                method_name => name,
                params_to_clone => params_to_clone,
                empty_args => empty_args,
                args_pairs => args_pairs,
                return_type => ret_ty,
                native_return_binding => self.native_struct_return(&method.return_type),
                missing_method_error => method_error_expr(
                    &spec.error_constructor,
                    name,
                    "cached_name_inner",
                    "missing method",
                ),
                failed_method_error => method_error_expr(
                    &spec.error_constructor,
                    name,
                    "cached_name_inner",
                    "failed",
                ),
                invalid_type_error => method_error_expr(
                    &spec.error_constructor,
                    name,
                    "cached_name_inner",
                    "returned invalid type",
                ),
                deserialization_error => method_error_expr(
                    &spec.error_constructor,
                    name,
                    "cached_name_inner",
                    "deserialization failed",
                ),
                spawn_blocking_error => make_error_expr(
                    &spec.error_constructor,
                    r#"format!("spawn_blocking failed: {}", e)"#,
                ),
            },
        )
    }

    fn gen_constructor(&self, spec: &TraitBridgeSpec) -> String {
        let wrapper = spec.wrapper_name();
        let required_methods: Vec<String> = spec.required_methods().iter().map(|m| m.name.clone()).collect();
        let mut optional_methods: Vec<String> = spec
            .trait_def
            .methods
            .iter()
            .filter(|m| self.forwardable_defaulted.contains(&m.name))
            .map(|m| m.name.clone())
            .collect();
        if spec.bridge_config.super_trait.is_some() {
            optional_methods.push("initialize".to_string());
            optional_methods.push("shutdown".to_string());
        }

        crate::backends::extendr::template_env::render(
            "bridge_constructor.jinja",
            minijinja::context! {
                wrapper => wrapper,
                required_methods => required_methods,
                optional_methods => optional_methods,
            },
        )
    }

    fn gen_unregistration_fn(&self, spec: &TraitBridgeSpec) -> String {
        let Some(unregister_fn) = spec.bridge_config.unregister_fn.as_deref() else {
            return String::new();
        };
        let host_path = crate::codegen::generators::trait_bridge::host_function_path(spec, unregister_fn);
        crate::backends::extendr::template_env::render(
            "unregistration_fn.jinja",
            minijinja::context! {
                unregister_fn => unregister_fn,
                host_path => host_path,
            },
        )
    }

    fn gen_clear_fn(&self, spec: &TraitBridgeSpec) -> String {
        let Some(clear_fn) = spec.bridge_config.clear_fn.as_deref() else {
            return String::new();
        };
        let host_path = crate::codegen::generators::trait_bridge::host_function_path(spec, clear_fn);
        crate::backends::extendr::template_env::render(
            "clear_fn.jinja",
            minijinja::context! {
                clear_fn => clear_fn,
                host_path => host_path,
            },
        )
    }

    fn gen_registration_fn(&self, spec: &TraitBridgeSpec) -> String {
        let Some(register_fn) = spec.bridge_config.register_fn.as_deref() else {
            return String::new();
        };
        let Some(registry_getter) = spec.bridge_config.registry_getter.as_deref() else {
            return String::new();
        };
        let wrapper = spec.wrapper_name();
        let trait_path = spec.trait_path();

        let req_methods = spec.required_methods();
        let has_methods = !req_methods.is_empty();
        let required_methods_list = req_methods
            .iter()
            .map(|m| format!("\"{}\"", m.name))
            .collect::<Vec<_>>()
            .join(", ");

        crate::backends::extendr::template_env::render(
            "registration_fn.jinja",
            minijinja::context! {
                register_fn => register_fn,
                wrapper => wrapper,
                trait_path => trait_path,
                registry_getter => registry_getter,
                required_methods => has_methods,
                required_methods_list => required_methods_list,
                error_map => ".map_err(|e| extendr_api::Error::Other(e))?",
            },
        )
    }
}

fn make_error_expr(error_constructor: &str, message_expr: &str) -> String {
    error_constructor.replace("{msg}", message_expr)
}

fn method_error_expr(error_constructor: &str, method_name: &str, plugin_name_expr: &str, reason: &str) -> String {
    let message_expr = if reason == "missing method" {
        format!(r#"format!("Plugin '{{}}' missing method '{method_name}'", {plugin_name_expr})"#)
    } else {
        format!(r#"format!("Plugin '{{}}' method '{method_name}' {reason}", {plugin_name_expr})"#)
    };
    make_error_expr(error_constructor, &message_expr)
}

/// Compute the set of trait-callback struct params that extendr should marshal to the host as
/// the binding's native R object (an `ExternalPtr` class env) rather than a JSON string.
///
/// Starts from the shared, backend-agnostic allowlist
/// ([`crate::codegen::generators::trait_bridge::native_marshalled_struct_params`] — known serde
/// structs) and removes structs that extendr cannot register as a class because their own fields
/// contain types extendr cannot convert (`Vec<Named>` / `Option<Vec<_>>` / nested `Vec`). Those
/// have no `#[extendr]`-generated `From<Binding> for Robj`, so the native conversion would not
/// compile; they keep their prior JSON-string representation.
pub(crate) fn native_marshalled_extendr_struct_params(
    trait_type: &TypeDef,
    api: &ApiSurface,
) -> std::collections::HashSet<String> {
    let mut out = crate::codegen::generators::trait_bridge::native_marshalled_struct_params(trait_type, api);
    out.retain(|name| {
        api.types
            .iter()
            .find(|t| &t.name == name)
            .is_some_and(|t| !t.fields.iter().any(|f| field_is_extendr_incompatible(&f.ty)))
    });
    out
}

/// Return-side counterpart to [`native_marshalled_extendr_struct_params`]: struct return types
/// extendr can unwrap from the host's native `ExternalPtr` and convert to the core type (mirroring
/// the options decoder). Requires the struct to be extendr-representable as a class AND to have a
/// generated `From<Binding> for core` (`convertible_types`); otherwise the native unwrap would not
/// compile and the return keeps the JSON-string path.
pub(crate) fn native_marshalled_extendr_struct_returns(
    trait_type: &TypeDef,
    api: &ApiSurface,
) -> std::collections::HashSet<String> {
    let binding_to_core = crate::codegen::conversions::convertible_types(api);
    let mut out = crate::codegen::generators::trait_bridge::native_marshalled_struct_returns(trait_type, api);
    out.retain(|name| {
        binding_to_core.contains(name.as_str())
            && api
                .types
                .iter()
                .find(|t| &t.name == name)
                .is_some_and(|t| !t.fields.iter().any(|f| field_is_extendr_incompatible(&f.ty)))
    });
    out
}

/// True if a field type prevents extendr from registering the containing struct as a class —
/// `Vec<Named>`, `Option<Vec<_>>`, or nested `Vec<Vec<_>>`. Mirrors the
/// `is_extendr_native_incompatible` check in `gen_bindings` (kept in sync; extendr cannot
/// auto-convert these from/to `Robj`).
fn field_is_extendr_incompatible(ty: &TypeRef) -> bool {
    match ty {
        TypeRef::Vec(inner) => matches!(inner.as_ref(), TypeRef::Named(_) | TypeRef::Vec(_)),
        TypeRef::Optional(inner) => {
            matches!(inner.as_ref(), TypeRef::Vec(inner2) if matches!(inner2.as_ref(), TypeRef::Named(_) | TypeRef::Vec(_)))
        }
        _ => false,
    }
}

/// Generate all trait bridge code for a given trait type and bridge config.
pub fn gen_trait_bridge(
    trait_type: &TypeDef,
    bridge_cfg: &TraitBridgeConfig,
    core_import: &str,
    error_type: &str,
    error_constructor: &str,
    api: &crate::core::ir::ApiSurface,
) -> anyhow::Result<BridgeOutput> {
    let struct_name = crate::codegen::generators::trait_bridge::bridge_wrapper_name("R", bridge_cfg);
    let trait_path = trait_type.rust_path.replace('-', "_");

    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 mut out = String::with_capacity(8192);
        gen_visitor_bridge(
            &mut out,
            trait_type,
            bridge_cfg,
            &struct_name,
            &trait_path,
            core_import,
            &type_paths,
            api,
        )?;
        Ok(BridgeOutput {
            imports: vec![],
            code: out,
        })
    } else {
        // registered as extendr classes and have no `#[extendr]`-generated `From<Binding> for Robj`,
        let struct_param_types = native_marshalled_extendr_struct_params(trait_type, api);
        let struct_return_types = native_marshalled_extendr_struct_returns(trait_type, api);
        let forwardable_defaulted =
            crate::codegen::generators::trait_bridge::forwardable_defaulted_method_names(trait_type, api);
        let generator = ExtendrBridgeGenerator {
            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,
        };
        let lifetime_type_names: std::collections::HashSet<String> = api
            .types
            .iter()
            .filter(|typ| typ.has_lifetime_params)
            .map(|typ| typ.name.clone())
            .collect();
        let spec = TraitBridgeSpec {
            trait_def: trait_type,
            bridge_config: bridge_cfg,
            core_import,
            wrapper_prefix: "R",
            type_paths,
            lifetime_type_names,
            error_type: error_type.to_string(),
            error_constructor: error_constructor.to_string(),
        };
        let mut output = gen_bridge_all(&spec, &generator);
        // SAFETY: `extendr_api::Robj` wraps a `*mut SEXPREC` and is therefore neither `Send`
        let send_sync_impl = format!(
            "\n#[allow(clippy::non_send_fields_in_send_ty)]\n\
             // SAFETY: R is single-threaded; the user must invoke plugins from the R main thread.\n\
             unsafe impl Send for {struct_name} {{}}\n\
             // SAFETY: see Send impl.\n\
             unsafe impl Sync for {struct_name} {{}}\n"
        );
        output.code.push_str(&send_sync_impl);
        Ok(output)
    }
}

/// Generate the shared `SendRobj` wrapper module that allows `Robj` to cross thread boundaries
/// in `spawn_blocking` closures. Emitted once per generated file when any trait bridge is
/// produced, before any bridge struct. The wrapper is required because `extendr_api::Robj`
/// contains a raw pointer and is therefore `!Send`/`!Sync`.
pub fn gen_send_robj_helper() -> &'static str {
    "/// Newtype wrapper around `extendr_api::Robj` that asserts `Send + Sync`.\n\
     ///\n\
     /// # Safety\n\
     ///\n\
     /// R is single-threaded; user-supplied R callbacks must only be invoked from the R main\n\
     /// thread. This wrapper exists to satisfy the `Send`/`Sync` bounds required by the Rust\n\
     /// plugin trait system and by `tokio::spawn_blocking`. Misuse from a background thread\n\
     /// triggers R-runtime undefined behaviour.\n\
     #[repr(transparent)]\n\
     #[derive(Clone)]\n\
     pub(crate) struct SendRobj(pub extendr_api::Robj);\n\
     // SAFETY: see SendRobj docs.\n\
     unsafe impl Send for SendRobj {}\n\
     // SAFETY: see SendRobj docs.\n\
     unsafe impl Sync for SendRobj {}\n\
     impl SendRobj {\n\
         /// Consume the wrapper and yield the inner `Robj`. Used inside `spawn_blocking`\n\
         /// closures so that the closure captures the whole `SendRobj` (which is `Send`)\n\
         /// rather than the inner `Robj` field (which is `!Send`) under 2021+ disjoint\n\
         /// capture rules.\n\
         #[inline]\n\
         pub(crate) fn into_inner(self) -> extendr_api::Robj { self.0 }\n\
     }\n"
}

/// Generate a visitor-style bridge wrapping an `extendr_api::Robj` (a named list of functions).
///
/// Every trait method checks if the list has a function with the snake_case method name,
/// calls it via extendr's `.call()`, and maps the return value to the configured result enum.
#[allow(clippy::too_many_arguments)]
fn gen_visitor_bridge(
    out: &mut String,
    trait_type: &TypeDef,
    bridge_cfg: &TraitBridgeConfig,
    struct_name: &str,
    trait_path: &str,
    core_crate: &str,
    type_paths: &std::collections::HashMap<String, String>,
    api: &ApiSurface,
) -> anyhow::Result<()> {
    let result_metadata = crate::codegen::visitor_result::required_visitor_result_metadata(api, bridge_cfg)?;
    let context_helper = crate::codegen::visitor_context::visitor_context_helper(
        api,
        bridge_cfg,
        core_crate,
        crate::codegen::visitor_context::VisitorContextBackend::Extendr,
    )?;
    let context_type = bridge_cfg.context_type.as_deref();
    let mut method_impls = String::with_capacity(4096);
    for method in crate::codegen::generators::trait_bridge::visitor_callback_methods(trait_type, bridge_cfg) {
        gen_visitor_method_extendr(&mut method_impls, method, context_type, type_paths, &result_metadata);
    }

    out.push_str(&crate::backends::extendr::template_env::render(
        "visitor_bridge.jinja",
        minijinja::context! {
            core_crate => core_crate,
            context_type_path => context_helper.type_path,
            context_field_lines => context_helper.field_lines,
            struct_name => struct_name,
            trait_path => trait_path,
            method_impls => method_impls,
        },
    ));
    Ok(())
}

/// Generate a single visitor method that checks if the R list has an element with this name
/// and calls it as a function.
fn gen_visitor_method_extendr(
    out: &mut String,
    method: &MethodDef,
    context_type: Option<&str>,
    type_paths: &std::collections::HashMap<String, String>,
    result_metadata: &crate::codegen::visitor_result::VisitorResultMetadata,
) {
    let name = &method.name;

    let mut sig_parts = vec!["&mut self".to_string()];
    for p in &method.params {
        let ty_str = visitor_param_type(&p.ty, p.is_ref, p.optional, type_paths);
        sig_parts.push(format!("{}: {}", p.name, ty_str));
    }
    let signature = sig_parts.join(", ");

    let return_type = match &method.return_type {
        TypeRef::Named(n) => type_paths
            .get(n.as_str())
            .map(|p| p.replace('-', "_"))
            .unwrap_or_else(|| n.clone()),
        other => param_type(other, "", false, type_paths),
    };

    let empty_args = method.params.is_empty();
    let args: Vec<String> = method
        .params
        .iter()
        .map(|p| build_extendr_arg(p, context_type))
        .collect();
    let args_pairs: Vec<String> = method
        .params
        .iter()
        .zip(args.iter())
        .map(|(p, expr)| format!("(\"{}\", {})", p.name.trim_start_matches('_'), expr))
        .collect();
    let args_pairs = args_pairs.join(", ");

    out.push_str(&crate::backends::extendr::template_env::render(
        "visitor_method.jinja",
        minijinja::context! {
            method_name => name,
            signature => signature,
            return_type => return_type,
            default_result_expr => crate::codegen::visitor_result::default_result_expr(&return_type, result_metadata),
            unknown_string_result_expr => crate::codegen::visitor_result::unknown_string_result_expr(
                &return_type,
                result_metadata,
                "s.to_string()",
            ),
            unit_result_variants => crate::codegen::visitor_result::variant_contexts(&result_metadata.unit_variants),
            payload_result_variants => crate::codegen::visitor_result::variant_contexts(
                &result_metadata.string_payload_variants,
            ),
            empty_args => empty_args,
            args_pairs => args_pairs,
        },
    ));
}

/// Build a single extendr `Pairlist` arg expression for a visitor method parameter.
fn build_extendr_arg(p: &crate::core::ir::ParamDef, context_type: Option<&str>) -> String {
    use crate::core::ir::TypeRef;

    if let TypeRef::Named(n) = &p.ty {
        if Some(n.as_str()) == context_type {
            let ref_prefix = if p.is_ref { "" } else { "&" };
            return format!("extendr_api::Robj::from(nodecontext_to_robj({}{}))", ref_prefix, p.name);
        }
    }

    if p.optional && matches!(&p.ty, TypeRef::String) && p.is_ref {
        return format!(
            "match {name} {{ Some(s) => extendr_api::Robj::from(s), None => extendr_api::Robj::from(extendr_api::NULL) }}",
            name = p.name
        );
    }

    if matches!(&p.ty, TypeRef::Bytes) {
        if p.is_ref {
            return format!("extendr_api::Robj::from(&{}[..])", p.name);
        }
        return format!("extendr_api::Robj::from(&{}[..])", p.name);
    }

    if matches!(&p.ty, TypeRef::String) && p.is_ref {
        return format!("extendr_api::Robj::from({})", p.name);
    }

    if matches!(&p.ty, TypeRef::String) {
        return format!("extendr_api::Robj::from({}.as_str())", p.name);
    }

    if let TypeRef::Named(_) = &p.ty {
        let serde_target = if p.is_ref {
            p.name.clone()
        } else {
            format!("&{}", p.name)
        };
        return format!(
            "extendr_api::Robj::from(serde_json::to_string({}).unwrap_or_default().as_str())",
            serde_target
        );
    }

    if matches!(&p.ty, TypeRef::Primitive(crate::core::ir::PrimitiveType::Bool)) {
        return format!("extendr_api::Robj::from({})", p.name);
    }

    if let TypeRef::Primitive(prim) = &p.ty {
        use crate::core::ir::PrimitiveType;
        match prim {
            PrimitiveType::U8
            | PrimitiveType::U16
            | PrimitiveType::U32
            | PrimitiveType::I8
            | PrimitiveType::I16
            | PrimitiveType::I32 => {
                return format!("extendr_api::Robj::from({} as i32)", p.name);
            }
            PrimitiveType::U64 | PrimitiveType::I64 | PrimitiveType::Usize | PrimitiveType::Isize => {
                return format!("extendr_api::Robj::from({} as f64)", p.name);
            }
            PrimitiveType::F32 | PrimitiveType::F64 => {
                return format!("extendr_api::Robj::from({} as f64)", p.name);
            }
            PrimitiveType::Bool => {
                return format!("extendr_api::Robj::from({})", p.name);
            }
        }
    }

    format!("extendr_api::Robj::from({})", p.name)
}

/// Generate an extendr free function that has one parameter replaced by `Option<extendr_api::Robj>`
/// (a trait bridge). The bridge is constructed before calling the core function.
#[allow(clippy::too_many_arguments)]
pub fn gen_bridge_function(
    api: &ApiSurface,
    func: &crate::core::ir::FunctionDef,
    bridge_param_idx: usize,
    bridge_cfg: &TraitBridgeConfig,
    mapper: &dyn crate::codegen::type_mapper::TypeMapper,
    opaque_types: &ahash::AHashSet<String>,
    core_import: &str,
) -> String {
    use crate::core::ir::TypeRef;

    let struct_name = crate::codegen::generators::trait_bridge::bridge_wrapper_name("R", bridge_cfg);
    let handle_path = crate::codegen::generators::trait_bridge::bridge_handle_path(api, bridge_cfg, core_import);
    let param_name = &func.params[bridge_param_idx].name;
    let bridge_param = &func.params[bridge_param_idx];
    let is_optional = bridge_param.optional || matches!(&bridge_param.ty, TypeRef::Optional(_));

    let mut sig_parts = Vec::new();
    for (idx, p) in func.params.iter().enumerate() {
        if idx == bridge_param_idx {
            sig_parts.push(format!("{}: Option<extendr_api::Robj>", p.name));
        } else {
            let promoted = idx > bridge_param_idx || func.params[..idx].iter().any(|pp| pp.optional);
            let ty = if p.optional || promoted {
                format!("Option<{}>", mapper.map_type(&p.ty))
            } else {
                mapper.map_type(&p.ty)
            };
            sig_parts.push(format!("{}: {}", p.name, ty));
        }
    }

    let params_str = sig_parts.join(", ");
    let return_type = mapper.map_type(&func.return_type);
    let has_error = func.error_type.is_some();
    let ret = mapper.wrap_return(&return_type, has_error);

    let err_conv = ".map_err(|e| extendr_api::Error::Other(e.to_string()))";

    let bridge_wrap = if is_optional {
        format!(
            "let {param_name}: Option<{handle_path}> = match {param_name} {{\n        \
             Some(v) if !v.is_null() => {{\n            \
             let bridge = {struct_name}::new(v);\n            \
             Some(std::sync::Arc::new(std::sync::Mutex::new(bridge)) as {handle_path})\n        \
             }},\n        \
             _ => None,\n    \
             }};"
        )
    } else {
        format!(
            "let {param_name}: Option<{handle_path}> = match {param_name} {{\n        \
             Some(v) if !v.is_null() => {{\n            \
             let bridge = {struct_name}::new(v);\n            \
             Some(std::sync::Arc::new(std::sync::Mutex::new(bridge)) as {handle_path})\n        \
             }},\n        \
             _ => None,\n    \
             }};"
        )
    };

    let serde_bindings: String = func
        .params
        .iter()
        .enumerate()
        .filter(|(idx, p)| {
            if *idx == bridge_param_idx {
                return false;
            }
            let named = match &p.ty {
                TypeRef::Named(n) => Some(n.as_str()),
                TypeRef::Optional(inner) => {
                    if let TypeRef::Named(n) = inner.as_ref() {
                        Some(n.as_str())
                    } else {
                        None
                    }
                }
                _ => None,
            };
            named.is_some_and(|n| !opaque_types.contains(n))
        })
        .map(|(_, p)| {
            let name = &p.name;
            let core_path = format!(
                "{core_import}::{}",
                match &p.ty {
                    TypeRef::Named(n) => n.clone(),
                    TypeRef::Optional(inner) => {
                        if let TypeRef::Named(n) = inner.as_ref() {
                            n.clone()
                        } else {
                            String::new()
                        }
                    }
                    _ => String::new(),
                }
            );
            let template_name = if p.optional || matches!(&p.ty, TypeRef::Optional(_)) {
                "serde_named_optional_binding.jinja"
            } else {
                "serde_named_required_binding.jinja"
            };
            crate::backends::extendr::template_env::render(
                template_name,
                minijinja::context! {
                    name => name,
                    core_path => core_path,
                    err_conv => err_conv,
                },
            )
        })
        .collect();

    let call_args: Vec<String> = func
        .params
        .iter()
        .enumerate()
        .map(|(idx, p)| {
            if idx == bridge_param_idx {
                return p.name.clone();
            }
            match &p.ty {
                TypeRef::Named(n) if opaque_types.contains(n.as_str()) => {
                    if p.optional {
                        format!("{}.as_ref().map(|v| &v.inner)", p.name)
                    } else {
                        format!("&{}.inner", p.name)
                    }
                }
                TypeRef::Named(_) => format!("{}_core", p.name),
                TypeRef::Optional(inner) => {
                    if let TypeRef::Named(n) = inner.as_ref() {
                        if opaque_types.contains(n.as_str()) {
                            format!("{}.as_ref().map(|v| &v.inner)", p.name)
                        } else {
                            format!("{}_core", p.name)
                        }
                    } else {
                        p.name.clone()
                    }
                }
                TypeRef::String | TypeRef::Char => {
                    if p.is_ref {
                        format!("&{}", p.name)
                    } else {
                        p.name.clone()
                    }
                }
                _ => p.name.clone(),
            }
        })
        .collect();
    let call_args_str = call_args.join(", ");

    let core_fn_path = {
        let path = func.rust_path.replace('-', "_");
        if path.starts_with(core_import) {
            path
        } else {
            format!("{core_import}::{}", func.name)
        }
    };
    let core_call = format!("{core_fn_path}({call_args_str})");

    let return_wrap = match &func.return_type {
        TypeRef::Named(name) if opaque_types.contains(name.as_str()) => {
            format!("{name} {{ inner: std::sync::Arc::new(val) }}")
        }
        TypeRef::Named(_) | TypeRef::String | TypeRef::Bytes => "val.into()".to_string(),
        _ => "val".to_string(),
    };

    let body = if func.error_type.is_some() {
        if return_wrap == "val" {
            format!("{bridge_wrap}\n    {serde_bindings}{core_call}{err_conv}")
        } else {
            format!("{bridge_wrap}\n    {serde_bindings}{core_call}.map(|val| {return_wrap}){err_conv}")
        }
    } else {
        format!("{bridge_wrap}\n    {serde_bindings}{core_call}")
    };

    let func_name = &func.name;
    crate::backends::extendr::template_env::render(
        "bridge_function.jinja",
        minijinja::context! {
            has_error => func.error_type.is_some(),
            func_name => func_name,
            params_str => params_str,
            ret => ret,
            body => body,
        },
    )
}

#[cfg(test)]
mod tests;