Skip to main content

miniextendr_macros/
miniextendr_impl_trait.rs

1//! # `#[miniextendr]` on trait impls - Trait Implementation Registration
2//!
3//! This module handles `#[miniextendr]` applied to trait implementations,
4//! generating the vtable static for cross-package trait dispatch, plus optional
5//! R-callable wrappers for direct method access.
6//!
7//! ## Overview
8//!
9//! When `#[miniextendr]` is applied to an `impl Trait for Type` block, it:
10//!
11//! 1. **Detects the trait** from the impl syntax (no attribute args needed)
12//! 2. **Generates vtable static** using declaration-provided layout and callbacks
13//! 3. **Generates C wrappers** for each trait method (for R `.Call` access)
14//! 4. **Generates R wrapper code** for the trait methods
15//! 5. **Passes through** the original impl block unchanged
16//!
17//! ## Usage
18//!
19//! ```ignore
20//! use miniextendr_api::miniextendr;
21//!
22//! // The trait must have been defined with #[miniextendr]
23//! // which generates __Counter_build_vtable::<T>()
24//!
25//! struct MyCounter { value: i32 }
26//!
27//! #[miniextendr]
28//! impl Counter for MyCounter {
29//!     fn value(&self) -> i32 {
30//!         self.value
31//!     }
32//!     fn increment(&mut self) {
33//!         self.value += 1;
34//!     }
35//!     fn add(&mut self, n: i32) {
36//!         self.value += n;
37//!     }
38//! }
39//! ```
40//!
41//! Generates (conceptually):
42//!
43//! ```ignore
44//! // Original impl block (passed through)
45//! impl Counter for MyCounter {
46//!     fn value(&self) -> i32 { self.value }
47//!     fn increment(&mut self) { self.value += 1; }
48//!     fn add(&mut self, n: i32) { self.value += n; }
49//! }
50//!
51//! // Generated vtable static (crate-prefixed for webR cross-package symbol
52//! // uniqueness — #1273; example assumes a crate named `mypkg`). Its local
53//! // repr(C) type reproduces Counter's declared callback order and types.
54//! pub static __VTABLE_mypkg_Counter_FOR_MyCounter: __VTABLE_mypkg_Counter_FOR_MyCounter_Layout =
55//!     __VTABLE_mypkg_Counter_FOR_MyCounter_Layout {
56//!         value: <MyCounter as Counter>::__Counter_value_shim,
57//!         increment: <MyCounter as Counter>::__Counter_increment_shim,
58//!         add: <MyCounter as Counter>::__Counter_add_shim,
59//!     };
60//! ```
61//!
62//! ## How It Works
63//!
64//! 1. Parse `impl Trait for Type` to extract trait path and concrete type
65//! 2. Generate vtable static name: `__VTABLE_{crate}_{Trait}_FOR_{Type}`
66//! 3. Obtain the declaration's ABI tag and ordered callback fields through its metadata macro
67//! 4. Initialize the local layout with associated or concrete generic callbacks
68//!
69//! ## Trait Detection
70//!
71//! The macro reads the trait directly from the impl syntax:
72//!
73//! ```ignore
74//! #[miniextendr]
75//! impl path::to::Counter for MyType { ... }
76//! //   ^^^^^^^^^^^^^^^^^ detected automatically
77//! ```
78//!
79//! No extra arguments are needed; the trait path is explicit in the impl syntax.
80//!
81//! ## Name Generation
82//!
83//! - **Vtable static**: `__VTABLE_{crate}_{Trait}_FOR_{Type}` (case-preserving;
84//!   `{crate}` is the consuming crate's name, prefixed for webR cross-package symbol
85//!   uniqueness — #1273)
86//! - **Local vtable type**: the static name with `_Layout` appended
87//!
88//! For `impl foo::Counter for my_mod::MyType` in a crate named `mypkg`:
89//! - Static: `__VTABLE_mypkg_Counter_FOR_MyType`
90//! - Callback: `<my_mod::MyType as foo::Counter>::__Counter_value_shim`
91//!
92//! ## Integration with ExternalPtr / TypedExternal
93//!
94//! The generated vtable static is automatically registered via linkme
95//! distributed slices.
96//!
97//! ```ignore
98//! #[derive(ExternalPtr)]
99//! struct MyCounter { value: i32 }
100//!
101//! #[miniextendr]
102//! impl Counter for MyCounter { /* ... */ }
103//! ```
104//!
105//! `ExternalPtr<T>` provides the type identity for the external pointer.
106//! Trait dispatch is wired automatically.
107//!
108//! ## Thread Safety
109//!
110//! The generated vtable is a static constant, safe to access from any thread.
111//! Trait shims, like inherent methods, run on R's main thread.
112
113use proc_macro2::TokenStream;
114use quote::{ToTokens, format_ident};
115use syn::ItemImpl;
116
117use crate::miniextendr_impl::{ClassSystem, ImplAttrs};
118
119/// Parsed method from a trait impl block.
120///
121/// Stores everything needed to generate C wrappers, R wrappers, and vtable
122/// shims for a single method in an `impl Trait for Type` block.
123#[derive(#[automatically_derived]impl ::core::fmt::Debug for TraitMethod {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            "TraitMethod inherited_signature ident sig invisible has_self is_mut coerce check_interrupt rng unwrap_in_r serialize return_wrap param_defaults doc_tags skip r_name strict lifecycle r_entry r_post_checks r_on_exit no_shortcut generic receiver no_dispatch_dots per_param preconditions";
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.inherited_signature, &self.ident, &self.sig,
                        &self.invisible, &self.has_self, &self.is_mut, &self.coerce,
                        &self.check_interrupt, &self.rng, &self.unwrap_in_r,
                        &self.serialize, &self.return_wrap, &self.param_defaults,
                        &self.doc_tags, &self.skip, &self.r_name, &self.strict,
                        &self.lifecycle, &self.r_entry, &self.r_post_checks,
                        &self.r_on_exit, &self.no_shortcut, &self.generic,
                        &self.receiver, &self.no_dispatch_dots, &self.per_param,
                        &&self.preconditions];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for TraitMethod {
    #[inline]
    fn clone(&self) -> Self {
        TraitMethod {
            inherited_signature: ::core::clone::Clone::clone(&self.inherited_signature),
            ident: ::core::clone::Clone::clone(&self.ident),
            sig: ::core::clone::Clone::clone(&self.sig),
            invisible: ::core::clone::Clone::clone(&self.invisible),
            has_self: ::core::clone::Clone::clone(&self.has_self),
            is_mut: ::core::clone::Clone::clone(&self.is_mut),
            coerce: ::core::clone::Clone::clone(&self.coerce),
            check_interrupt: ::core::clone::Clone::clone(&self.check_interrupt),
            rng: ::core::clone::Clone::clone(&self.rng),
            unwrap_in_r: ::core::clone::Clone::clone(&self.unwrap_in_r),
            serialize: ::core::clone::Clone::clone(&self.serialize),
            return_wrap: ::core::clone::Clone::clone(&self.return_wrap),
            param_defaults: ::core::clone::Clone::clone(&self.param_defaults),
            doc_tags: ::core::clone::Clone::clone(&self.doc_tags),
            skip: ::core::clone::Clone::clone(&self.skip),
            r_name: ::core::clone::Clone::clone(&self.r_name),
            strict: ::core::clone::Clone::clone(&self.strict),
            lifecycle: ::core::clone::Clone::clone(&self.lifecycle),
            r_entry: ::core::clone::Clone::clone(&self.r_entry),
            r_post_checks: ::core::clone::Clone::clone(&self.r_post_checks),
            r_on_exit: ::core::clone::Clone::clone(&self.r_on_exit),
            no_shortcut: ::core::clone::Clone::clone(&self.no_shortcut),
            generic: ::core::clone::Clone::clone(&self.generic),
            receiver: ::core::clone::Clone::clone(&self.receiver),
            no_dispatch_dots: ::core::clone::Clone::clone(&self.no_dispatch_dots),
            per_param: ::core::clone::Clone::clone(&self.per_param),
            preconditions: ::core::clone::Clone::clone(&self.preconditions),
        }
    }
}Clone)]
124struct TraitMethod {
125    /// Signature copied from declaration metadata: infer its argument types
126    /// from the real method so declaration-local aliases keep their identity.
127    inherited_signature: bool,
128    /// Rust method identifier (e.g., `value`, `increment`).
129    ident: syn::Ident,
130    /// Full method signature including self receiver and all parameters. A
131    /// return-visibility marker is already peeled (see `invisible`).
132    sig: syn::Signature,
133    /// Return-type visibility marker (#1213): `Some(true)` for
134    /// `-> Invisible<T>`, `Some(false)` for `-> Visible<T>`, stripped from
135    /// `sig.output`. The C wrapper unwraps the newtype before conversion.
136    invisible: Option<bool>,
137    /// Whether the method has a receiver (`&self`, `&mut self`).
138    /// False for static/associated methods.
139    has_self: bool,
140    /// Whether receiver is `&mut self` (vs `&self`). Only meaningful if `has_self` is true.
141    is_mut: bool,
142    /// Enable automatic type coercion for all parameters via `Rf_coerceVector`.
143    coerce: bool,
144    /// Check for R user interrupts (`R_CheckUserInterrupt`) before calling the method.
145    check_interrupt: bool,
146    /// Enable RNG state management (`GetRNGstate`/`PutRNGstate`) around the call.
147    rng: bool,
148    /// Return `Result<T, E>` to R without unwrapping -- R wrapper receives the result variant.
149    unwrap_in_r: bool,
150    /// Serialize the complete return value through `AsSerialize<T>`.
151    serialize: bool,
152    /// Explicit class-system return wrapping.
153    return_wrap: Option<crate::return_wrap::ReturnWrap>,
154    /// Parameter default values from `#[miniextendr(defaults(param = "value", ...))]`.
155    /// Keys are Rust names, values are R expressions used as default values;
156    /// the R wrapper keys them by formal (`Formals::rekey`).
157    param_defaults: std::collections::HashMap<String, String>,
158    /// The author's roxygen tags from the method's doc comment. The wrapper
159    /// generators forward the `@param` lines and the page tags (see
160    /// `r_wrappers::own_block_page`): a method-level `@rdname other` or
161    /// `@describeIn other ...` puts the method's own R wrapper block (S3
162    /// method, S4 `setMethod`, env/R6 namespace member, S7 shortcut, static
163    /// function) on that page instead of the type's shared `@rdname <Type>`
164    /// page, `@name` replaces the generated topic name, `@order` the generated
165    /// order, and `@inheritParams` / `@inherit` / `@inheritDotParams` fill the
166    /// arguments. Generics and consts stay on the type page.
167    doc_tags: Vec<String>,
168    /// When true, this method is excluded from C wrappers, R wrappers, and vtable shims.
169    /// The method is still kept in the emitted impl block (it's a real trait method).
170    skip: bool,
171    /// Override the R-facing method name. When set, the R wrapper uses this name
172    /// instead of the Rust method name (e.g., `next` -> `next_item` to avoid R reserved words).
173    r_name: Option<String>,
174    /// Strict output conversion: panic instead of lossy widening for i64/u64/isize/usize.
175    strict: bool,
176    /// Lifecycle specification for deprecation/experimental status.
177    lifecycle: Option<crate::lifecycle::LifecycleSpec>,
178    /// R code to inject at the very top of the wrapper body.
179    r_entry: Option<String>,
180    /// R code to inject after all checks, immediately before `.Call()`.
181    r_post_checks: Option<String>,
182    /// Register `on.exit()` cleanup code in the R wrapper.
183    r_on_exit: Option<crate::miniextendr_fn::ROnExit>,
184    /// Opt out of the per-class `<ClassName>_<method>` S7 fast-dispatch shortcut
185    /// (set via `#[miniextendr(s7(no_shortcut))]`). Only meaningful for S7 trait
186    /// impls; ignored by the other class systems.
187    no_shortcut: bool,
188    /// Existing S3/S4 generic and its receiver/formals contract.
189    generic: Option<String>,
190    receiver: Option<String>,
191    no_dispatch_dots: bool,
192    /// Per-parameter `#[miniextendr(match_arg(...))]` / `choices(...)` /
193    /// `several_ok` attributes, keyed by Rust parameter name. Mirrors
194    /// `MethodAttrs::per_param` on the inherent-impl path (`miniextendr_impl.rs`)
195    /// so trait methods get the same `match.arg()` validation prelude — see
196    /// `TraitMethodContext::match_arg_prelude`.
197    per_param: std::collections::HashMap<String, crate::miniextendr_fn::ParamAttrs>,
198    /// The method's own `preconditions` / `no_preconditions` (bare, #1017):
199    /// the type-derived R-side checks of the parameters that do not decide
200    /// for themselves (`preconditions(p)` / `no_preconditions(p)` land in
201    /// [`Self::per_param`]). `None` defers to the impl block.
202    preconditions: Option<bool>,
203}
204
205impl TraitMethod {
206    /// Returns the R-facing method name.
207    ///
208    /// Uses `r_name` override if set, otherwise falls back to the Rust identifier string.
209    fn r_method_name(&self) -> String {
210        self.r_name
211            .clone()
212            .unwrap_or_else(|| crate::naming::ident_name(&self.ident))
213    }
214
215    /// Generates the C wrapper function identifier: `C_{crate}_{Type}__{Trait}__{method}`.
216    ///
217    /// This is the symbol name registered with R via `R_CallMethodDef` for `.Call()` access.
218    /// Crate-prefixed for webR cross-package symbol uniqueness (#1273); shares one
219    /// formatter with `TraitConst` and with the string variant below so the shape
220    /// can't drift across the two types × two forms.
221    fn c_wrapper_ident(&self, type_ident: &syn::Ident, trait_name: &syn::Ident) -> syn::Ident {
222        crate::naming::trait_member_c_wrapper_ident(type_ident, trait_name, &self.ident)
223    }
224
225    /// Generates the C wrapper identifier as a `String`, for use in R-side `.Call()` generation.
226    ///
227    /// Prefer `c_wrapper_ident()` for Rust token generation; use this variant
228    /// when building R code strings (e.g., `".Call(C_crate_Type__Trait__method, ...)"`).
229    fn c_wrapper_ident_string(&self, type_ident: &syn::Ident, trait_name: &syn::Ident) -> String {
230        crate::naming::trait_member_c_wrapper_string(type_ident, trait_name, &self.ident)
231    }
232
233    /// Whether the R wrapper returns this method's value with `invisible()`
234    /// (#1213): set by an `Invisible<T>` return-type marker on the method.
235    /// Trait methods are visible by default, void ones included.
236    fn is_invisible(&self) -> bool {
237        self.invisible == Some(true)
238    }
239
240    /// Returns true if this method has no return type (returns unit `()`).
241    ///
242    /// Used to decide whether the R wrapper should hand back the receiver
243    /// (`x` / `self`) for void instance methods (pipe-friendly chaining).
244    fn returns_unit(&self) -> bool {
245        match &self.sig.output {
246            syn::ReturnType::Default => true,
247            syn::ReturnType::Type(_, ty) => {
248                #[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())
249            }
250        }
251    }
252
253    /// Returns true if this method returns `Self` (a factory/clone method).
254    ///
255    /// Mirrors [`crate::miniextendr_impl::ParsedMethod::returns_self`] on the
256    /// inherent-impl path. The C wrapper hands back a bare `ExternalPtr`
257    /// (`ReturnHandling::ExternalPtr`); the R wrapper must re-wrap it into a
258    /// classed object — see `TraitMethodContext::returns_self`.
259    fn returns_self(&self) -> bool {
260        #[allow(non_exhaustive_omitted_patterns)] match &self.sig.output {
    syn::ReturnType::Type(_, ty) if
        #[allow(non_exhaustive_omitted_patterns)] match ty.as_ref() {
            syn::Type::Path(p) if
                p.path.segments.last().map(|s|
                            s.ident == "Self").unwrap_or(false) => true,
            _ => false,
        } => true,
    _ => false,
}matches!(&self.sig.output, syn::ReturnType::Type(_, ty)
261            if matches!(ty.as_ref(), syn::Type::Path(p)
262                if p.path.segments.last().map(|s| s.ident == "Self").unwrap_or(false)))
263    }
264
265    /// Returns true if this method returns `Result<Self, E>`. Treated exactly
266    /// like a bare `Self` return on the R side (the C wrapper already raised on
267    /// `Err`, so `.val` is a bare `ExternalPtr`). Mirrors
268    /// [`crate::miniextendr_impl::ParsedMethod::returns_result_self`].
269    fn returns_result_self(&self) -> bool {
270        self.first_generic_arg_is_self("Result")
271    }
272
273    /// Returns true if this method returns `Option<Self>`. Treated exactly like
274    /// a bare `Self` return on the R side (the C wrapper already raised on
275    /// `None`). Mirrors
276    /// [`crate::miniextendr_impl::ParsedMethod::returns_option_self`].
277    fn returns_option_self(&self) -> bool {
278        self.first_generic_arg_is_self("Option")
279    }
280
281    /// Shared helper for [`Self::returns_result_self`] /
282    /// [`Self::returns_option_self`]: true when the return type is
283    /// `wrapper<Self, ..>` (e.g. `Result<Self, E>` / `Option<Self>`).
284    fn first_generic_arg_is_self(&self, wrapper: &str) -> bool {
285        let syn::ReturnType::Type(_, ty) = &self.sig.output else {
286            return false;
287        };
288        let syn::Type::Path(p) = ty.as_ref() else {
289            return false;
290        };
291        let Some(seg) = p.path.segments.last() else {
292            return false;
293        };
294        if seg.ident != wrapper {
295            return false;
296        }
297        let syn::PathArguments::AngleBracketed(ab) = &seg.arguments else {
298            return false;
299        };
300        #[allow(non_exhaustive_omitted_patterns)] match ab.args.first() {
    Some(syn::GenericArgument::Type(syn::Type::Path(ip))) if
        ip.path.segments.last().map(|s| s.ident == "Self").unwrap_or(false) =>
        true,
    _ => false,
}matches!(ab.args.first(), Some(syn::GenericArgument::Type(syn::Type::Path(ip)))
301            if ip.path.segments.last().map(|s| s.ident == "Self").unwrap_or(false))
302    }
303
304    /// Generates the `R_CallMethodDef` static identifier: `call_method_def_{Type}__{Trait}_{method}`.
305    ///
306    /// This constant holds the C function pointer and arity used by R's `.Call()` registration.
307    fn call_method_def_ident(
308        &self,
309        type_ident: &syn::Ident,
310        trait_name: &syn::Ident,
311    ) -> syn::Ident {
312        match ::quote::__private::IdentFragmentAdapter(&type_ident) {
    arg =>
        match ::quote::__private::IdentFragmentAdapter(&trait_name) {
            arg =>
                match ::quote::__private::IdentFragmentAdapter(&self.ident) {
                    arg =>
                        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("call_method_def_{0}__{1}_{2}",
                                                arg, arg, arg))
                                    }),
                            ::quote::__private::Option::None.or(arg.span()).or(arg.span()).or(arg.span())),
                },
        },
}format_ident!(
313            "call_method_def_{}__{}_{}",
314            type_ident,
315            trait_name,
316            self.ident
317        )
318    }
319}
320
321/// Parsed associated constant from a trait impl block.
322///
323/// Trait constants are exposed to R as zero-argument `.Call()` wrappers
324/// that simply return the constant value.
325#[derive(#[automatically_derived]impl ::core::fmt::Debug for TraitConst {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "TraitConst ident ty", &self.ident, &&self.ty)
    }
}Debug)]
326struct TraitConst {
327    /// Constant identifier (e.g., `MAX_SIZE`).
328    ident: syn::Ident,
329    /// Constant type (e.g., `i32`, `&str`). Used to determine SEXP conversion.
330    ty: syn::Type,
331}
332
333impl TraitConst {
334    /// Generates the C wrapper function identifier: `C_{crate}_{Type}__{Trait}__{CONST}`.
335    ///
336    /// This is the symbol name registered with R for `.Call()` access to the constant.
337    /// Crate-prefixed for webR cross-package symbol uniqueness (#1273); shares one
338    /// formatter with `TraitMethod` so the shape can't drift.
339    fn c_wrapper_ident(&self, type_ident: &syn::Ident, trait_name: &syn::Ident) -> syn::Ident {
340        crate::naming::trait_member_c_wrapper_ident(type_ident, trait_name, &self.ident)
341    }
342
343    /// Generates the C wrapper identifier as a `String`, for use in R-side `.Call()` generation.
344    fn c_wrapper_ident_string(&self, type_ident: &syn::Ident, trait_name: &syn::Ident) -> String {
345        crate::naming::trait_member_c_wrapper_string(type_ident, trait_name, &self.ident)
346    }
347
348    /// Generates the `R_CallMethodDef` static identifier: `call_method_def_{Type}__{Trait}_{CONST}`.
349    fn call_method_def_ident(
350        &self,
351        type_ident: &syn::Ident,
352        trait_name: &syn::Ident,
353    ) -> syn::Ident {
354        match ::quote::__private::IdentFragmentAdapter(&type_ident) {
    arg =>
        match ::quote::__private::IdentFragmentAdapter(&trait_name) {
            arg =>
                match ::quote::__private::IdentFragmentAdapter(&self.ident) {
                    arg =>
                        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("call_method_def_{0}__{1}_{2}",
                                                arg, arg, arg))
                                    }),
                            ::quote::__private::Option::None.or(arg.span()).or(arg.span()).or(arg.span())),
                },
        },
}format_ident!(
355            "call_method_def_{}__{}_{}",
356            type_ident,
357            trait_name,
358            self.ident
359        )
360    }
361}
362
363/// Expand `#[miniextendr]` applied to a trait implementation.
364///
365/// # Arguments
366///
367/// * `attr` - Attribute arguments (currently unused)
368/// * `item` - The impl block token stream
369///
370/// # Returns
371///
372/// Expanded token stream containing:
373/// - Original impl block
374/// - Vtable static constant
375///
376/// # Errors
377///
378/// Returns a compile error if:
379/// - Not applied to a trait impl (`impl Trait for Type`)
380/// - Applied to an inherent impl (`impl Type`)
381pub fn expand_miniextendr_impl_trait(
382    attr: proc_macro::TokenStream,
383    item: proc_macro::TokenStream,
384) -> proc_macro::TokenStream {
385    // Parse class system from attribute (defaults to Env if empty)
386    let attr_tokens = TokenStream::from(attr.clone());
387    let impl_attrs: ImplAttrs = match ::syn::parse::<ImplAttrs>(attr) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(attr as ImplAttrs);
388    let impl_item = match ::syn::parse::<ItemImpl>(item) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(item as ItemImpl);
389
390    // Validate: must be a trait impl, not inherent impl
391    let (trait_path, concrete_type) = match extract_trait_and_type(&impl_item) {
392        Ok(result) => result,
393        Err(e) => return e.into_compile_error().into(),
394    };
395
396    // TPIE: empty impl body → expand via macro_rules! helper from the trait definition
397    if impl_item.items.is_empty() && !impl_attrs.blanket {
398        // Only the `@noRd` flag and the `@param` warnings are read here; the
399        // page rule is `generate_vtable_static`'s (#1818).
400        let raw_tags = crate::roxygen::roxygen_tags_from_attrs(
401            &impl_item.attrs,
402            crate::roxygen::RdPage::suppressed_if(impl_attrs.noexport && !impl_attrs.internal),
403        );
404        let (doc_tags, param_warnings) = crate::roxygen::strip_method_tags(
405            &raw_tags,
406            &concrete_type.to_token_stream().to_string(),
407            impl_item.impl_token.span,
408        );
409        let no_rd = crate::roxygen::has_roxygen_tag(&doc_tags, "noRd");
410        let mut output = generate_tpie_invocation(
411            &trait_path,
412            &concrete_type,
413            impl_attrs.class_system,
414            no_rd,
415            impl_attrs.internal,
416            impl_attrs.noexport,
417            // The trait's signatures carry no method or parameter spellings,
418            // so the impl block, the crate default and the feature decide;
419            // the `macro_rules!` contract carries the decision as a bool.
420            !crate::r_preconditions::resolve_item_type_checks(
421                None,
422                impl_attrs.preconditions,
423                crate::crate_config::preconditions_default(),
424                falsecfg!(feature = "no-preconditions-default"),
425            ),
426        );
427        output.extend(param_warnings);
428        return output.into();
429    }
430
431    // Ask the declaration for its R metadata before generating wrappers.
432    // Rust imports/re-exports the metadata macro beside the trait itself.
433    let mut macro_path = trait_path;
434    macro_path.segments.last_mut().unwrap().arguments = syn::PathArguments::None;
435    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&macro_path, &mut _s);
    ::quote::__private::push_bang(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_at(&mut _s);
            ::quote::__private::push_ident(&mut _s, "impl");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::ToTokens::to_tokens(&attr_tokens, &mut _s);
                    _s
                });
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::ToTokens::to_tokens(&impl_item, &mut _s);
                    _s
                });
            _s
        });
    _s
}quote::quote! {
436        #macro_path! { @impl { #attr_tokens } { #impl_item } }
437    }
438    .into()
439}
440
441/// Extract the trait path and concrete type from an impl block.
442///
443/// For `impl path::Trait for concrete::Type`, returns:
444/// - trait_path: `path::Trait`
445/// - concrete_type: `concrete::Type`
446fn extract_trait_and_type(impl_item: &ItemImpl) -> syn::Result<(syn::Path, syn::Type)> {
447    // Check for trait impl
448    let (_, trait_path, _) = impl_item.trait_.as_ref().ok_or_else(|| {
449        syn::Error::new_spanned(
450            impl_item,
451            "#[miniextendr] must be applied to a trait implementation (impl Trait for Type), \
452             not an inherent impl (impl Type)",
453        )
454    })?;
455
456    let concrete_type = (*impl_item.self_ty).clone();
457
458    Ok((trait_path.clone(), concrete_type))
459}
460
461// region: Sub-modules
462
463mod defaults;
464mod method_context;
465mod r_wrappers;
466mod vtable;
467
468use r_wrappers::TraitWrapperOpts;
469use r_wrappers::generate_trait_r_wrapper;
470use vtable::generate_trait_method_c_wrapper;
471use vtable::generate_vtable_static;
472
473/// Generate R function body lines that capture the `.Call()` result in `.val`,
474/// check for a tagged `rust_condition_value`, and return `.val`.
475/// `raise_default` is the raise helper's fallback call
476/// (`CallAttribution::raise_default`).
477fn trait_method_body_lines(call_expr: &str, indent: &str, raise_default: &str) -> Vec<String> {
478    let mut lines = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("{0}.val <- {1}", indent,
                                call_expr))
                    })]))vec![format!("{}.val <- {}", indent, call_expr)];
