Skip to main content

miniextendr_macros/miniextendr_impl_trait/
vtable.rs

1//! Vtable static generation, C wrapper generation, and method attribute parsing for trait impls.
2//!
3//! This module contains the core codegen for `#[miniextendr]` on `impl Trait for Type` blocks.
4//! It produces the vtable static constant, C-callable wrapper functions for each method and
5//! associated constant, and delegates to [`super::r_wrappers`] for R wrapper code generation.
6
7use proc_macro2::TokenStream;
8use quote::format_ident;
9use syn::ItemImpl;
10
11use super::r_wrappers::{TraitWrapperOpts, binds_trait_namespace, generate_trait_r_wrapper};
12use super::{TraitAbiMetadata, TraitConst, TraitMethod, type_to_symbol_name};
13use crate::miniextendr_impl::{ClassSystem, ImplAttrs};
14
15/// Generate the vtable static, C wrappers, R wrappers, and call defs for a trait implementation.
16///
17/// This is the main entry point for trait impl codegen. For a given
18/// `impl Trait for Type { ... }` block, it produces:
19///
20/// - The cleaned original impl block (with `#[miniextendr]` attrs stripped from methods)
21/// - A `static __VTABLE_{crate}_{Trait}_FOR_{Type}` with the declared repr(C) layout
22/// - C wrapper functions and `R_CallMethodDef` entries for each method and const
23/// - R wrapper code string (class-system specific)
24/// - Two `const` items: `{TYPE}_{TRAIT}_CALL_DEFS` and `R_WRAPPERS_{TYPE}_{TRAIT}_IMPL`
25/// - A `TraitNamespaceEntry` when the R wrappers bind the `Class$Trait`
26///   namespace ([`binds_trait_namespace`], #2264)
27///
28/// # Arguments
29///
30/// - `impl_item`: The parsed `impl Trait for Type` block
31/// - `trait_path`: Full path to the trait (e.g., `crate::Counter`)
32/// - `concrete_type`: The implementing type (e.g., `MyCounter`)
33/// - `impl_attrs`: The impl block's options. The class system picks the R
34///   wrapper generator; `blanket` skips emitting the impl block (a blanket impl
35///   already provides it); `internal` / `noexport` control the roxygen export
36///   tags; `no_preconditions` drops the R-side type checks, as on an inherent
37///   impl.
38/// - `abi`: The canonical trait name, fingerprint and callback layout from the declaration.
39pub(super) fn generate_vtable_static(
40    impl_item: &ItemImpl,
41    trait_path: &syn::Path,
42    concrete_type: &syn::Type,
43    impl_attrs: &ImplAttrs,
44    abi: &TraitAbiMetadata,
45    declaration: &[syn::TraitItemFn],
46    defaults: &[syn::ImplItemFn],
47) -> TokenStream {
48    let trait_name = &abi.name;
49
50    // Extract type identifier (for simple types)
51    let type_ident = match concrete_type {
52        syn::Type::Path(type_path) => {
53            let Some(last_seg) = type_path.path.segments.last() else {
54                return syn::Error::new_spanned(
55                    concrete_type,
56                    "type path must have at least one segment",
57                )
58                .into_compile_error();
59            };
60            last_seg.ident.clone()
61        }
62        _ => ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("Unknown"))
            }), ::quote::__private::Option::None)format_ident!("Unknown"),