479    lines.extend(
480        crate::method_return_builder::condition_check_lines_with_default(indent, raise_default),
481    );
482    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.val", indent))
    })format!("{}.val", indent));
483    lines
484}
485
486/// Convert a type to a case-preserving identifier-safe name.
487///
488/// For non-generic types, the name is the last path segment with its spelling preserved:
489/// - `MyType` → `MyType`
490/// - `path::to::MyType` → `MyType`
491///
492/// For generic types, a 16-character lowercase hex suffix derived from a stable
493/// FNV-1a-64 hash of the full canonical token stream is appended:
494/// - `MyType<u32>` → `MyType_a1b2c3d4e5f60718`
495/// - `MyType<f64>` → `MyType_0102030405060708` (different hash → no collision)
496///
497/// This prevents vtable static name collisions when the same base type is
498/// monomorphised with different generic arguments in the same crate.
499///
500/// **Hash stability:** FNV-1a-64 with a fixed seed (offset basis = 0xcbf29ce484222325)
501/// is deterministic across builds, rustc versions, and platforms.  We deliberately
502/// avoid `std::collections::hash_map::DefaultHasher` and `RandomState` because both
503/// are explicitly unspecified and can change across releases.
504fn type_to_symbol_name(ty: &syn::Type) -> String {
505    /// FNV-1a 64-bit hash of a byte slice.
506    ///
507    /// Chosen for simplicity (≈10 lines, no new deps) and cross-build stability.
508    /// The FNV offset basis and prime are fixed constants defined in the FNV spec.
509    fn fnv1a_64(data: &[u8]) -> u64 {
510        const OFFSET_BASIS: u64 = 0xcbf29ce484222325;
511        const PRIME: u64 = 0x00000100000001b3;
512        let mut h = OFFSET_BASIS;
513        for &b in data {
514            h ^= b as u64;
515            h = h.wrapping_mul(PRIME);
516        }
517        h
518    }
519
520    match ty {
521        syn::Type::Path(type_path) => {
522            let last = type_path.path.segments.last();
523            let base = last
524                .map(|s| crate::naming::ident_name(&s.ident))
525                .unwrap_or_else(|| "UNKNOWN".to_string());
526
527            // Only append a hash suffix when the type actually carries generic arguments
528            // (e.g. `MyType<u32>`). Plain `MyType` keeps the clean `MyType` form.
529            let has_generics = last
530                .map(|s| !#[allow(non_exhaustive_omitted_patterns)] match s.arguments {
    syn::PathArguments::None => true,
    _ => false,
}matches!(s.arguments, syn::PathArguments::None))
531                .unwrap_or(false);
532
533            if has_generics {
534                // Canonical token string of the *full* type (including all generic args)
535                // so that `MyType<u32>` and `MyType<f64>` produce distinct hashes.
536                let token_str = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&ty, &mut _s);
    _s
}quote::quote!(#ty).to_string();
537                let hash = fnv1a_64(token_str.as_bytes());
538                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}_{1:016x}", base, hash))
    })format!("{}_{:016x}", base, hash)
539            } else {
540                base
541            }
542        }
543        _ => "UNKNOWN".to_string(),
544    }
545}
546// endregion
547
548// region: TPIE: Trait-Provided Impl Expansion
549
550/// The declaration's ABI layout and tag, carried through its metadata macro.
551/// An impl must not reconstruct these from an imported or re-exported path.
552struct TraitAbiMetadata {
553    name: syn::Ident,
554    generic: bool,
555    tag: syn::LitStr,
556    fields: syn::FieldsNamed,
557}
558
559impl syn::parse::Parse for TraitAbiMetadata {
560    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
561        let keyword: syn::Ident = input.parse()?;
562        if keyword != "abi" {
563            return Err(syn::Error::new_spanned(
564                keyword,
565                "expected trait ABI metadata",
566            ));
567        }
568        Ok(Self {
569            name: input.parse()?,
570            generic: input.parse::<syn::LitBool>()?.value,
571            tag: input.parse()?,
572            fields: input.parse()?,
573        })
574    }
575}
576
577/// Populated impl plus declaration metadata, supplied by the trait's macro.
578/// Keep this as Rust syntax so method bodies, generics and author attributes
579/// pass through without a second bespoke representation.
580struct ImplWithMetadata {
581    attrs: ImplAttrs,
582    implementation: ItemImpl,
583    methods: Vec<syn::TraitItemFn>,
584    generics: syn::Generics,
585    abi: TraitAbiMetadata,
586}
587
588impl syn::parse::Parse for ImplWithMetadata {
589    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
590        input.parse::<::syn::token::Atsyn::Token![@]>()?;
591        input.parse::<::syn::token::Implsyn::Token![impl]>()?;
592        let attrs;
593        match ::syn::__private::parse_braces(&input) {
    ::syn::__private::Ok(braces) => {
        attrs = braces.content;
        _ = attrs;
        braces.token
    }
    ::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
};syn::braced!(attrs in input);
594        let attrs = attrs.parse()?;
595        let implementation;
596        match ::syn::__private::parse_braces(&input) {
    ::syn::__private::Ok(braces) => {
        implementation = braces.content;
        _ = implementation;
        braces.token
    }
    ::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
};syn::braced!(implementation in input);
597        let implementation = implementation.parse()?;
598        let metadata;
599        match ::syn::__private::parse_braces(&input) {
    ::syn::__private::Ok(braces) => {
        metadata = braces.content;
        _ = metadata;
        braces.token
    }
    ::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
};syn::braced!(metadata in input);
600        let mut methods = Vec::new();
601        while !metadata.is_empty() {
602            methods.push(metadata.parse()?);
603        }
604        let generics;
605        match ::syn::__private::parse_braces(&input) {
    ::syn::__private::Ok(braces) => {
        generics = braces.content;
        _ = generics;
        braces.token
    }
    ::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
};syn::braced!(generics in input);
606        Ok(Self {
607            attrs,
608            implementation,
609            methods,
610            generics: generics.parse()?,
611            abi: input.parse()?,
612        })
613    }
614}
615
616impl ImplWithMetadata {
617    fn expand(mut self) -> syn::Result<TokenStream> {
618        vtable::inherit_method_metadata(&mut self.implementation, &self.methods)?;
619        let (trait_path, concrete_type) = extract_trait_and_type(&self.implementation)?;
620        let defaults = defaults::inherited_methods(
621            &self.implementation,
622            &self.methods,
623            &self.generics,
624            &trait_path,
625        )?;
626        Ok(generate_vtable_static(
627            &self.implementation,
628            &trait_path,
629            &concrete_type,
630            &self.attrs,
631            &self.abi,
632            &self.methods,
633            &defaults,
634        ))
635    }
636}
637
638/// Input to the `__mx_trait_impl_expand!` proc macro.
639///
640/// TPIE (Trait-Provided Impl Expansion) allows empty `#[miniextendr] impl Trait for Type {}`
641/// blocks to auto-expand C/R wrappers using metadata embedded in a `macro_rules!` helper
642/// generated at the trait definition site.
643///
644/// Parsed from tokens like:
645/// ```text
646/// concrete_type = Point;
647/// trait_path = miniextendr_api::adapter_traits::RDebug;
648/// class_system = env;
649/// no_rd = false;
650/// internal = false;
651/// noexport = false;
652/// no_preconditions = false;
653/// abi RDebug false "<declaration fingerprint>" {
654///     pub debug_str: ::miniextendr_api::abi::mx_meth,
655///     pub debug_str_pretty: ::miniextendr_api::abi::mx_meth,
656/// }
657/// method { r_name = debug_str; #[doc = " Get a compact debug string representation."] fn debug_str(&self) -> String; }
658/// method { r_name = debug_str_pretty; fn debug_str_pretty(&self) -> String; }
659/// ```
660struct TpieInput {
661    /// The concrete type implementing the trait (e.g., `Point`).
662    concrete_type: syn::Type,
663    /// Fully qualified path to the trait (e.g., `miniextendr_api::adapter_traits::RDebug`).
664    trait_path: syn::Path,
665    /// Which R class system to generate wrappers for (env, r6, s3, s4, s7).
666    class_system: ClassSystem,
667    /// Whether the impl block has `@noRd`, suppressing roxygen documentation.
668    no_rd: bool,
669    /// Whether the impl block has `#[miniextendr(internal)]`, adding `@keywords internal`.
670    internal: bool,
671    /// Whether the impl block has `#[miniextendr(noexport)]`, suppressing `@export`.
672    noexport: bool,
673    /// Whether the impl block drops the R-side type checks: its
674    /// `ImplAttrs::preconditions`, the crate default and the
675    /// `no-preconditions-default` feature, resolved in the implementing crate
676    /// when the empty impl invoked the trait's `macro_rules!` helper.
677    no_preconditions: bool,
678    /// Method signatures and R-facing names from the trait definition.
679    methods: Vec<TpieMethod>,
680    abi: TraitAbiMetadata,
681}
682
683/// A single method entry in TPIE metadata.
684///
685/// Contains the R-facing name, the declaration's docs and the method
686/// signature as declared in the trait.
687struct TpieMethod {
688    /// The R-facing method name (may differ from the Rust ident via `r_name`).
689    r_name: String,
690    /// The declaration's `#[doc]` attributes, which document the method's
691    /// wrappers.
692    docs: Vec<syn::Attribute>,
693    /// The method signature (parameters and return type) from the trait definition.
694    sig: syn::Signature,
695}
696
697impl syn::parse::Parse for TpieInput {
698    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
699        // concrete_type = Type;
700        let kw: syn::Ident = input.parse()?;
701        if kw != "concrete_type" {
702            return Err(syn::Error::new_spanned(
703                &kw,
704                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected \'concrete_type\', got \'{0}\'",
                kw))
    })format!("expected 'concrete_type', got '{}'", kw),