63    };
64
65    // Extract type name for naming (simplified - handles Path types)
66    let type_name_str = type_to_symbol_name(concrete_type);
67
68    // Generate names (crate-prefixed vtable static — #1273 — routed through the
69    // shared naming.rs helper so this can't drift from the other two
70    // reconstruction sites in `miniextendr_impl_trait.rs`)
71    let vtable_static_name = crate::naming::vtable_static_ident(trait_name, &type_name_str);
72
73    // The impl block renders no page under `@noRd` or a plain `noexport`
74    // (`generate_trait_r_wrapper`'s `suppress_all_rd`); its methods' docs, of
75    // which S3 / vctrs keep the `@param` lines, then keep no links (#1818).
76    let impl_page = crate::roxygen::RdPage::suppressed_if(
77        crate::roxygen::attrs_have_roxygen_tag(&impl_item.attrs, "noRd")
78            || (impl_attrs.noexport && !impl_attrs.internal),
79    );
80
81    // Parse methods and consts from the impl block
82    let mut wrapper_impl = impl_item.clone();
83    wrapper_impl
84        .items
85        .extend(defaults.iter().cloned().map(syn::ImplItem::Fn));
86    let mut all_methods = match extract_methods(&wrapper_impl, impl_page, declaration) {
87        Ok(m) => m,
88        Err(e) => return e.into_compile_error(),
89    };
90    for method in &mut all_methods {
91        let inherited = defaults
92            .iter()
93            .find(|default| default.sig.ident == method.ident);
94        method.inherited_signature = inherited.is_some();
95        // An inherited default is documented by the declaration's rustdoc.
96        if let Some(default) = inherited {
97            method.doc_tags = crate::roxygen::declaration_roxygen_tags(&default.attrs);
98        }
99    }
100    let consts = extract_consts(impl_item);
101
102    // Separate skipped methods: skipped methods are kept in the emitted impl block
103    // but excluded from C wrappers, R wrappers and call defs. The declaration
104    // alone determines vtable membership, including when an impl hides a wrapper.
105    let methods: Vec<&TraitMethod> = all_methods.iter().filter(|m| !m.skip).collect();
106
107    // Generate C wrappers and call defs for each non-skipped method
108    let method_c_wrappers: Vec<TokenStream> = methods
109        .iter()
110        .map(|m| generate_trait_method_c_wrapper(m, &type_ident, trait_name, trait_path))
111        .collect();
112
113    // Generate C wrappers for consts
114    let const_c_wrappers: Vec<TokenStream> = consts
115        .iter()
116        .map(|c| generate_trait_const_c_wrapper(c, &type_ident, trait_name, trait_path))
117        .collect();
118
119    // Combine C wrappers
120    let c_wrappers: Vec<TokenStream> = method_c_wrappers
121        .into_iter()
122        .chain(const_c_wrappers)
123        .collect();
124
125    // Check if impl block has @noRd doc comment (strip @param from class-level tags)
126    let raw_impl_tags = crate::roxygen::roxygen_tags_from_attrs(&impl_item.attrs, impl_page);
127    let (impl_doc_tags, param_warnings) = crate::roxygen::strip_method_tags(
128        &raw_impl_tags,
129        &type_ident.to_string(),
130        impl_item.impl_token.span,
131    );
132    let class_has_no_rd = crate::roxygen::has_roxygen_tag(&impl_doc_tags, "noRd");
133
134    // Generate R wrapper code string based on class system (only non-skipped methods)
135    let methods_owned: Vec<TraitMethod> = methods.iter().map(|m| (*m).clone()).collect();
136    let r_wrapper_string = match generate_trait_r_wrapper(
137        &type_ident,
138        trait_name,
139        &methods_owned,
140        &consts,
141        TraitWrapperOpts {
142            class_system: impl_attrs.class_system,
143            class_has_no_rd,
144            internal: impl_attrs.internal,
145            noexport: impl_attrs.noexport,
146            impl_preconditions: impl_attrs.preconditions,
147        },
148    ) {
149        Ok(s) => s,
150        Err(e) => return e.into_compile_error(),
151    };
152
153    // A trait impl that binds `Class$Trait` tells the wrapper writer, which
154    // keeps the type's S3 or vctrs class environment for it (#2264, #2289):
155    // the type's own impl blocks are separate expansions and can't see this
156    // one.
157    let trait_namespace_entry = if binds_trait_namespace(
158        impl_attrs.class_system,
159        &methods_owned,
160        &consts,
161    ) {
162        {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "const");
    ::quote::__private::push_underscore(&mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_pound(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "cfg_attr");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "not");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s, "target_arch");
                                    ::quote::__private::push_eq(&mut _s);
                                    ::quote::__private::parse(&mut _s, "\"wasm32\"");
                                    _s
                                });
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "linkme");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s,
                                "distributed_slice");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "registry");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s,
                                        "MX_TRAIT_NAMESPACES");
                                    _s
                                });
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "linkme");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s, "crate");
                                    ::quote::__private::push_eq(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "linkme");
                                    _s
                                });
                            _s
                        });
                    _s
                });
            ::quote::__private::push_ident(&mut _s, "static");
            ::quote::__private::push_ident(&mut _s, "TRAIT_NAMESPACE");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "registry");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "TraitNamespaceEntry");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "registry");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "TraitNamespaceEntry");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "type_path");
                    ::quote::__private::push_colon(&mut _s);
                    ::quote::__private::push_or_or(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "any");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "type_name");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_lt(&mut _s);
                    ::quote::ToTokens::to_tokens(&concrete_type, &mut _s);
                    ::quote::__private::push_gt(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
163            const _: () = {
164                #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_TRAIT_NAMESPACES), linkme(crate = ::miniextendr_api::linkme))]
165                static TRAIT_NAMESPACE: ::miniextendr_api::registry::TraitNamespaceEntry =
166                    ::miniextendr_api::registry::TraitNamespaceEntry {
167                        type_path: || ::core::any::type_name::<#concrete_type>(),
168                    };
169            };
170        }
171    } else {
172        ::quote::__private::TokenStream::new();quote::quote! {}
173    };
174
175    // Generate constant name for R wrapper registration
176    let r_wrappers_const = crate::naming::trait_impl_wrappers_ident(&type_name_str, trait_name);
177
178    // Generate trait dispatch entry name
179    let dispatch_entry_name = crate::naming::trait_dispatch_ident(trait_name, &type_name_str);
180
181    let trait_tag = &abi.tag;
182
183    // Format R wrapper as raw string literal
184    let r_wrapper_str = crate::r_wrapper_raw_literal(
185        &r_wrapper_string,
186        &crate::r_shadowing::formal_names(
187            methods_owned
188                .iter()
189                .map(|m| (&m.sig.inputs, Default::default())),
190        ),
191    );
192    let source_loc_doc = crate::source_location_doc(type_ident.span());
193    let source_start = type_ident.span().start();
194    let source_line_lit = syn::LitInt::new(&source_start.line.to_string(), type_ident.span());
195    let source_col_lit =
196        syn::LitInt::new(&(source_start.column + 1).to_string(), type_ident.span());
197
198    // Strip #[miniextendr(...)] attrs from methods before emitting,
199    // so they don't trigger another macro expansion.
200    //
201    // Skip emitting the impl block when:
202    // - Body is empty (no methods, no consts) — blanket impl provides it
203    // - `blanket` flag is set — a blanket impl exists, methods are only for
204    //   C wrapper signature extraction, not for actual trait implementation
205    let has_items = !all_methods.is_empty() || !consts.is_empty();
206    let clean_impl_tokens = if has_items && !impl_attrs.blanket {
207        let mut clean_impl = impl_item.clone();
208        for item in &mut clean_impl.items {
209            if let syn::ImplItem::Fn(method) = item {
210                method
211                    .attrs
212                    .retain(|attr| !attr.path().is_ident("miniextendr"));
213                crate::trait_receiver::rewrite(&mut method.sig, Some(&mut method.block));
214            }
215        }
216        {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&clean_impl, &mut _s);
    _s
}quote::quote! { #clean_impl }
217    } else {
218        ::quote::__private::TokenStream::new();quote::quote! {}
219    };
220
221    let vtable_static_tokens =
222        match generate_impl_vtable(abi, concrete_type, trait_path, &all_methods, declaration) {
223            Ok(tokens) => tokens,
224            Err(error) => return error.into_compile_error(),
225        };
226
227    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&clean_impl_tokens, &mut _s);
    ::quote::ToTokens::to_tokens(&param_warnings, &mut _s);
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s, "\"Vtable for `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "stringify");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&concrete_type, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"` implementing `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "stringify");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&trait_path, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "\"Generated by `#[miniextendr]` on the trait impl block.\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&source_loc_doc, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"Generated from source file `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "file");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::ToTokens::to_tokens(&vtable_static_tokens, &mut _s);
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut c_wrappers, i) = c_wrappers.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let c_wrappers =
                match c_wrappers.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&c_wrappers, &mut _s);
        }
    }
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"R wrapper code for `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "stringify");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"` implementing `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "stringify");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&trait_name, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&source_loc_doc, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"Generated from source file `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "file");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "cfg_attr");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "not");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "target_arch");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::parse(&mut _s, "\"wasm32\"");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "distributed_slice");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "registry");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "MX_R_WRAPPERS");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "crate");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "linkme");
                            _s
                        });
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "non_upper_case_globals");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "static");
    ::quote::ToTokens::to_tokens(&r_wrappers_const, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "RWrapperEntry");
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "RWrapperEntry");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "priority");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "registry");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "RWrapperPriority");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "TraitImpl");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "source_file");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "file");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "source_line");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&source_line_lit, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "content");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"# Generated from Rust impl `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "stringify");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&trait_name, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"` for `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "stringify");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"` (\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "file");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\":\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&source_line_lit, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\":\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&source_col_lit, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\")\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&r_wrapper_str, &mut _s);
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&trait_namespace_entry, &mut _s);
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"Trait dispatch entry: `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "stringify");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&trait_name, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"` for `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "stringify");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&source_loc_doc, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"Generated from source file `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "file");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "cfg_attr");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "not");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "target_arch");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::parse(&mut _s, "\"wasm32\"");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "distributed_slice");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "registry");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s,
                                "MX_TRAIT_DISPATCH");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "crate");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "linkme");
                            _s
                        });
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "non_upper_case_globals");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "static");
    ::quote::ToTokens::to_tokens(&dispatch_entry_name, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "TraitDispatchEntry");
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "TraitDispatchEntry");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "concrete_tag");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "abi");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "mx_tag_from_path");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "concat");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "core");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "module_path");
                            ::quote::__private::push_bang(&mut _s);
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                ::quote::__private::TokenStream::new());
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::parse(&mut _s, "\"::\"");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "core");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "stringify");
                            ::quote::__private::push_bang(&mut _s);
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
                                    _s
                                });
                            _s
                        });
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "trait_tag");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "abi");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "mx_tag_from_path");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::ToTokens::to_tokens(&trait_tag, &mut _s);
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "vtable");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "std");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "ptr");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "from_ref");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_and(&mut _s);
                            ::quote::ToTokens::to_tokens(&vtable_static_name, &mut _s);
                            _s
                        });
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "cast");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_lt(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "std");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "os");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "raw");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "c_void");
                    ::quote::__private::push_gt(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "vtable_symbol");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "stringify");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::ToTokens::to_tokens(&vtable_static_name, &mut _s);
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
228        // Pass through the original impl block (with method attrs stripped)
229        // — omitted when the body is empty (blanket impl covers it)
230        #clean_impl_tokens
231
232        // Warnings for @param tags on trait impl blocks
233        #param_warnings
234
235        #[doc = ::core::concat!(
236            "Vtable for `",
237            ::core::stringify!(#concrete_type),
238            "` implementing `",
239            ::core::stringify!(#trait_path),
240            "`."
241        )]
242        #[doc = "Generated by `#[miniextendr]` on the trait impl block."]
243        #[doc = #source_loc_doc]
244        #[doc = ::core::concat!("Generated from source file `", ::core::file!(), "`.")]
245        #[doc(hidden)]
246        #vtable_static_tokens
247
248        // C wrappers and call method defs for trait methods
249        #(#c_wrappers)*
250
251        // R wrapper registration via distributed slice
252        #[doc = ::core::concat!(
253            "R wrapper code for `",
254            ::core::stringify!(#type_ident),
255            "` implementing `",
256            ::core::stringify!(#trait_name),
257            "`."
258        )]
259        #[doc = #source_loc_doc]
260        #[doc = ::core::concat!("Generated from source file `", ::core::file!(), "`.")]
261        #[doc(hidden)]
262        #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_R_WRAPPERS), linkme(crate = ::miniextendr_api::linkme))]
263        #[allow(non_upper_case_globals)]
264        static #r_wrappers_const: ::miniextendr_api::registry::RWrapperEntry =
265            ::miniextendr_api::registry::RWrapperEntry {
266                priority: ::miniextendr_api::registry::RWrapperPriority::TraitImpl,
267                source_file: ::core::file!(),
268                source_line: #source_line_lit,
269                content: ::core::concat!(
270                    "# Generated from Rust impl `",
271                    ::core::stringify!(#trait_name),
272                    "` for `",
273                    ::core::stringify!(#type_ident),
274                    "` (",
275                    ::core::file!(),
276                    ":",
277                    #source_line_lit,
278                    ":",
279                    #source_col_lit,
280                    ")",
281                    #r_wrapper_str
282                ),
283            };
284        #trait_namespace_entry
285
286        // Trait dispatch entry for universal_query
287        #[doc = ::core::concat!(
288            "Trait dispatch entry: `",
289            ::core::stringify!(#trait_name),
290            "` for `",
291            ::core::stringify!(#type_ident),
292            "`."
293        )]
294        #[doc = #source_loc_doc]
295        #[doc = ::core::concat!("Generated from source file `", ::core::file!(), "`.")]
296        #[doc(hidden)]
297        #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_TRAIT_DISPATCH), linkme(crate = ::miniextendr_api::linkme))]
298        #[allow(non_upper_case_globals)]
299        static #dispatch_entry_name: ::miniextendr_api::registry::TraitDispatchEntry =
300            ::miniextendr_api::registry::TraitDispatchEntry {
301                concrete_tag: ::miniextendr_api::abi::mx_tag_from_path(
302                    ::core::concat!(::core::module_path!(), "::", ::core::stringify!(#type_ident))
303                ),
304                trait_tag: ::miniextendr_api::abi::mx_tag_from_path(#trait_tag),
305                vtable: unsafe {
306                    // SAFETY: vtable is a static reference valid for program lifetime
307                    ::std::ptr::from_ref(&#vtable_static_name).cast::<::std::os::raw::c_void>()
308                },
309                vtable_symbol: ::core::stringify!(#vtable_static_name),
310            };
311    }
312}
313
314/// Reproduce the declaration's repr(C) layout locally, with its exact field
315/// order and callback types. The versioned declaration tag guards the cast to
316/// the consumer's nominal vtable type. The exported static's name and byte
317/// representation stay the same for native and wasm registration.
318///
319/// Non-generic callbacks belong to the trait, keeping default methods and
320/// declaration-local argument types in their original scope. Generic traits
321/// retain the existing concrete-shim path to avoid recursive conversion bounds.
322pub(super) fn generate_impl_vtable(
323    abi: &TraitAbiMetadata,
324    concrete_type: &syn::Type,
325    trait_path: &syn::Path,
326    methods: &[TraitMethod],
327    declaration: &[syn::TraitItemFn],
328) -> syn::Result<TokenStream> {
329    let trait_name = &abi.name;
330    let type_name = type_to_symbol_name(concrete_type);
331    let static_name = crate::naming::vtable_static_ident(trait_name, &type_name);
332    let layout_name = crate::naming::vtable_layout_ident(trait_name, &type_name);
333    let fields = &abi.fields;
334    let type_ident = match concrete_type {
335        syn::Type::Path(path) => path.path.segments.last().unwrap().ident.clone(),
336        _ => ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("Unknown"))
            }), ::quote::__private::Option::None)format_ident!("Unknown"),
337    };
338    let mut concrete_methods = Vec::new();
339    let mut initializers = Vec::new();
340    for field in &fields.named {
341        let name = field.ident.as_ref().unwrap();
342        let callback = if abi.generic {
343            let Some(method) = methods.iter().find(|method| method.ident == *name) else {
344                let message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this impl must define the required trait method `{0}`",
                name))
    })format!("this impl must define the required trait method `{name}`");
345                return Err(syn::Error::new_spanned(trait_path, message));
346            };
347            concrete_methods.push(method.clone());
348            let shim = crate::naming::vtshim_ident(&type_ident, trait_name, name);
349            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&shim, &mut _s);
    _s
}quote::quote!(#shim)
350        } else {
351            let shim = crate::naming::trait_method_shim_ident(trait_name, name);
352            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_lt(&mut _s);
    ::quote::ToTokens::to_tokens(&concrete_type, &mut _s);
    ::quote::__private::push_ident(&mut _s, "as");
    ::quote::ToTokens::to_tokens(&trait_path, &mut _s);
    ::quote::__private::push_gt(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::ToTokens::to_tokens(&shim, &mut _s);
    _s
}quote::quote!(<#concrete_type as #trait_path>::#shim)
353        };
354        initializers.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&name, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::ToTokens::to_tokens(&callback, &mut _s);
    _s
}quote::quote!(#name: #callback));
355    }
356    let shims = generate_concrete_vtable_shims(
357        &concrete_methods,
358        &type_ident,
359        trait_name,
360        trait_path,
361        concrete_type,
362        declaration,
363    );
364    Ok({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "repr");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "C");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "non_camel_case_types");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "pub");
    ::quote::__private::push_ident(&mut _s, "struct");
    ::quote::ToTokens::to_tokens(&layout_name, &mut _s);
    ::quote::ToTokens::to_tokens(&fields, &mut _s);
    ::quote::ToTokens::to_tokens(&shims, &mut _s);
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "no_mangle");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "non_upper_case_globals");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "pub");
    ::quote::__private::push_ident(&mut _s, "static");
    ::quote::ToTokens::to_tokens(&static_name, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::ToTokens::to_tokens(&layout_name, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&layout_name, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            {
                use ::quote::__private::ext::*;
                let mut _first = true;
                let has_iter = ::quote::__private::HasIterator::<false>;
                #[allow(unused_mut)]
                let (mut initializers, i) = initializers.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let initializers =
                        match initializers.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&initializers, &mut _s);
                }
            }
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
365        #[doc(hidden)]
366        #[repr(C)]
367        #[allow(non_camel_case_types)]
368        pub struct #layout_name #fields
369
370        #shims
371        #[doc(hidden)]
372        #[unsafe(no_mangle)]
373        #[allow(non_upper_case_globals)]
374        pub static #static_name: #layout_name = #layout_name {
375            #(#initializers),*
376        };
377    })
378}
379
380/// Generate concrete vtable shims for a generic trait impl.
381///
382/// For generic traits (e.g., `RExtend<T>`), shims and the vtable builder function
383/// cannot be generated at the trait definition site because where clauses like
384/// `Vec<T>: TryFromSexp` cause recursive trait resolution overflow. Instead, we
385/// generate fully monomorphized shims at the impl site where `T` is known (e.g., `T = i32`).
386///
387/// Each instance method gets a concrete `unsafe extern "C"` shim named
388/// `__vtshim_{crate}_{Type}__{Trait}__{method}` (crate-prefixed for webR
389/// cross-package symbol uniqueness — #1273) that, inside
390/// `with_r_unwind_protect_shim`, follows the declaration shim's steps:
391/// 1. Checks argument arity
392/// 2. Refuses aliased native borrows among the arguments
393/// 3. Extracts SEXP arguments to concrete Rust types
394/// 4. Calls the method via fully-qualified syntax `<Type as Trait>::method()`
395/// 5. Converts the result back to SEXP
396///
397/// Static methods are skipped (not part of the vtable).
398fn generate_concrete_vtable_shims(
399    methods: &[TraitMethod],
400    type_ident: &syn::Ident,
401    trait_name: &syn::Ident,
402    trait_path: &syn::Path,
403    concrete_type: &syn::Type,
404    declaration: &[syn::TraitItemFn],
405) -> TokenStream {
406    let mut shims = Vec::new();
407
408    for method in methods {
409        if !method.has_self {
410            continue; // Static methods not in vtable
411        }
412
413        let method_ident = &method.ident;
414        let shim_name = crate::naming::vtshim_ident(type_ident, trait_name, method_ident);
415        // Match the declaration shim's hygiene: source argument names must
416        // not shadow ABI parameters or the generated receiver reference.
417        let data = syn::Ident::new("data", proc_macro2::Span::mixed_site());
418        let argc = syn::Ident::new("argc", proc_macro2::Span::mixed_site());
419        let argv = syn::Ident::new("argv", proc_macro2::Span::mixed_site());
420        let self_ref = syn::Ident::new("self_ref", proc_macro2::Span::mixed_site());
421        let cell = syn::Ident::new("__mx_cell", proc_macro2::Span::mixed_site());
422        let guard = syn::Ident::new("__mx_guard", proc_macro2::Span::mixed_site());
423        let owner_kind = crate::trait_receiver::owner_receiver(&method.sig);
424        let owner = syn::Ident::new("owner", proc_macro2::Span::mixed_site());
425        let owner_parameter = owner_kind.map(|_| {
426            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&owner, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SEXP");
    ::quote::__private::push_comma(&mut _s);
    _s
}quote::quote! {
427                #owner: ::miniextendr_api::SEXP,
428            }
429        });
430
431        // Count non-self parameters
432        let param_count = method
433            .sig
434            .inputs
435            .iter()
436            .filter(|a| !#[allow(non_exhaustive_omitted_patterns)] match a {
    syn::FnArg::Receiver(_) => true,
    _ => false,
}matches!(a, syn::FnArg::Receiver(_)))
437            .count();
438        let expected_argc = param_count as i32;
439
440        let diagnostic_names = declared_param_names(declaration, method_ident)
441            .expect("trait metadata includes each callback's argument names");
442
443        // Generate argument extraction (concrete types, no generics)
444        let arg_extractions: Vec<TokenStream> = method
445            .sig
446            .inputs
447            .iter()
448            .filter(|a| !#[allow(non_exhaustive_omitted_patterns)] match a {
    syn::FnArg::Receiver(_) => true,
    _ => false,
}matches!(a, syn::FnArg::Receiver(_)))
449            .enumerate()
450            .map(|(i, arg)| {
451                if let syn::FnArg::Typed(pt) = arg {
452                    let name = if let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() {
453                        pat_ident.ident.clone()
454                    } else {
455                        match ::quote::__private::IdentFragmentAdapter(&i) {
    arg =>
        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("arg{0}", arg))
                    }), ::quote::__private::Option::None.or(arg.span())),
}format_ident!("arg{}", i)
456                    };
457                    crate::trait_self_ref::argument(
458                        &name,
459                        &diagnostic_names[i],
460                        &pt.ty,
461                        concrete_type,
462                        i,
463                        &argv,
464                        method
465                            .inherited_signature
466                            .then(|| crate::trait_signature::argument_ident(&name))
467                            .as_ref(),
468                    )
469                } else {
470                    ::quote::__private::TokenStream::new();quote::quote! {}
471                }
472            })
473            .collect();
474
475        // Collect param names for the method call
476        let param_names: Vec<syn::Ident> = method
477            .sig
478            .inputs
479            .iter()
480            .filter(|a| !#[allow(non_exhaustive_omitted_patterns)] match a {
    syn::FnArg::Receiver(_) => true,
    _ => false,
}matches!(a, syn::FnArg::Receiver(_)))
481            .enumerate()
482            .map(|(i, arg)| {
483                if let syn::FnArg::Typed(pt) = arg
484                    && let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
485                {
486                    return pat_ident.ident.clone();
487                }
488                match ::quote::__private::IdentFragmentAdapter(&i) {
    arg =>
        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("arg{0}", arg))
                    }), ::quote::__private::Option::None.or(arg.span())),
}format_ident!("arg{}", i)
489            })
490            .collect();
491
492        let targets = method.inherited_signature.then(|| {
493            param_names
494                .iter()
495                .map(crate::trait_signature::argument_ident)
496                .collect::<Vec<_>>()
497        });
498        let type_setup = method.inherited_signature.then(|| {
499            crate::trait_signature::setup(
500                &method.sig.inputs,
501                method.has_self,
502                &crate::trait_signature::callable(
503                    &method.sig,
504                    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_lt(&mut _s);
    ::quote::ToTokens::to_tokens(&concrete_type, &mut _s);
    ::quote::__private::push_ident(&mut _s, "as");
    ::quote::ToTokens::to_tokens(&trait_path, &mut _s);
    ::quote::__private::push_gt(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::ToTokens::to_tokens(&method_ident, &mut _s);
    _s
}quote::quote!(<#concrete_type as #trait_path>::#method_ident),
505                ),
506            )
507        });
508        let native_borrow_checks = crate::trait_self_ref::native_borrow_checks(
509            param_names
510                .iter()
511                .zip(method.sig.inputs.iter().filter_map(|arg| match arg {
512                    syn::FnArg::Typed(pt) => Some(pt.ty.as_ref()),
513                    syn::FnArg::Receiver(_) => None,
514                }))
515                .enumerate()
516                .map(|(index, (_, ty))| (index, diagnostic_names[index].clone(), ty)),
517            &argv,
518            targets.as_deref(),
519        );
520
521        let self_refs: Vec<_> = param_names
522            .iter()
523            .zip(method.sig.inputs.iter().filter_map(|arg| match arg {
524                syn::FnArg::Typed(pt) => Some(pt.ty.as_ref()),
525                syn::FnArg::Receiver(_) => None,
526            }))
527            .enumerate()
528            .filter_map(|(index, (name, ty))| {
529                crate::type_inspect::self_ref_mutability(ty).map(|mutable| (name, mutable, index))
530            })
531            .collect();
532        let handles: Vec<_> = self_refs
533            .iter()
534            .map(|(name, mutable, index)| {
535                (
536                    crate::trait_self_ref::handle_ident(name),
537                    *mutable,
538                    diagnostic_names[*index].clone(),
539                )
540            })
541            .collect();
542        let alias_checks = crate::trait_self_ref::alias_checks(
543            concrete_type,
544            &handles,
545            Some((crate::trait_self_ref::cell_address(&cell), method.is_mut)),
546        );
547        let self_borrows = self_refs
548            .iter()
549            .map(|(name, mutable, _)| crate::trait_self_ref::borrow(name, *mutable));
550
551        // Generate method call using fully-qualified syntax to avoid ambiguity
552        // with generic trait paths like `RExtend<i32>::method()` where `<` would
553        // be parsed as a comparison operator in expression position.
554        // A visibility marker (`Invisible<T>`, #1213) is a transparent newtype
555        // around the real return; `method.sig.output` is already peeled, so
556        // unwrap it here before the conversion below.
557        let unwrap_marker = |call: TokenStream| -> TokenStream {
558            let call =
559                crate::type_inspect::prepare_return_value(call, method.invisible, method.serialize);
560            match &method.return_wrap {
561                Some(wrap) => wrap.prepare_value(call),
562                None => call,
563            }
564        };
565        let invocation = unwrap_marker({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_lt(&mut _s);
    ::quote::ToTokens::to_tokens(&concrete_type, &mut _s);
    ::quote::__private::push_ident(&mut _s, "as");
    ::quote::ToTokens::to_tokens(&trait_path, &mut _s);
    ::quote::__private::push_gt(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::ToTokens::to_tokens(&method_ident, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&self_ref, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            {
                use ::quote::__private::ext::*;
                let mut _first = true;
                let has_iter = ::quote::__private::HasIterator::<false>;
                #[allow(unused_mut)]
                let (mut param_names, i) = param_names.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let param_names =
                        match param_names.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&param_names, &mut _s);
                }
            }
            _s
        });
    _s
}quote::quote! {
566            <#concrete_type as #trait_path>::#method_ident(#self_ref, #(#param_names),*)
567        });
568        // The receiver borrows the value's RefCell for the rest of the shim,
569        // through the result conversion.
570        let receiver = if let Some(kind) = owner_kind {
571            let handle = kind.type_path();
572            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::ToTokens::to_tokens(&self_ref, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&handle, &mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_lt(&mut _s);
            ::quote::ToTokens::to_tokens(&concrete_type, &mut _s);
            ::quote::__private::push_gt(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "from_raw_parts");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_and(&mut _s);
                    ::quote::ToTokens::to_tokens(&owner, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&cell, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
573                let #self_ref = unsafe {
574                    #handle::<#concrete_type>::from_raw_parts(
575                        &#owner,
576                        #cell,
577                    )
578                };
579            }
580        } else {
581            crate::trait_self_ref::receiver_borrow(
582                &cell,
583                &guard,
584                &self_ref,
585                method.is_mut,
586                crate::trait_self_ref::ReceiverStorage::Erased,
587            )
588        };
589
590        // Generate result conversion
591        let has_return = match &method.sig.output {
592            syn::ReturnType::Default => false,
593            syn::ReturnType::Type(_, ty) => {
594                !#[allow(non_exhaustive_omitted_patterns)] match ty.as_ref() {
    syn::Type::Tuple(t) if t.elems.is_empty() => true,
    _ => false,
}matches!(ty.as_ref(), syn::Type::Tuple(t) if t.elems.is_empty())
595            }
596        };
597        // A failed `IntoR` is a classed `result_err` condition (#2272).
598        let result_conversion = if has_return {
599            crate::c_wrapper_builder::return_conversion(
600                &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "result");
    _s
}quote::quote!(result),
601                &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "None");
    _s
}quote::quote!(::core::option::Option::None),
602            )
603        } else {
604            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_underscore(&mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_ident(&mut _s, "result");
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "trait_abi");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "nil");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            _s
        });
    _s
}quote::quote! {
605                let _ = result;
606                unsafe { ::miniextendr_api::trait_abi::nil() }
607            }
608        };
609
610        let method_name_str = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::{1}", trait_name,
                method_ident))
    })format!("{}::{}", trait_name, method_ident);