705            ));
706        }
707        input.parse::<::syn::token::Eqsyn::Token![=]>()?;
708        let concrete_type: syn::Type = input.parse()?;
709        input.parse::<::syn::token::Semisyn::Token![;]>()?;
710
711        // trait_path = some::Path;
712        let kw: syn::Ident = input.parse()?;
713        if kw != "trait_path" {
714            return Err(syn::Error::new_spanned(
715                &kw,
716                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected \'trait_path\', got \'{0}\'",
                kw))
    })format!("expected 'trait_path', got '{}'", kw),
717            ));
718        }
719        input.parse::<::syn::token::Eqsyn::Token![=]>()?;
720        let trait_path: syn::Path = input.parse()?;
721        input.parse::<::syn::token::Semisyn::Token![;]>()?;
722
723        // class_system = env;
724        let kw: syn::Ident = input.parse()?;
725        if kw != "class_system" {
726            return Err(syn::Error::new_spanned(
727                &kw,
728                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected \'class_system\', got \'{0}\'",
                kw))
    })format!("expected 'class_system', got '{}'", kw),
729            ));
730        }
731        input.parse::<::syn::token::Eqsyn::Token![=]>()?;
732        let cs_ident: syn::Ident = input.parse()?;
733        input.parse::<::syn::token::Semisyn::Token![;]>()?;
734
735        let class_system = ClassSystem::from_ident(&cs_ident).ok_or_else(|| {
736            syn::Error::new_spanned(&cs_ident, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown class system: {0}",
                cs_ident))
    })format!("unknown class system: {}", cs_ident))
737        })?;
738
739        // no_rd = true/false;
740        let kw: syn::Ident = input.parse()?;
741        if kw != "no_rd" {
742            return Err(syn::Error::new_spanned(
743                &kw,
744                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected \'no_rd\', got \'{0}\'",
                kw))
    })format!("expected 'no_rd', got '{}'", kw),
745            ));
746        }
747        input.parse::<::syn::token::Eqsyn::Token![=]>()?;
748        let no_rd_lit: syn::LitBool = input.parse()?;
749        input.parse::<::syn::token::Semisyn::Token![;]>()?;
750        let no_rd = no_rd_lit.value;
751
752        // internal = true/false;
753        let kw: syn::Ident = input.parse()?;
754        if kw != "internal" {
755            return Err(syn::Error::new_spanned(
756                &kw,
757                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected \'internal\', got \'{0}\'",
                kw))
    })format!("expected 'internal', got '{}'", kw),
758            ));
759        }
760        input.parse::<::syn::token::Eqsyn::Token![=]>()?;
761        let internal_lit: syn::LitBool = input.parse()?;
762        input.parse::<::syn::token::Semisyn::Token![;]>()?;
763        let internal = internal_lit.value;
764
765        // noexport = true/false;
766        let kw: syn::Ident = input.parse()?;
767        if kw != "noexport" {
768            return Err(syn::Error::new_spanned(
769                &kw,
770                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected \'noexport\', got \'{0}\'",
                kw))
    })format!("expected 'noexport', got '{}'", kw),