611
612        shims.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "non_snake_case");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_ident(&mut _s, "extern");
    ::quote::__private::parse(&mut _s, "\"C\"");
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::ToTokens::to_tokens(&shim_name, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&data, &mut _s);
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_star(&mut _s);
            ::quote::__private::push_ident(&mut _s, "mut");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "std");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "os");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "raw");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "c_void");
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&owner_parameter, &mut _s);
            ::quote::ToTokens::to_tokens(&argc, &mut _s);
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_ident(&mut _s, "i32");
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&argv, &mut _s);
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_star(&mut _s);
            ::quote::__private::push_ident(&mut _s, "const");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_rarrow(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SEXP");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "unwind_protect");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s,
                "with_r_unwind_protect_shim");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_or_or(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "trait_abi");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "check_arity");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::ToTokens::to_tokens(&argc, &mut _s);
                                    ::quote::__private::push_comma(&mut _s);
                                    ::quote::ToTokens::to_tokens(&expected_argc, &mut _s);
                                    ::quote::__private::push_comma(&mut _s);
                                    ::quote::ToTokens::to_tokens(&method_name_str, &mut _s);
                                    _s
                                });
                            ::quote::__private::push_semi(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "let");
                            ::quote::ToTokens::to_tokens(&cell, &mut _s);
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "unsafe");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Brace,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_and(&mut _s);
                                    ::quote::__private::push_star(&mut _s);
                                    ::quote::ToTokens::to_tokens(&data, &mut _s);
                                    ::quote::__private::push_dot(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "cast");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "core");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "cell");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "RefCell");
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::ToTokens::to_tokens(&concrete_type, &mut _s);
                                    ::quote::__private::push_shr(&mut _s);
                                    ::quote::__private::push_group(&mut _s,
                                        ::quote::__private::Delimiter::Parenthesis,
                                        ::quote::__private::TokenStream::new());
                                    _s
                                });
                            ::quote::__private::push_semi(&mut _s);
                            ::quote::ToTokens::to_tokens(&type_setup, &mut _s);
                            ::quote::ToTokens::to_tokens(&native_borrow_checks,
                                &mut _s);
                            {
                                use ::quote::__private::ext::*;
                                let has_iter = ::quote::__private::HasIterator::<false>;
                                #[allow(unused_mut)]
                                let (mut arg_extractions, i) =
                                    arg_extractions.quote_into_iter();
                                let has_iter = has_iter | i;
                                <_ as
                                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                                while true {
                                    let arg_extractions =
                                        match arg_extractions.next() {
                                            Some(_x) => ::quote::__private::RepInterp(_x),
                                            None => break,
                                        };
                                    ::quote::ToTokens::to_tokens(&arg_extractions, &mut _s);
                                }
                            }
                            ::quote::ToTokens::to_tokens(&alias_checks, &mut _s);
                            {
                                use ::quote::__private::ext::*;
                                let has_iter = ::quote::__private::HasIterator::<false>;
                                #[allow(unused_mut)]
                                let (mut self_borrows, i) = self_borrows.quote_into_iter();
                                let has_iter = has_iter | i;
                                <_ as
                                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                                while true {
                                    let self_borrows =
                                        match self_borrows.next() {
                                            Some(_x) => ::quote::__private::RepInterp(_x),
                                            None => break,
                                        };
                                    ::quote::ToTokens::to_tokens(&self_borrows, &mut _s);
                                }
                            }
                            ::quote::ToTokens::to_tokens(&receiver, &mut _s);
                            ::quote::__private::push_ident(&mut _s, "let");
                            ::quote::__private::push_ident(&mut _s, "result");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::ToTokens::to_tokens(&invocation, &mut _s);
                            ::quote::__private::push_semi(&mut _s);
                            ::quote::ToTokens::to_tokens(&result_conversion, &mut _s);
                            _s
                        });
                    _s
                });
            _s
        });
    _s
}quote::quote! {
613            #[doc(hidden)]
614            #[allow(non_snake_case)]
615            unsafe extern "C" fn #shim_name(
616                #data: *mut ::std::os::raw::c_void,
617                #owner_parameter
618                #argc: i32,
619                #argv: *const ::miniextendr_api::SEXP,
620            ) -> ::miniextendr_api::SEXP {
621                // with_r_unwind_protect_shim: returns tagged error SEXP on panic
622                // so the View method wrapper can re-panic via repanic_if_rust_error,
623                // allowing rust_* class layering (issue #345).
624                ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(|| {
625                    ::miniextendr_api::trait_abi::check_arity(#argc, #expected_argc, #method_name_str);
626                    let #cell = unsafe { &*#data.cast::<::core::cell::RefCell<#concrete_type>>() };
627                    #type_setup
628                    #native_borrow_checks
629                    #(#arg_extractions)*
630                    #alias_checks
631                    #(#self_borrows)*
632                    #receiver
633                    let result = #invocation;
634                    #result_conversion
635                })
636            }
637        });
638    }
639
640    {
    let mut _s = ::quote::__private::TokenStream::new();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut shims, i) = shims.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let shims =
                match shims.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&shims, &mut _s);
        }
    }
    _s
}quote::quote! { #(#shims)* }
641}
642
643/// Inherit only declaration-level R naming/export metadata. The implementation
644/// owns its execution options, docs and signatures; an explicit impl rename
645/// wins, while a declaration's skipped method is never exported accidentally.
646pub(super) fn inherit_method_metadata(
647    implementation: &mut ItemImpl,
648    declaration: &[syn::TraitItemFn],
649) -> syn::Result<()> {
650    for item in &mut implementation.items {
651        let syn::ImplItem::Fn(method) = item else {
652            continue;
653        };
654        let Some(declared) = declaration
655            .iter()
656            .find(|declared| declared.sig.ident == method.sig.ident)
657        else {
658            continue; // rustc diagnoses methods that do not belong to the trait.
659        };
660        let inherited = parse_trait_method_attrs(&declared.attrs)?;
661        let own = parse_trait_method_attrs(&method.attrs)?;
662        if own.r_name.is_none()
663            && let Some(r_name) = inherited.r_name
664        {
665            method
666                .attrs
667                .push(::syn::__private::parse_quote({
        let mut _s = ::quote::__private::TokenStream::new();
        ::quote::__private::push_pound(&mut _s);
        ::quote::__private::push_group(&mut _s,
            ::quote::__private::Delimiter::Bracket,
            {
                let mut _s = ::quote::__private::TokenStream::new();
                ::quote::__private::push_ident(&mut _s, "miniextendr");
                ::quote::__private::push_group(&mut _s,
                    ::quote::__private::Delimiter::Parenthesis,
                    {
                        let mut _s = ::quote::__private::TokenStream::new();
                        ::quote::__private::push_ident(&mut _s, "r_name");
                        ::quote::__private::push_eq(&mut _s);
                        ::quote::ToTokens::to_tokens(&r_name, &mut _s);
                        _s
                    });
                _s
            });
        _s
    })syn::parse_quote!(#[miniextendr(r_name = #r_name)]));
668        }
669        if inherited.skip && !own.skip {
670            method.attrs.push(::syn::__private::parse_quote({
        let mut _s = ::quote::__private::TokenStream::new();
        ::quote::__private::push_pound(&mut _s);
        ::quote::__private::push_group(&mut _s,
            ::quote::__private::Delimiter::Bracket,
            {
                let mut _s = ::quote::__private::TokenStream::new();
                ::quote::__private::push_ident(&mut _s, "miniextendr");
                ::quote::__private::push_group(&mut _s,
                    ::quote::__private::Delimiter::Parenthesis,
                    {
                        let mut _s = ::quote::__private::TokenStream::new();
                        ::quote::__private::push_ident(&mut _s, "skip");
                        _s
                    });
                _s
            });
        _s
    })syn::parse_quote!(#[miniextendr(skip)]));
671        }
672    }
673    Ok(())
674}
675
676/// The parameter names the declaration's metadata gives `method`, in order.
677/// The metadata names every parameter (`arg<i>` for a declaration pattern).
678fn declared_param_names(
679    declaration: &[syn::TraitItemFn],
680    method: &syn::Ident,
681) -> Option<Vec<String>> {
682    let declared = declaration
683        .iter()
684        .find(|declared| declared.sig.ident == *method)?;
685    Some(
686        declared
687            .sig
688            .inputs
689            .iter()
690            .filter_map(|arg| match arg {
691                syn::FnArg::Typed(arg) => Some(arg),
692                syn::FnArg::Receiver(_) => None,
693            })
694            .map(|arg| {
695                let syn::Pat::Ident(name) = arg.pat.as_ref() else {
696                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("metadata has named arguments")));
}unreachable!("metadata has named arguments")
697                };
698                crate::naming::ident_name(&name.ident)
699            })
700            .collect(),
701    )
702}
703
704/// One parameter of an impl method, which the wrappers name as the
705/// declaration does.
706struct RenamedParam {
707    /// The impl's name for it; `None` for a pattern (`_`, a destructuring).
708    own: Option<String>,
709    /// The name the wrappers use: the declaration's.
710    declared: String,
711}
712
713impl RenamedParam {
714    /// The R formal the impl's name would have given ([`normalize_r_arg_string`]
715    /// drops leading underscores), when it differs from the declared one.
716    ///
717    /// [`normalize_r_arg_string`]: crate::r_wrapper_builder::normalize_r_arg_string
718    fn own_formal(&self) -> Option<String> {
719        let own = crate::r_wrapper_builder::normalize_r_arg_string(self.own.as_deref()?);
720        (own != self.formal()).then_some(own)
721    }
722
723    /// The R formal: the declared name, normalized.
724    fn formal(&self) -> String {
725        crate::r_wrapper_builder::normalize_r_arg_string(&self.declared)
726    }
727}
728
729/// Name every parameter of `sig`, a copy of an impl method's signature, as
730/// the declaration's metadata does (`declared`; `arg<i>` for a declaration
731/// pattern), so every impl of a trait has the same R formals and argument
732/// errors. Without the declaration's names, or with another count, which
733/// rustc refuses, a named parameter keeps its name and a pattern becomes
734/// `arg<i>`. A name already taken gets a `_` suffix. Returns each
735/// parameter's names, in order.
736fn name_params_as_declared(
737    sig: &mut syn::Signature,
738    declared: Option<&[String]>,
739) -> Vec<RenamedParam> {
740    let params: Vec<&mut syn::PatType> = sig
741        .inputs
742        .iter_mut()
743        .filter_map(|arg| match arg {
744            syn::FnArg::Typed(arg) => Some(arg),
745            syn::FnArg::Receiver(_) => None,
746        })
747        .collect();
748    let declared = declared.filter(|names| names.len() == params.len());
749    let mut used = std::collections::HashSet::new();
750    let mut renamed = Vec::with_capacity(params.len());
751    for (index, param) in params.into_iter().enumerate() {
752        let own = match param.pat.as_ref() {
753            syn::Pat::Ident(pat) => Some(crate::naming::ident_name(&pat.ident)),
754            _ => None,
755        };
756        let mut name = match declared {
757            Some(names) => names[index].clone(),
758            None => own.clone().unwrap_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("arg{0}", index))
    })format!("arg{index}")),
759        };
760        while !used.insert(name.clone()) {
761            name.push('_');
762        }
763        let mut ident = crate::naming::name_ident(&name);
764        ident.set_span(syn::spanned::Spanned::span(&param.pat));
765        param.pat = ::syn::__private::parse_quote({
        let mut _s = ::quote::__private::TokenStream::new();
        ::quote::ToTokens::to_tokens(&ident, &mut _s);
        _s
    })syn::parse_quote!(#ident);
766        renamed.push(RenamedParam {
767            own,
768            declared: name,
769        });
770    }
771    renamed
772}
773
774/// `options`, keyed by parameter names as the impl method spells them, keyed
775/// by the declared names. A key may also be the declared name already; one
776/// that names no parameter stays, for the caller's check to refuse. Naming
777/// one parameter both ways is an error at `span`.
778fn rekey_params<V>(
779    options: std::collections::HashMap<String, V>,
780    renamed: &[RenamedParam],
781    what: &str,
782    span: proc_macro2::Span,
783) -> syn::Result<std::collections::HashMap<String, V>> {
784    let mut keys: std::collections::HashMap<String, String> = std::collections::HashMap::new();
785    let mut rekeyed = std::collections::HashMap::with_capacity(options.len());
786    for (key, value) in options {
787        let name = key.strip_prefix("r#").unwrap_or(&key);
788        let target = renamed
789            .iter()
790            .find(|param| param.own.as_deref() == Some(name))
791            .or_else(|| renamed.iter().find(|param| param.declared == name))
792            .map_or_else(|| key.clone(), |param| param.declared.clone());
793        if let Some(other) = keys.insert(target.clone(), key.clone()) {
794            let (first, second) = if other < key {
795                (other, key)
796            } else {
797                (key, other)
798            };
799            return Err(syn::Error::new(
800                span,
801                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} name the trait\'s parameter `{1}` twice, as `{2}` and `{3}`",
                what, target, first, second))
    })format!(
802                    "{what} name the trait's parameter `{target}` twice, as `{first}` and \
803                     `{second}`"
804                ),
805            ));
806        }
807        rekeyed.insert(target, value);
808    }
809    Ok(rekeyed)
810}
811
812/// Refuse a method's R code (`r_entry`, `r_post_checks`, `r_on_exit`, a
813/// `defaults(...)` value) that uses a parameter by the impl's name where the
814/// wrapper's formal has the declaration's: R would find no such variable when
815/// the wrapper runs.
816fn check_r_code_uses_declared_names(
817    attrs: &TraitMethodAttrs,
818    renamed: &[RenamedParam],
819    span: proc_macro2::Span,
820) -> syn::Result<()> {
821    let snippets = [
822        ("r_entry", attrs.r_entry.as_deref()),
823        ("r_post_checks", attrs.r_post_checks.as_deref()),
824        (
825            "r_on_exit",
826            attrs.r_on_exit.as_ref().map(|exit| exit.expr.as_str()),
827        ),
828    ]
829    .into_iter()
830    .filter_map(|(what, code)| Some((what, code?)))
831    .chain(
832        attrs
833            .defaults
834            .values()
835            .map(|code| ("defaults(...)", code.as_str())),
836    );
837    for (what, code) in snippets {
838        for param in renamed {
839            if let Some(own) = param.own_formal()
840                && crate::r_shadowing::refers_to(code, &own)
841            {
842                return Err(syn::Error::new(
843                    span,
844                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{2} uses `{3}`, this impl\'s name for the trait\'s parameter `{0}`; R wrappers take the trait\'s parameter names, so write `{1}`",
                param.formal(), param.formal(), what, own))
    })format!(
845                        "{what} uses `{own}`, this impl's name for the trait's parameter `{}`; \
846                         R wrappers take the trait's parameter names, so write `{}`",
847                        param.formal(),
848                        param.formal()
849                    ),
850                ));
851            }
852        }
853    }
854    Ok(())
855}
856
857/// Extract all methods from a trait impl block as [`TraitMethod`] structs.
858///
859/// Parses each `ImplItem::Fn` to determine receiver type, mutability,
860/// `#[miniextendr(...)]` attributes (coerce, skip, r_name, defaults, etc.),
861/// and roxygen `@param` tags from doc comments. `impl_page` is whether the
862/// impl block renders a help page: the methods' docs keep no links when it
863/// does not.
864pub(super) fn extract_methods(
865    impl_item: &ItemImpl,
866    impl_page: crate::roxygen::RdPage,
867    declaration: &[syn::TraitItemFn],
868) -> syn::Result<Vec<TraitMethod>> {
869    let mut methods = Vec::new();
870    for item in &impl_item.items {
871        if let syn::ImplItem::Fn(method) = item {
872            // Check receiver type
873            let (has_self, is_mut) = method.sig.inputs.first().map_or((false, false), |arg| {
874                if let syn::FnArg::Receiver(_) = arg {
875                    (true, crate::trait_receiver::is_mut(&method.sig))
876                } else {
877                    (false, false)
878                }
879            });
880            // The unforced dots are no trait-method parameter (#1892), nor is
881            // the RNG guard (#2002).
882            crate::miniextendr_fn::refuse_lazy_dots_in_trait_method(&method.sig.inputs)?;
883            crate::miniextendr_fn::refuse_rng_guard_in_trait_method(&method.sig.inputs)?;
884            let mut attrs = parse_trait_method_attrs(&method.attrs)?;
885            // The wrappers name every parameter as the declaration does, for
886            // every impl: the R formals, `e$param` and the messages are the
887            // trait's. Wrappers call the method positionally, so the impl's
888            // body keeps its own names.
889            let mut sig = method.sig.clone();
890            let renamed = name_params_as_declared(
891                &mut sig,
892                declared_param_names(declaration, &method.sig.ident).as_deref(),
893            );
894            let span = method.sig.ident.span();
895            attrs.per_param = rekey_params(
896                std::mem::take(&mut attrs.per_param),
897                &renamed,
898                "the parameter options",
899                attrs.per_param_span.unwrap_or(span),
900            )?;
901            attrs.defaults = rekey_params(
902                std::mem::take(&mut attrs.defaults),
903                &renamed,
904                "defaults(...)",
905                attrs.defaults_span.unwrap_or(span),
906            )?;
907            check_r_code_uses_declared_names(&attrs, &renamed, span)?;
908            // Every parameter `choices(...)` / `inherits(...)` /
909            // `not_inherits(...)` / `no_na(...)` name must exist, as on
910            // inherent methods; `Option<T>` scalar
911            // choices params are the optional form (#1473).
912            crate::miniextendr_fn::finalize_method_param_attrs(
913                &mut attrs.per_param,
914                &sig.inputs,
915                &[],
916                &attrs.defaults,
917                attrs.per_param_span.unwrap_or(span),
918            )?;
919            check_trait_method_defaults(
920                &attrs.defaults,
921                &sig.inputs,
922                attrs.defaults_span.unwrap_or(span),
923            )?;
924
925            // The author's tags; the R wrapper generators pick the `@param`
926            // lines and the page tags from them (every tag but `@title` and a
927            // bare `@export` on blocks without `\usage`,
928            // `r_wrappers::forwarded_body_tag`). The impl's `@param` names a
929            // parameter as the impl does: it documents the declaration's name.
930            let mut doc_tags = crate::roxygen::roxygen_tags_from_attrs(&method.attrs, impl_page);
931            crate::roxygen::rename_param_tags(&mut doc_tags, |name| {
932                renamed
933                    .iter()
934                    .find(|param| param.own_formal().as_deref() == Some(name))
935                    .map(RenamedParam::formal)
936            })
937            .map_err(|message| syn::Error::new(span, message))?;
938            // A method without docs of its own has the declaration's, which
939            // already use the declaration's names.
940            if doc_tags.is_empty()
941                && let Some(declared) = declaration
942                    .iter()
943                    .find(|declared| declared.sig.ident == method.sig.ident)
944            {
945                doc_tags = crate::roxygen::declaration_roxygen_tags(&declared.attrs);
946            }
947
948            // Validate and peel a return-visibility marker (#1213): the
949            // codegen sees the inner type, `.0` unwraps the value.
950            if let syn::ReturnType::Type(_, ty) = &method.sig.output
951                && let Some(err) = crate::type_inspect::visibility_marker_error(ty, "return")
952            {
953                return Err(err);
954            }
955            let (invisible, output) =
956                crate::type_inspect::peel_return_visibility(&method.sig.output);
957            let (return_wrap, output) = crate::return_wrap::resolve(&output, attrs.wrap)?;
958            if return_wrap
959                .as_ref()
960                .is_some_and(|wrap| wrap.conversion.is_some())
961            {
962                return Err(syn::Error::new_spanned(
963                    &method.sig.output,
964                    "ConvertTo/ConvertFrom require an inherent S7 impl method",
965                ));
966            }
967            if return_wrap.is_some() && (attrs.serialize || attrs.unwrap_in_r) {
968                return Err(syn::Error::new_spanned(
969                    &method.sig.output,
970                    "explicit class wrapping cannot be combined with serialize or unwrap_in_r",
971                ));
972            }
973            sig.output = crate::type_inspect::serialize_return_type(&output, attrs.serialize);
974
975            methods.push(TraitMethod {
976                inherited_signature: false,
977                ident: method.sig.ident.clone(),
978                sig,
979                invisible,
980                has_self,
981                is_mut,
982                coerce: attrs.coerce,
983                check_interrupt: attrs.check_interrupt,
984                rng: attrs.rng,
985                unwrap_in_r: attrs.unwrap_in_r,
986                serialize: attrs.serialize,
987                return_wrap,
988                param_defaults: attrs.defaults,
989                doc_tags,
990                skip: attrs.skip,
991                r_name: attrs.r_name,
992                strict: attrs.strict,
993                lifecycle: attrs.lifecycle,
994                r_entry: attrs.r_entry,
995                r_post_checks: attrs.r_post_checks,
996                r_on_exit: attrs.r_on_exit,
997                no_shortcut: attrs.no_shortcut,
998                generic: attrs.generic,
999                receiver: attrs.receiver,
1000                no_dispatch_dots: attrs.no_dispatch_dots,
1001                per_param: attrs.per_param,
1002                preconditions: attrs.preconditions,
1003            });
1004        }
1005    }
1006    Ok(methods)
1007}
1008
1009/// Reject a `defaults(...)` entry that names no parameter of the trait
1010/// method, with the inherent-impl wording (a typo would otherwise drop the
1011/// default without a word).
1012fn check_trait_method_defaults(
1013    defaults: &std::collections::HashMap<String, String>,
1014    inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
1015    span: proc_macro2::Span,
1016) -> syn::Result<()> {
1017    let names: std::collections::HashSet<String> = inputs
1018        .iter()
1019        .filter_map(|arg| match arg {
1020            syn::FnArg::Typed(pt) => match pt.pat.as_ref() {
1021                syn::Pat::Ident(pat_ident) => Some(crate::naming::ident_name(&pat_ident.ident)),
1022                _ => None,
1023            },
1024            syn::FnArg::Receiver(_) => None,
1025        })
1026        .collect();
1027    let mut invalid: Vec<&str> = defaults
1028        .keys()
1029        .map(String::as_str)
1030        .filter(|key| !names.contains(key.strip_prefix("r#").unwrap_or(key)))
1031        .collect();
1032    if invalid.is_empty() {
1033        return Ok(());
1034    }
1035    invalid.sort_unstable();
1036    Err(syn::Error::new(
1037        span,
1038        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("defaults(...) references non-existent parameter(s): {0}",
                invalid.join(", ")))
    })format!(
1039            "defaults(...) references non-existent parameter(s): {}",
1040            invalid.join(", ")
1041        ),
1042    ))
1043}
1044
1045/// Parsed `#[miniextendr(...)]` attributes for a single trait method.
1046///
1047/// Extracted from method-level attributes to control C wrapper behavior and
1048/// R wrapper generation.
1049struct TraitMethodAttrs {
1050    /// Enable `Rf_coerceVector` for all parameters. Set by `coerce` /
1051    /// `no_coerce`, else the `coerce-default` feature.
1052    coerce: bool,
1053    /// Call `R_CheckUserInterrupt` before the method body.
1054    check_interrupt: bool,
1055    /// Wrap the call in `GetRNGstate`/`PutRNGstate` for reproducible random number generation.
1056    rng: bool,
1057    /// Return `Result<T, E>` to R without unwrapping (R wrapper receives the result variant).
1058    unwrap_in_r: bool,
1059    /// Serialize the complete return value through `AsSerialize<T>`.
1060    serialize: bool,
1061    wrap: Option<ClassSystem>,
1062    /// Exclude this method from all generated wrappers (C, R, vtable shims).
1063    skip: bool,
1064    /// Parameter default values: keys are parameter names, values are R expressions.
1065    defaults: std::collections::HashMap<String, String>,
1066    /// Override the R-facing method name.
1067    r_name: Option<String>,
1068    /// Strict output conversion: panic instead of lossy widening for i64/u64/isize/usize.
1069    /// Set by `strict` / `no_strict`, else the `strict-default` feature.
1070    strict: bool,
1071    /// Lifecycle specification for deprecation/experimental status.
1072    lifecycle: Option<crate::lifecycle::LifecycleSpec>,
1073    /// R code to inject at the very top of the wrapper body.
1074    r_entry: Option<String>,
1075    /// R code to inject after all checks, immediately before `.Call()`.
1076    r_post_checks: Option<String>,
1077    /// Register `on.exit()` cleanup code in the R wrapper.
1078    r_on_exit: Option<crate::miniextendr_fn::ROnExit>,
1079    /// Opt out of the S7 fast-dispatch shortcut (`#[miniextendr(s7(no_shortcut))]`).
1080    no_shortcut: bool,
1081    generic: Option<String>,
1082    receiver: Option<String>,
1083    no_dispatch_dots: bool,
1084    /// The method's bare `preconditions` / `no_preconditions` (#1017); the
1085    /// last one written wins. See `TraitMethod::preconditions`.
1086    preconditions: Option<bool>,
1087    /// Per-parameter `match_arg`/`choices`/`several_ok` attributes, keyed by
1088    /// Rust parameter name. See `TraitMethod::per_param`.
1089    per_param: std::collections::HashMap<String, crate::miniextendr_fn::ParamAttrs>,
1090    /// Span of the first `choices` / `choices_several_ok` / `no_default` /
1091    /// `no_na` / `inherits` / `not_inherits` option: where an unknown
1092    /// parameter name is reported.
1093    per_param_span: Option<proc_macro2::Span>,
1094    /// Span of the `defaults(...)` option: where an unknown parameter name in
1095    /// it is reported.
1096    defaults_span: Option<proc_macro2::Span>,
1097}
1098
1099/// Parse `#[miniextendr(...)]` attributes from a trait method.
1100///
1101/// Supports two syntax styles:
1102/// - **Flat**: `#[miniextendr(coerce, rng)]`
1103/// - **Nested class-system**: `#[miniextendr(env(coerce, check_interrupt))]`
1104///
1105/// Both styles can coexist. `coerce` and `strict` default to the `coerce-default` / `strict-default`
1106/// features, as on inherent methods, and `no_coerce` / `no_strict` opt out.
1107fn parse_trait_method_attrs(attrs: &[syn::Attribute]) -> syn::Result<TraitMethodAttrs> {
1108    use syn::spanned::Spanned;
1109    let mut coerce: Option<bool> = None;
1110    let mut check_interrupt = false;
1111    let mut rng = false;
1112    let mut unwrap_in_r = false;
1113    let mut serialize = false;
1114    let mut wrap = None;
1115    let mut skip = false;
1116    let mut strict: Option<bool> = None;
1117    let mut defaults = std::collections::HashMap::new();
1118    let mut r_name: Option<String> = None;
1119    let mut lifecycle: Option<crate::lifecycle::LifecycleSpec> = None;
1120    let mut r_entry: Option<String> = None;
1121    let mut r_post_checks: Option<String> = None;
1122    let mut r_on_exit: Option<crate::miniextendr_fn::ROnExit> = None;
1123    let mut no_shortcut = false;
1124    let mut generic = None;
1125    let mut receiver = None;
1126    let mut no_dispatch_dots = false;
1127    let mut preconditions: Option<bool> = None;
1128    let mut per_param: std::collections::HashMap<String, crate::miniextendr_fn::ParamAttrs> =
1129        std::collections::HashMap::new();
1130    let mut per_param_span: Option<proc_macro2::Span> = None;
1131    let mut defaults_span: Option<proc_macro2::Span> = None;
1132
1133    for attr in attrs {
1134        if !attr.path().is_ident("miniextendr") {
1135            continue;
1136        }
1137
1138        attr.parse_nested_meta(|meta| {
1139            let is_class_meta = meta.path.is_ident("env")
1140                || meta.path.is_ident("r6")
1141                || meta.path.is_ident("s7")
1142                || meta.path.is_ident("s3")
1143                || meta.path.is_ident("s4");
1144
1145            if is_class_meta {
1146                meta.parse_nested_meta(|inner| {
1147                    if inner.path.is_ident("coerce") {
1148                        coerce = Some(true);
1149                    } else if inner.path.is_ident("no_coerce") {
1150                        coerce = Some(false);
1151                    } else if inner.path.is_ident("check_interrupt") {
1152                        check_interrupt = true;
1153                    } else if inner.path.is_ident("unwrap_in_r") {
1154                        unwrap_in_r = true;
1155                    } else if inner.path.is_ident("wrap") {
1156                        let value: syn::LitStr = inner.value()?.parse()?;
1157                        wrap = Some(crate::return_wrap::parse_system(&value)?);
1158                    } else if inner.path.is_ident("serialize") {
1159                        serialize = true;
1160                    } else if inner.path.is_ident("no_shortcut") {
1161                        no_shortcut = true;
1162                    } else if (meta.path.is_ident("s3") || meta.path.is_ident("s4"))
1163                        && inner.path.is_ident("generic")
1164                    {
1165                        let value: syn::LitStr = inner.value()?.parse()?;
1166                        if generic
1167                            .replace(crate::naming::parse_generic(&value)?)
1168                            .is_some()
1169                        {
1170                            return Err(inner.error("generic may be specified only once"));
1171                        }
1172                    } else if (meta.path.is_ident("s3") || meta.path.is_ident("s4"))
1173                        && inner.path.is_ident("receiver")
1174                    {
1175                        let value: syn::LitStr = inner.value()?.parse()?;
1176                        if receiver.replace(crate::naming::parse_r_receiver(&value)?).is_some() {
1177                            return Err(inner.error("receiver may be specified only once"));
1178                        }
1179                    } else if (meta.path.is_ident("s3") || meta.path.is_ident("s4"))
1180                        && inner.path.is_ident("no_dots")
1181                    {
1182                        no_dispatch_dots = true;
1183                    } else {
1184                        return Err(inner.error(
1185                            "unknown nested option; expected `coerce`, `no_coerce`, \
1186                             `check_interrupt`, `unwrap_in_r`, `serialize`, or `no_shortcut` \
1187                             (S3/S4 also accept `generic`, `receiver`, `no_dots`)",
1188                        ));
1189                    }
1190                    Ok(())
1191                })?;
1192            } else if meta.path.is_ident("coerce") {
1193                coerce = Some(true);
1194            } else if meta.path.is_ident("no_coerce") {
1195                coerce = Some(false);
1196            } else if meta.path.is_ident("check_interrupt") {
1197                check_interrupt = true;
1198            } else if meta.path.is_ident("rng") {
1199                if meta.input.peek(syn::token::Paren) {
1200                    return crate::miniextendr_fn::refuse_rng_seed_on_method(
1201                        &meta,
1202                        "a trait method",
1203                    );
1204                }
1205                rng = true;
1206            } else if meta.path.is_ident("unwrap_in_r") {
1207                unwrap_in_r = true;
1208            } else if meta.path.is_ident("wrap") {
1209                let value: syn::LitStr = meta.value()?.parse()?;
1210                wrap = Some(crate::return_wrap::parse_system(&value)?);
1211            } else if meta.path.is_ident("serialize") {
1212                serialize = true;
1213            } else if meta.path.is_ident("skip") {
1214                skip = true;
1215            } else if meta.path.is_ident("no_shortcut") {
1216                no_shortcut = true;
1217            } else if meta.path.is_ident("r_name") {
1218                let value: syn::LitStr = meta.value()?.parse()?;
1219                r_name = Some(value.value());
1220            } else if meta.path.is_ident("strict") {
1221                strict = Some(true);
1222            } else if meta.path.is_ident("no_strict") {
1223                strict = Some(false);
1224            } else if meta.path.is_ident("defaults") {
1225                // Parse defaults(param = "value", param2 = "value2", ...)
1226                defaults_span.get_or_insert(meta.path.span());
1227                meta.parse_nested_meta(|inner| {
1228                    let param_name = inner
1229                        .path
1230                        .get_ident()
1231                        .map(|i| i.to_string())
1232                        .unwrap_or_default();
1233                    let value: syn::LitStr = inner.value()?.parse()?;
1234                    defaults.insert(param_name, value.value());
1235                    Ok(())
1236                })?;
1237            } else if meta.path.is_ident("lifecycle") {
1238                if meta.input.peek(::syn::token::Eqsyn::Token![=]) {
1239                    // lifecycle = "stage"
1240                    let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
1241                    let value: syn::LitStr = meta.input.parse()?;
1242                    let stage = crate::lifecycle::LifecycleStage::from_str(&value.value())
1243                        .ok_or_else(|| {
1244                            syn::Error::new(
1245                                value.span(),
1246                                "invalid lifecycle stage; expected one of: experimental, stable, superseded, soft-deprecated, deprecated, defunct",
1247                            )
1248                        })?;
1249                    lifecycle = Some(crate::lifecycle::LifecycleSpec::new(stage));
1250                } else {
1251                    // lifecycle(stage = "deprecated", when = "0.4.0", ...)
1252                    let mut spec = crate::lifecycle::LifecycleSpec::default();
1253                    meta.parse_nested_meta(|inner| {
1254                        let key = inner.path.get_ident()
1255                            .ok_or_else(|| inner.error("expected identifier"))?
1256                            .to_string();
1257                        let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1258                        let value: syn::LitStr = inner.input.parse()?;
1259                        match key.as_str() {
1260                            "stage" => {
1261                                spec.stage = crate::lifecycle::LifecycleStage::from_str(&value.value())
1262                                    .ok_or_else(|| syn::Error::new(value.span(), "invalid lifecycle stage"))?;
1263                            }
1264                            "when" => spec.when = Some(value.value()),
1265                            "what" => spec.what = Some(value.value()),
1266                            "with" => spec.with = Some(value.value()),
1267                            "details" => spec.details = Some(value.value()),
1268                            "id" => spec.id = Some(value.value()),
1269                            _ => return Err(inner.error(
1270                                "unknown lifecycle option; expected: stage, when, what, with, details, id"
1271                            )),
1272                        }
1273                        Ok(())
1274                    })?;
1275                    lifecycle = Some(spec);
1276                }
1277            } else if meta.path.is_ident("r_entry") {
1278                let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
1279                let value: syn::LitStr = meta.input.parse()?;
1280                r_entry = Some(value.value());
1281            } else if meta.path.is_ident("r_post_checks") {
1282                let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
1283                let value: syn::LitStr = meta.input.parse()?;
1284                r_post_checks = Some(value.value());
1285            } else if meta.path.is_ident("r_on_exit") {
1286                if meta.input.peek(::syn::token::Eqsyn::Token![=]) {
1287                    // Short form: r_on_exit = "expr"
1288                    let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
1289                    let value: syn::LitStr = meta.input.parse()?;
1290                    r_on_exit = Some(crate::miniextendr_fn::ROnExit {
1291                        expr: value.value(),
1292                        add: true,
1293                        after: true,
1294                    });
1295                } else {
1296                    // Long form: r_on_exit(expr = "...", add = false, after = false)
1297                    let mut expr = None;
1298                    let mut add = true;
1299                    let mut after = true;
1300                    meta.parse_nested_meta(|inner| {
1301                        if inner.path.is_ident("expr") {
1302                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1303                            let value: syn::LitStr = inner.input.parse()?;
1304                            expr = Some(value.value());
1305                        } else if inner.path.is_ident("add") {
1306                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1307                            let value: syn::LitBool = inner.input.parse()?;
1308                            add = value.value;
1309                        } else if inner.path.is_ident("after") {
1310                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1311                            let value: syn::LitBool = inner.input.parse()?;
1312                            after = value.value;
1313                        } else {
1314                            return Err(inner.error(
1315                                "unknown r_on_exit option; expected `expr`, `add`, or `after`",
1316                            ));
1317                        }
1318                        Ok(())
1319                    })?;
1320                    let expr = expr.ok_or_else(|| {
1321                        meta.error("r_on_exit(...) requires `expr = \"...\"` specifying the R expression")
1322                    })?;
1323                    r_on_exit = Some(crate::miniextendr_fn::ROnExit { expr, add, after });
1324                }
1325            } else if meta.path.is_ident("choices") {
1326                per_param_span.get_or_insert(meta.path.span());
1327                // `choices(param = "a, b, c", param2 = "x, y")` — explicit string choice lists.
1328                //
1329                // NOTE: `match_arg`/`match_arg_several_ok` (choices derived from a
1330                // `#[derive(MatchArg)]` enum's `CHOICES` const) are intentionally NOT
1331                // supported here yet. The inherent-impl path additionally emits a
1332                // `MX_MATCH_ARG_CHOICES` registration
1333                // (`generate_method_match_arg_entries` in
1334                // `miniextendr_impl.rs`) that resolves the write-time placeholder
1335                // formal default into the enum's literal choice list — trait methods
1336                // have no equivalent metadata registration yet, so accepting `match_arg`
1337                // here would silently ship a formal default that never resolves
1338                // (`object '.__MX_MATCH_ARG_CHOICES_...__' not found` at call time).
1339                // `choices(...)` needs no such resolution (the literal list is baked in
1340                // at macro-expansion time), so it's safe to support today. Tracked in
1341                // the trait-method-emitter follow-up issue for full match_arg parity.
1342                meta.parse_nested_meta(|inner| {
1343                    let name = crate::miniextendr_fn::method_check_param(&inner)?;
1344                    let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1345                    let value: syn::LitStr = inner.input.parse()?;
1346                    let choices = crate::r_wrapper_builder::split_choice_list(&value.value());
1347                    per_param.entry(name).or_default().choices = Some(choices);
1348                    Ok(())
1349                })?;
1350            } else if meta.path.is_ident("choices_several_ok") {
1351                per_param_span.get_or_insert(meta.path.span());
1352                // `choices_several_ok(param = "a, b, c")` — choices + several_ok.
1353                meta.parse_nested_meta(|inner| {
1354                    let name = crate::miniextendr_fn::method_check_param(&inner)?;
1355                    let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1356                    let value: syn::LitStr = inner.input.parse()?;
1357                    let choices = crate::r_wrapper_builder::split_choice_list(&value.value());
1358                    let entry = per_param.entry(name).or_default();
1359                    entry.choices = Some(choices);
1360                    entry.several_ok = true;
1361                    Ok(())
1362                })?;
1363            } else if meta.path.is_ident("no_default") {
1364                per_param_span.get_or_insert(meta.path.span());
1365                // `no_default(p, q)` — choice params whose R formal has no
1366                // default (#1828).
1367                crate::miniextendr_fn::parse_method_no_default(&meta, &mut per_param)?;
1368            } else if meta.path.is_ident("preconditions") || meta.path.is_ident("no_preconditions")
1369            {
1370                // Bare: the whole method keeps / drops its type-derived R-side
1371                // checks. `preconditions(p)` / `no_preconditions(p)`: those
1372                // parameters. The last one written wins.
1373                let keep = meta.path.is_ident("preconditions");
1374                if meta.input.peek(syn::token::Paren) {
1375                    per_param_span.get_or_insert(meta.path.span());
1376                    crate::miniextendr_fn::parse_method_preconditions(&meta, &mut per_param, keep)?;
1377                } else {
1378                    preconditions = Some(keep);
1379                }
1380            } else if meta.path.is_ident("convert") {
1381                per_param_span.get_or_insert(meta.path.span());
1382                crate::miniextendr_fn::parse_method_convert(&meta, &mut per_param)?;
1383            } else if meta.path.is_ident("no_na") {
1384                per_param_span.get_or_insert(meta.path.span());
1385                // `no_na(p, q(message = "..."))` — R-side `!anyNA(p)` checks.
1386                crate::miniextendr_fn::parse_method_no_na(&meta, &mut per_param)?;
1387            } else if let Some(check) = crate::miniextendr_fn::ClassCheck::of(&meta.path) {
1388                per_param_span.get_or_insert(meta.path.span());
1389                // `inherits(p = "cls_a, cls_b", q(class = "cls", message = "..."))` —
1390                // R-side `inherits(p, c(...))` checks; `not_inherits(...)` the
1391                // same shape, `!inherits(p, c(...))`.
1392                crate::miniextendr_fn::parse_method_class_check(&meta, &mut per_param, check)?;
1393            } else if meta.path.is_ident("formal") {
1394                return Err(meta.error(crate::miniextendr_fn::TRAIT_FORMAL_UNSUPPORTED));
1395            } else {
1396                return Err(meta.error(
1397                    "unknown #[miniextendr] option on trait impl method; expected one of: \
1398                     `env`, `r6`, `s7`, `s3`, `s4`, `coerce`, `no_coerce`, \
1399                     `check_interrupt`, `rng`, `unwrap_in_r`, `serialize`, `skip`, `no_shortcut`, `r_name`, \
1400                     `defaults`, `strict`, `no_strict`, `lifecycle`, `r_entry`, `r_post_checks`, `r_on_exit`, \
1401                     `choices`, `choices_several_ok`, `no_default`, `inherits`, `not_inherits`, `no_na`, \
1402                     `preconditions`, `no_preconditions`",
1403                ));
1404            }
1405            Ok(())
1406        })?;
1407    }
1408
1409    if serialize && unwrap_in_r {
1410        return Err(syn::Error::new(
1411            proc_macro2::Span::call_site(),
1412            "`serialize` cannot be combined with `unwrap_in_r`: it serializes the complete return value, including any Result variant",
1413        ));
1414    }
1415
1416    Ok(TraitMethodAttrs {
1417        coerce: coerce.unwrap_or(falsecfg!(feature = "coerce-default")),
1418        check_interrupt,
1419        rng,
1420        unwrap_in_r,
1421        serialize,
1422        wrap,
1423        skip,
1424        strict: strict.unwrap_or(falsecfg!(feature = "strict-default")),
1425        defaults,
1426        r_name,
1427        lifecycle,
1428        r_entry,
1429        r_post_checks,
1430        r_on_exit,
1431        no_shortcut,
1432        generic,
1433        receiver,
1434        no_dispatch_dots,
1435        preconditions,
1436        per_param,
1437        per_param_span,
1438        defaults_span,
1439    })
1440}
1441
1442/// Extract associated constant items from a trait impl block.
1443///
1444/// Each `const NAME: Type = value;` in the impl block becomes a [`TraitConst`]
1445/// that will get its own zero-argument C wrapper for R access.
1446fn extract_consts(impl_item: &ItemImpl) -> Vec<TraitConst> {
1447    impl_item
1448        .items
1449        .iter()
1450        .filter_map(|item| {
1451            if let syn::ImplItem::Const(const_item) = item {
1452                Some(TraitConst {
1453                    ident: const_item.ident.clone(),
1454                    ty: const_item.ty.clone(),
1455                })
1456            } else {
1457                None
1458            }
1459        })
1460        .collect()
1461}
1462
1463/// Generate a C wrapper function and `R_CallMethodDef` for a single trait method.
1464///
1465/// Uses `CWrapperContext` builder to produce:
1466/// - An `extern "C-unwind"` function callable from R via `.Call()`
1467/// - A `R_CallMethodDef` constant for symbol registration
1468///
1469/// Instance methods (`has_self`) extract the object via `ErasedExternalPtr::from_sexp`
1470/// and call with fully-qualified trait syntax `<Type as Trait>::method(self_ref, ...)`.
1471///
1472/// `&Self` / `&mut Self` parameters are borrowed external arguments (#2106): the C wrapper
1473/// converts each to its `ExternalPtr<Type>` handle and borrows it with the declared
1474/// mutability for the call, after checking that no two of them alias while one is mutable.
1475pub(super) fn generate_trait_method_c_wrapper(
1476    method: &TraitMethod,
1477    type_ident: &syn::Ident,
1478    trait_name: &syn::Ident,
1479    trait_path: &syn::Path,
1480) -> TokenStream {
1481    use crate::c_wrapper_builder::{CWrapperContext, ReturnHandling};
1482
1483    let method_ident = &method.ident;
1484    let c_ident = method.c_wrapper_ident(type_ident, trait_name);
1485    let call_method_def_ident = method.call_method_def_ident(type_ident, trait_name);
1486
1487    // Build rust argument names from the signature (excluding self receiver)
1488    let rust_args: Vec<syn::Ident> = method
1489        .sig
1490        .inputs
1491        .iter()
1492        .filter_map(|arg| {
1493            if let syn::FnArg::Typed(pt) = arg {
1494                if let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() {
1495                    Some(pat_ident.ident.clone())
1496                } else {
1497                    None
1498                }
1499            } else {
1500                None
1501            }
1502        })
1503        .collect();
1504
1505    // Filter inputs to exclude the receiver (builder handles self separately with has_self()).
1506    // `&Self` / `&mut Self` parameters stay: the builder converts them to their handles and
1507    // borrows them for the call (#2106). Track them for the alias checks.
1508    let mut self_ref_params = Vec::new();
1509    let filtered_inputs: syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]> = method
1510        .sig
1511        .inputs
1512        .iter()
1513        .filter(|arg| !#[allow(non_exhaustive_omitted_patterns)] match arg {
    syn::FnArg::Receiver(_) => true,
    _ => false,
}matches!(arg, syn::FnArg::Receiver(_)))
1514        .inspect(|arg| {
1515            if let syn::FnArg::Typed(pt) = arg
1516                && let Some(mutable) = crate::type_inspect::self_ref_mutability(&pt.ty)
1517                && let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
1518            {
1519                self_ref_params.push((pat_ident.ident.clone(), mutable));
1520            }
1521        })
1522        .cloned()
1523        .collect();
1524    let call_args = &rust_args;
1525
1526    // Determine return handling
1527    let return_handling = if method.unwrap_in_r
1528        && crate::return_type_analysis::output_is_result(&method.sig.output)
1529    {
1530        ReturnHandling::IntoR
1531    } else {
1532        crate::c_wrapper_builder::detect_return_handling(
1533            &method.sig.output,
1534            method.return_wrap.as_ref(),
1535        )
1536    };
1537
1538    // Generate R wrapper const name (not actually used but needed by builder)
1539    let r_wrappers_const = crate::naming::trait_impl_wrappers_ident(
1540        &crate::naming::ident_name(type_ident),
1541        trait_name,
1542    );
1543
1544    // Build the wrapper using the builder infrastructure
1545    // Use custom call_method_def_ident to avoid collisions with inherent impl methods
1546    // Messages R sees name the method as R calls it (`r_name`).
1547    let mut builder = CWrapperContext::builder(method_ident.clone(), c_ident)
1548        .r_name(method.r_method_name())
1549        .r_wrapper_const(r_wrappers_const)
1550        .inputs(filtered_inputs)
1551        .output(method.sig.output.clone())
1552        .return_handling(return_handling)
1553        .type_context(type_ident.clone())
1554        .call_method_def_ident(call_method_def_ident);
1555
1556    if method.inherited_signature {
1557        builder = builder.inferred_signature(crate::trait_signature::callable(
1558            &method.sig,
1559            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_lt(&mut _s);
    ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
    ::quote::__private::push_ident(&mut _s, "as");
    ::quote::ToTokens::to_tokens(&trait_path, &mut _s);
    ::quote::__private::push_gt(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::ToTokens::to_tokens(&method_ident, &mut _s);
    _s
}quote::quote!(<#type_ident as #trait_path>::#method_ident),
1560        ));
1561    }
1562
1563    let mut post_conversion = Vec::new();
1564    let handles: Vec<_> = self_ref_params
1565        .iter()
1566        .map(|(name, mutable)| {
1567            (
1568                crate::externalptr_args::handle_ident(name),
1569                *mutable,
1570                crate::naming::ident_name(name),
1571            )
1572        })
1573        .collect();
1574    let receiver = method
1575        .has_self
1576        .then(|| ({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "__miniextendr_receiver_addr");
    _s
}quote::quote!(__miniextendr_receiver_addr), method.is_mut));
1577    post_conversion.push(crate::trait_self_ref::alias_checks(
1578        type_ident, &handles, receiver,
1579    ));
1580
1581    if method.has_self {
1582        let self_sexp = crate::naming::self_sexp_ident();
1583        let owner = syn::Ident::new("__mx_owner", proc_macro2::Span::mixed_site());
1584        let self_ptr = syn::Ident::new("self_ptr", proc_macro2::Span::mixed_site());
1585        let self_ref = syn::Ident::new("self_ref", proc_macro2::Span::mixed_site());
1586        let cell = syn::Ident::new("__mx_cell", proc_macro2::Span::mixed_site());
1587        let guard = syn::Ident::new("__mx_guard", proc_macro2::Span::mixed_site());
1588        let resolve = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::ToTokens::to_tokens(&owner, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "externalptr");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "ReceiverOwner");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "resolve");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_lt(&mut _s);
    ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
    ::quote::__private::push_gt(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&self_sexp, &mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
1589            let #owner =
1590                ::miniextendr_api::externalptr::ReceiverOwner::resolve::<#type_ident>(#self_sexp);
1591        };
1592        let self_extraction = if let Some(kind) = crate::trait_receiver::owner_receiver(&method.sig)
1593        {
1594            let receiver_mutability = method.is_mut.then(|| {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "mut");
    _s
}quote::quote!(mut));
1595            let borrow = match kind {
1596                crate::trait_receiver::OwnerReceiver::Shared => {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "borrow");
    _s
}quote::quote!(borrow),
1597                crate::trait_receiver::OwnerReceiver::Mutable => {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "borrow_mut");
    _s
}quote::quote!(borrow_mut),
1598            };
1599            let address = (!self_ref_params.is_empty()).then(|| {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__miniextendr_receiver_addr");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&self_ptr, &mut _s);
    ::quote::__private::push_dot(&mut _s);
    ::quote::__private::push_ident(&mut _s, "as_ptr");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_dot(&mut _s);
    ::quote::__private::push_ident(&mut _s, "cast");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_lt(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "ffi");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "c_void");
    ::quote::__private::push_gt(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
1600                let __miniextendr_receiver_addr = #self_ptr.as_ptr().cast::<::core::ffi::c_void>();
1601            });
1602            // The alias preflight above runs before constructing either an
1603            // exclusive view or any &Self argument reference. The view holds
1604            // the value's RefCell borrow for the rest of the call.
1605            post_conversion.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::ToTokens::to_tokens(&self_ref, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&self_ptr, &mut _s);
    ::quote::__private::push_dot(&mut _s);
    ::quote::ToTokens::to_tokens(&borrow, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
1606                let #self_ref = #self_ptr.#borrow();
1607            });
1608            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&resolve, &mut _s);
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::ToTokens::to_tokens(&receiver_mutability, &mut _s);
    ::quote::ToTokens::to_tokens(&self_ptr, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "externalptr");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "wrap_receiver");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_lt(&mut _s);
            ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
            ::quote::__private::push_gt(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::ToTokens::to_tokens(&owner, &mut _s);
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "get");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    _s
                });
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&address, &mut _s);
    _s
}quote::quote! {
1609                #resolve
1610                let #receiver_mutability #self_ptr = unsafe {
1611                    ::miniextendr_api::externalptr::wrap_receiver::<#type_ident>(#owner.get())
1612                };
1613                #address
1614            }
1615        } else {
1616            let trait_method_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::{1}()", trait_name,
                method.r_method_name()))
    })format!("{}::{}()", trait_name, method.r_method_name());