771            ));
772        }
773        input.parse::<::syn::token::Eqsyn::Token![=]>()?;
774        let noexport_lit: syn::LitBool = input.parse()?;
775        input.parse::<::syn::token::Semisyn::Token![;]>()?;
776        let noexport = noexport_lit.value;
777
778        // no_preconditions = true/false;
779        let kw: syn::Ident = input.parse()?;
780        if kw != "no_preconditions" {
781            return Err(syn::Error::new_spanned(
782                &kw,
783                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected \'no_preconditions\', got \'{0}\'",
                kw))
    })format!("expected 'no_preconditions', got '{}'", kw),
784            ));
785        }
786        input.parse::<::syn::token::Eqsyn::Token![=]>()?;
787        let no_preconditions_lit: syn::LitBool = input.parse()?;
788        input.parse::<::syn::token::Semisyn::Token![;]>()?;
789        let no_preconditions = no_preconditions_lit.value;
790
791        let abi = input.parse()?;
792
793        // method { ... } repeated
794        let mut methods = Vec::new();
795        while !input.is_empty() {
796            let kw: syn::Ident = input.parse()?;
797            if kw != "method" {
798                return Err(syn::Error::new_spanned(
799                    &kw,
800                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected \'method\', got \'{0}\'",
                kw))
    })format!("expected 'method', got '{}'", kw),
801                ));
802            }
803            let content;
804            match ::syn::__private::parse_braces(&input) {
    ::syn::__private::Ok(braces) => {
        content = braces.content;
        _ = content;
        braces.token
    }
    ::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
};syn::braced!(content in input);
805            methods.push(content.parse::<TpieMethod>()?);
806        }
807
808        Ok(TpieInput {
809            concrete_type,
810            trait_path,
811            class_system,
812            no_rd,
813            internal,
814            noexport,
815            no_preconditions,
816            methods,
817            abi,
818        })
819    }
820}
821
822impl syn::parse::Parse for TpieMethod {
823    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
824        // r_name = some_name;
825        let kw: syn::Ident = input.parse()?;
826        if kw != "r_name" {
827            return Err(syn::Error::new_spanned(
828                &kw,
829                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected \'r_name\', got \'{0}\'",
                kw))
    })format!("expected 'r_name', got '{}'", kw),