1617            // Borrow after argument conversion and alias preflight: an R
1618            // error that longjmps out of a conversion would skip the
1619            // borrow's release.
1620            post_conversion.push(crate::trait_self_ref::receiver_borrow(
1621                &cell,
1622                &guard,
1623                &self_ref,
1624                method.is_mut,
1625                crate::trait_self_ref::ReceiverStorage::Ordinary,
1626            ));
1627            let self_setup = (!self_ref_params.is_empty()).then(|| {
1628                let address = crate::trait_self_ref::cell_address(&cell);
1629                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__miniextendr_receiver_addr");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&address, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
1630                    let __miniextendr_receiver_addr = #address;
1631                }
1632            });
1633            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&resolve, &mut _s);
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::ToTokens::to_tokens(&self_ptr, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "externalptr");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "ErasedExternalPtr");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "from_sexp");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::ToTokens::to_tokens(&owner, &mut _s);
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "get");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    _s
                });
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::ToTokens::to_tokens(&cell, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_ident(&mut _s, "match");
    ::quote::ToTokens::to_tokens(&self_ptr, &mut _s);
    ::quote::__private::push_dot(&mut _s);
    ::quote::__private::push_ident(&mut _s, "downcast_cell");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_lt(&mut _s);
    ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
    ::quote::__private::push_gt(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Some");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "cell");
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_ident(&mut _s, "cell");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "None");
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "externalptr");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s,
                "handle_downcast_failed_in");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_lt(&mut _s);
            ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
            ::quote::__private::push_gt(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_and(&mut _s);
                    ::quote::ToTokens::to_tokens(&self_ptr, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&trait_method_name, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&self_setup, &mut _s);
    _s
}quote::quote! {
1634                #resolve
1635                let #self_ptr = unsafe {
1636                    ::miniextendr_api::externalptr::ErasedExternalPtr::from_sexp(#owner.get())
1637                };
1638                let #cell = match #self_ptr.downcast_cell::<#type_ident>() {
1639                    ::core::option::Option::Some(cell) => cell,
1640                    ::core::option::Option::None => ::miniextendr_api::externalptr::handle_downcast_failed_in::<#type_ident>(
1641                        &#self_ptr, #trait_method_name,
1642                    ),
1643                };
1644                #self_setup
1645            }
1646        };
1647
1648        // Call expression with self_ref and dereferenced &Self params
1649        // Use fully-qualified syntax to avoid ambiguity with generic traits
1650        // (e.g., `RExtend<i32>::method()` is ambiguous — `<` parsed as comparison)
1651        let call_expr = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_lt(&mut _s);
    ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
    ::quote::__private::push_ident(&mut _s, "as");
    ::quote::ToTokens::to_tokens(&trait_path, &mut _s);
    ::quote::__private::push_gt(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::ToTokens::to_tokens(&method_ident, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&self_ref, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            {
                use ::quote::__private::ext::*;
                let mut _first = true;
                let has_iter = ::quote::__private::HasIterator::<false>;
                #[allow(unused_mut)]
                let (mut call_args, i) = call_args.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let call_args =
                        match call_args.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&call_args, &mut _s);
                }
            }
            _s
        });
    _s
}quote::quote! {
1652            <#type_ident as #trait_path>::#method_ident(#self_ref, #(#call_args),*)
1653        };
1654        // Unwrap a visibility-marker newtype (#1213); the output type is peeled.
1655        let call_expr = crate::type_inspect::prepare_return_value(
1656            call_expr,
1657            method.invisible,
1658            method.serialize,
1659        );
1660        let call_expr = match &method.return_wrap {
1661            Some(wrap) => wrap.prepare_value(call_expr),
1662            None => call_expr,
1663        };
1664
1665        builder = builder
1666            .pre_call(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self_extraction]))vec![self_extraction])
1667            .call_expr(call_expr)
1668            .has_self();
1669    } else {
1670        // Static method: call directly without self
1671        let call_expr = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_lt(&mut _s);
    ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
    ::quote::__private::push_ident(&mut _s, "as");
    ::quote::ToTokens::to_tokens(&trait_path, &mut _s);
    ::quote::__private::push_gt(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::ToTokens::to_tokens(&method_ident, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            {
                use ::quote::__private::ext::*;
                let mut _first = true;
                let has_iter = ::quote::__private::HasIterator::<false>;
                #[allow(unused_mut)]
                let (mut call_args, i) = call_args.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let call_args =
                        match call_args.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&call_args, &mut _s);
                }
            }
            _s
        });
    _s
}quote::quote! {
1672            <#type_ident as #trait_path>::#method_ident(#(#call_args),*)
1673        };
1674        let call_expr = crate::type_inspect::prepare_return_value(
1675            call_expr,
1676            method.invisible,
1677            method.serialize,
1678        );
1679        let call_expr = match &method.return_wrap {
1680            Some(wrap) => wrap.prepare_value(call_expr),
1681            None => call_expr,
1682        };
1683
1684        builder = builder.call_expr(call_expr);
1685    }
1686
1687    // Apply coerce_all if the method has #[miniextendr(coerce)]
1688    if method.coerce {
1689        builder = builder.coerce_all();
1690    }
1691
1692    // Apply check_interrupt if the method has #[miniextendr(check_interrupt)]
1693    if method.check_interrupt {
1694        builder = builder.check_interrupt();
1695    }
1696
1697    // Apply rng if the method has #[miniextendr(rng)]
1698    if method.rng {
1699        builder = builder.rng();
1700    }
1701
1702    // Apply strict mode for lossy type conversions
1703    if method.strict {
1704        builder = builder.strict();
1705    }
1706
1707    // A `choices(...)` string under an `Either<.., R>` layer decodes with the
1708    // choice-or-other split instead of `TryFromSexp` (the other layers of a
1709    // `choices` string convert through `TryFromSexp` directly).
1710    // `no_na(..)` parameters also have their converted value checked, for what
1711    // the type reads as `NA` beyond the R guard's `anyNA()`.
1712    for (rust_name, attrs) in &method.per_param {
1713        if attrs.convert {
1714            builder = builder.with_convert_param(rust_name.clone());
1715        }
1716        if let Some(leaf) = attrs.layered_leaf() {
1717            builder = builder.layered_choice(rust_name.clone(), leaf);
1718        }
1719        if attrs.checks.no_na {
1720            builder = builder.no_na(rust_name.clone(), attrs.checks.no_na_message.clone());
1721        }
1722    }
1723
1724    // The builder generates both the C wrapper and the R_CallMethodDef
1725    builder.post_conversion(post_conversion).build().generate()
1726}
1727
1728/// Generate a C wrapper function and `R_CallMethodDef` for a trait associated constant.
1729///
1730/// The generated wrapper takes only the call-attribution slot and returns the constant value
1731/// converted to SEXP. Uses fully-qualified syntax `<Type as Trait>::CONST`
1732/// to access the value. Always runs on the main thread.
1733pub(super) fn generate_trait_const_c_wrapper(
1734    trait_const: &TraitConst,
1735    type_ident: &syn::Ident,
1736    trait_name: &syn::Ident,
1737    trait_path: &syn::Path,
1738) -> TokenStream {
1739    use crate::c_wrapper_builder::CWrapperContext;
1740
1741    let const_ident = &trait_const.ident;
1742    let c_ident = trait_const.c_wrapper_ident(type_ident, trait_name);
1743    let call_method_def_ident = trait_const.call_method_def_ident(type_ident, trait_name);
1744    let const_ty = &trait_const.ty;
1745
1746    // Generate R wrapper const name
1747    let r_wrappers_const = crate::naming::trait_impl_wrappers_ident(
1748        &crate::naming::ident_name(type_ident),
1749        trait_name,
1750    );
1751
1752    // Build the call expression to access the const
1753    let call_expr = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_lt(&mut _s);
    ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
    ::quote::__private::push_ident(&mut _s, "as");
    ::quote::ToTokens::to_tokens(&trait_path, &mut _s);
    ::quote::__private::push_gt(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::ToTokens::to_tokens(&const_ident, &mut _s);
    _s
}quote::quote! {
1754        <#type_ident as #trait_path>::#const_ident
1755    };
1756
1757    // Determine return type handling - we need to convert the const to SEXP
1758    // The return type is `-> Type` not just `Type`
1759    let return_type: syn::ReturnType = ::syn::__private::parse_quote({
        let mut _s = ::quote::__private::TokenStream::new();
        ::quote::__private::push_rarrow(&mut _s);
        ::quote::ToTokens::to_tokens(&const_ty, &mut _s);
        _s
    })syn::parse_quote!(-> #const_ty);
1760    let return_handling = crate::c_wrapper_builder::detect_return_handling(&return_type, None);
1761
1762    // Build wrapper - no inputs, just returns the const value
1763    let builder = CWrapperContext::builder(const_ident.clone(), c_ident)
1764        .r_wrapper_const(r_wrappers_const)
1765        .inputs(Default::default()) // no inputs
1766        .output(return_type)
1767        .call_expr(call_expr)
1768        .return_handling(return_handling)
1769        .type_context(type_ident.clone())
1770        .call_method_def_ident(call_method_def_ident);
1771
1772    builder.build().generate()
1773}