830            ));
831        }
832        input.parse::<::syn::token::Eqsyn::Token![=]>()?;
833        let r_name_ident: syn::Ident = input.parse()?;
834        input.parse::<::syn::token::Semisyn::Token![;]>()?;
835
836        // #[doc = "..."]* fn method_name(...) -> ReturnType;
837        let docs = syn::Attribute::parse_outer(input)?;
838        let sig: syn::Signature = input.parse()?;
839        input.parse::<::syn::token::Semisyn::Token![;]>()?;
840
841        Ok(TpieMethod {
842            r_name: crate::naming::ident_name(&r_name_ident),
843            docs,
844            sig,
845        })
846    }
847}
848
849/// Rewrite `Self` → concrete type in a method signature's parameters.
850///
851/// `&Self` params are left as-is because `generate_trait_method_c_wrapper`
852/// detects them via `type_inspect::self_ref_mutability` and generates `ExternalPtr<T>` extraction.
853///
854/// The return type keeps `Self`, as in a trait impl with method bodies: the
855/// C wrapper hands a `Self` / `Option<Self>` / `Result<Self, E>` back as an
856/// `ExternalPtr` without naming the type, and the R wrapper re-wraps exactly
857/// those returns into an object of the class (`TraitMethod::returns_self` and
858/// its siblings look for `Self`).
859fn rewrite_self_in_params(sig: &mut syn::Signature, concrete_type: &syn::Type) {
860    for input in &mut sig.inputs {
861        if let syn::FnArg::Typed(pt) = input {
862            // Don't rewrite &Self — C wrapper generator handles it specially
863            if crate::type_inspect::self_ref_mutability(&pt.ty).is_some() {
864                continue;
865            }
866            let rewritten = rewrite_self_type(&pt.ty, concrete_type);
867            *pt.ty = rewritten;
868        }
869    }
870}
871
872/// Recursively replace `Self` with the concrete type in a type tree.
873fn rewrite_self_type(ty: &syn::Type, concrete_type: &syn::Type) -> syn::Type {
874    match ty {
875        syn::Type::Path(tp) => {
876            if tp.path.is_ident("Self") {
877                return concrete_type.clone();
878            }
879            let mut new_tp = tp.clone();
880            for seg in &mut new_tp.path.segments {
881                if let syn::PathArguments::AngleBracketed(args) = &mut seg.arguments {
882                    for arg in &mut args.args {
883                        if let syn::GenericArgument::Type(inner) = arg {
884                            *inner = rewrite_self_type(inner, concrete_type);
885                        }
886                    }
887                }
888            }
889            syn::Type::Path(new_tp)
890        }
891        syn::Type::Reference(r) => {
892            let mut new_r = r.clone();
893            new_r.elem = Box::new(rewrite_self_type(&r.elem, concrete_type));
894            syn::Type::Reference(new_r)
895        }
896        syn::Type::Tuple(t) => {
897            let mut new_t = t.clone();
898            for elem in &mut new_t.elems {
899                *elem = rewrite_self_type(elem, concrete_type);
900            }
901            syn::Type::Tuple(new_t)
902        }
903        _ => ty.clone(),
904    }
905}
906
907/// Unwrap invisible Group tokens from `macro_rules!` `$t:ty` captures.
908///
909/// When a type passes through a `macro_rules!` pattern like `$concrete_type:ty`,
910/// the compiler wraps it in a `Group` with invisible delimiters. This function
911/// recursively unwraps those groups to get the underlying type.
912fn unwrap_group_type(ty: &syn::Type) -> syn::Type {
913    match ty {
914        syn::Type::Group(g) => unwrap_group_type(&g.elem),
915        _ => ty.clone(),
916    }
917}
918
919/// Entry point for the `__mx_trait_impl_expand!` proc macro.
920///
921/// Parses TPIE metadata tokens and generates C wrappers, R wrappers,
922/// and call defs — the same outputs as a manual trait impl with method bodies.
923pub fn expand_tpie(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
924    if #[allow(non_exhaustive_omitted_patterns)] match input.clone().into_iter().next()
    {
    Some(proc_macro::TokenTree::Punct(p)) if p.as_char() == '@' => true,
    _ => false,
}matches!(input.clone().into_iter().next(), Some(proc_macro::TokenTree::Punct(p)) if p.as_char() == '@')
925    {
926        let metadata = match ::syn::parse::<ImplWithMetadata>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as ImplWithMetadata);
927        return metadata
928            .expand()
929            .unwrap_or_else(syn::Error::into_compile_error)
930            .into();
931    }
932    let tpie_input = match ::syn::parse::<TpieInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as TpieInput);
933
934    // Unwrap Group tokens (macro_rules! wraps $concrete_type:ty and $trait_path:path
935    // in invisible groups)
936    let concrete_type = unwrap_group_type(&tpie_input.concrete_type);
937    let trait_path = &tpie_input.trait_path;
938    let class_system = tpie_input.class_system;
939
940    let trait_name = &tpie_input.abi.name;
941
942    let type_ident = match &concrete_type {
943        syn::Type::Path(tp) => tp
944            .path
945            .segments
946            .last()
947            .map(|s| s.ident.clone())
948            .unwrap_or_else(|| ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("Unknown"))
            }), ::quote::__private::Option::None)format_ident!("Unknown")),
949        _ => ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("Unknown"))
            }), ::quote::__private::Option::None)format_ident!("Unknown"),
950    };
951
952    // Convert TpieMethod → TraitMethod, rewriting Self → ConcreteType
953    let methods: Vec<TraitMethod> = tpie_input
954        .methods
955        .iter()
956        .map(|tm| {
957            let mut sig = tm.sig.clone();
958            rewrite_self_in_params(&mut sig, &concrete_type);
959
960            let (has_self, is_mut) = sig.inputs.first().map_or((false, false), |arg| {
961                if let syn::FnArg::Receiver(_) = arg {
962                    (true, crate::trait_receiver::is_mut(&sig))
963                } else {
964                    (false, false)
965                }
966            });
967
968            // Peel a return-visibility marker (#1213) so the return-shape
969            // predicates and the C wrapper see the inner type.
970            let (invisible, sig) = {
971                let (marker, output) = crate::type_inspect::peel_return_visibility(&sig.output);
972                let mut sig = sig;
973                sig.output = output;
974                (marker, sig)
975            };
976            TraitMethod {
977                inherited_signature: true,
978                ident: sig.ident.clone(),
979                sig,
980                invisible,
981                has_self,
982                is_mut,
983                coerce: false,
984                check_interrupt: false,
985                rng: false,
986                unwrap_in_r: false,
987                serialize: false,
988                return_wrap: None,
989                param_defaults: Default::default(),
990                // The declaration's docs, as for an inherited default.
991                doc_tags: crate::roxygen::declaration_roxygen_tags(&tm.docs),
992                skip: false,
993                strict: false,
994                lifecycle: None,
995                r_entry: None,
996                r_post_checks: None,
997                r_on_exit: None,
998                no_shortcut: false,
999                generic: None,
1000                receiver: None,
1001                no_dispatch_dots: false,
1002                per_param: Default::default(),
1003                preconditions: None,
1004                r_name: if tm.sig.ident == tm.r_name {
1005                    None // r_name matches ident → no override
1006                } else {
1007                    Some(tm.r_name.clone())
1008                },
1009            }
1010        })
1011        .collect();
1012
1013    // Generate C wrappers
1014    let c_wrappers: Vec<TokenStream> = methods
1015        .iter()
1016        .map(|m| generate_trait_method_c_wrapper(m, &type_ident, trait_name, trait_path))
1017        .collect();
1018
1019    // Generate R wrappers
1020    let r_wrapper_string = match generate_trait_r_wrapper(
1021        &type_ident,
1022        trait_name,
1023        &methods,
1024        &[], // no consts in TPIE
1025        TraitWrapperOpts {
1026            class_system,
1027            class_has_no_rd: tpie_input.no_rd,
1028            internal: tpie_input.internal,
1029            noexport: tpie_input.noexport,
1030            impl_preconditions: Some(!tpie_input.no_preconditions),
1031        },
1032    ) {
1033        Ok(s) => s,
1034        Err(e) => return e.into_compile_error().into(),
1035    };
1036
1037    // Generate const names (same pattern as generate_vtable_static)
1038    let type_name_str = type_to_symbol_name(&concrete_type);
1039    let r_wrappers_const = crate::naming::trait_impl_wrappers_ident(&type_name_str, trait_name);
1040
1041    // Generate trait dispatch entry name
1042    let dispatch_entry_name = crate::naming::trait_dispatch_ident(trait_name, &type_name_str);
1043
1044    let trait_tag = &tpie_input.abi.tag;
1045
1046    // Build vtable static name (same as generate_vtable_static — routed through
1047    // the shared naming.rs helper so the three reconstruction sites can't drift, #1273)
1048    let vtable_static_name = crate::naming::vtable_static_ident(trait_name, &type_name_str);
1049
1050    let vtable = match vtable::generate_impl_vtable(
1051        &tpie_input.abi,
1052        &concrete_type,
1053        trait_path,
1054        &methods,
1055        &[],
1056    ) {
1057        Ok(tokens) => tokens,
1058        Err(error) => return error.into_compile_error().into(),
1059    };
1060
1061    // Format R wrapper as raw string literal
1062    let r_wrapper_str = crate::r_wrapper_raw_literal(
1063        &r_wrapper_string,
1064        &crate::r_shadowing::formal_names(
1065            methods.iter().map(|m| (&m.sig.inputs, Default::default())),
1066        ),
1067    );
1068    let source_start = type_ident.span().start();
1069    let source_line_lit = syn::LitInt::new(&source_start.line.to_string(), type_ident.span());
1070    let source_col_lit =
1071        syn::LitInt::new(&(source_start.column + 1).to_string(), type_ident.span());
1072
1073    let expanded = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&vtable, &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_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::__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! {
1074        #vtable
1075        // C wrappers and call method defs for trait methods
1076        #(#c_wrappers)*
1077
1078        // R wrapper registration via distributed slice
1079        #[doc(hidden)]
1080        #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_R_WRAPPERS), linkme(crate = ::miniextendr_api::linkme))]
1081        #[allow(non_upper_case_globals)]
1082        static #r_wrappers_const: ::miniextendr_api::registry::RWrapperEntry =
1083            ::miniextendr_api::registry::RWrapperEntry {
1084                priority: ::miniextendr_api::registry::RWrapperPriority::TraitImpl,
1085                source_file: ::core::file!(),
1086                source_line: #source_line_lit,
1087                content: ::core::concat!(
1088                    "# Generated from Rust impl `",
1089                    ::core::stringify!(#trait_name),
1090                    "` for `",
1091                    ::core::stringify!(#type_ident),
1092                    "` (",
1093                    ::core::file!(),
1094                    ":",
1095                    #source_line_lit,
1096                    ":",
1097                    #source_col_lit,
1098                    ")",
1099                    #r_wrapper_str
1100                ),
1101            };
1102
1103        // Trait dispatch entry for universal_query
1104        #[doc(hidden)]
1105        #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_TRAIT_DISPATCH), linkme(crate = ::miniextendr_api::linkme))]
1106        #[allow(non_upper_case_globals)]
1107        static #dispatch_entry_name: ::miniextendr_api::registry::TraitDispatchEntry =
1108            ::miniextendr_api::registry::TraitDispatchEntry {
1109                concrete_tag: ::miniextendr_api::abi::mx_tag_from_path(
1110                    ::core::concat!(::core::module_path!(), "::", ::core::stringify!(#type_ident))
1111                ),
1112                trait_tag: ::miniextendr_api::abi::mx_tag_from_path(#trait_tag),
1113                vtable: unsafe {
1114                    ::std::ptr::from_ref(&#vtable_static_name).cast::<::std::os::raw::c_void>()
1115                },
1116                vtable_symbol: ::core::stringify!(#vtable_static_name),
1117            };
1118    };
1119
1120    expanded.into()
1121}
1122
1123/// Request declaration metadata for an empty trait impl.
1124///
1125/// When `#[miniextendr] impl Trait for Type {}` has no method bodies, this
1126/// delegates to the trait's metadata macro
1127/// (generated at the trait definition site) to expand C/R wrappers.
1128fn generate_tpie_invocation(
1129    trait_path: &syn::Path,
1130    concrete_type: &syn::Type,
1131    class_system: ClassSystem,
1132    class_has_no_rd: bool,
1133    internal: bool,
1134    noexport: bool,
1135    no_preconditions: bool,
1136) -> TokenStream {
1137    // Resolve metadata through the same path as the trait. The declaration
1138    // exports both in separate Rust namespaces.
1139    let mut macro_path = trait_path.clone();
1140    macro_path.segments.last_mut().unwrap().arguments = syn::PathArguments::None;
1141    let class_system_ident = class_system.to_ident();
1142    let no_rd_ident = if class_has_no_rd {
1143        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("true"))
            }), ::quote::__private::Option::None)format_ident!("true")
1144    } else {
1145        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("false"))
            }), ::quote::__private::Option::None)format_ident!("false")
1146    };
1147    let internal_ident = if internal {
1148        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("true"))
            }), ::quote::__private::Option::None)format_ident!("true")
1149    } else {
1150        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("false"))
            }), ::quote::__private::Option::None)format_ident!("false")
1151    };
1152    let noexport_ident = if noexport {
1153        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("true"))
            }), ::quote::__private::Option::None)format_ident!("true")
1154    } else {
1155        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("false"))
            }), ::quote::__private::Option::None)format_ident!("false")
1156    };
1157    let no_preconditions_ident = if no_preconditions {
1158        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("true"))
            }), ::quote::__private::Option::None)format_ident!("true")
1159    } else {
1160        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("false"))
            }), ::quote::__private::Option::None)format_ident!("false")
1161    };
1162
1163    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&macro_path, &mut _s);
    ::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);
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&trait_path, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&class_system_ident, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&no_rd_ident, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&internal_ident, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&noexport_ident, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&no_preconditions_ident, &mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
1164        #macro_path !(#concrete_type, #trait_path, #class_system_ident, #no_rd_ident, #internal_ident, #noexport_ident, #no_preconditions_ident);
1165    }
1166}
1167
1168#[cfg(test)]
1169mod tests;
1170// endregion