Skip to main content

miniextendr_macros/
miniextendr_impl.rs

1//! # Impl-block Parsing and Wrapper Generation
2//!
3//! This module handles `#[miniextendr]` applied to inherent impl blocks,
4//! generating R wrappers for different class systems.
5//!
6//! ## Architecture Overview
7//!
8//! ```text
9//! ┌─────────────────────────────────────────────────────────────────────────┐
10//! │                         #[miniextendr(r6)]                              │
11//! │                         impl MyType { ... }                             │
12//! └─────────────────────────────────────────────────────────────────────────┘
13//!                                    │
14//!                                    ▼
15//! ┌─────────────────────────────────────────────────────────────────────────┐
16//! │                           PARSING PHASE                                 │
17//! │  ┌─────────────────┐    ┌─────────────────┐    ┌─────────────────────┐ │
18//! │  │   ImplAttrs     │    │  ParsedMethod   │    │    ParsedImpl       │ │
19//! │  │ - class_system  │    │ - ident         │───▶│ - type_ident        │ │
20//! │  │ - class_name    │    │ - receiver      │    │ - class_system      │ │
21//! │  └─────────────────┘    │ - sig           │    │ - methods[]         │ │
22//! │                         │ - doc_tags      │    │ - doc_tags          │ │
23//! │                         │ - method_attrs  │    └─────────────────────┘ │
24//! │                         └─────────────────┘                             │
25//! └─────────────────────────────────────────────────────────────────────────┘
26//!                                    │
27//!                                    ▼
28//! ┌─────────────────────────────────────────────────────────────────────────┐
29//! │                        CODE GENERATION PHASE                            │
30//! │                                                                         │
31//! │  For each method:                                                       │
32//! │  ┌─────────────────────────────────────────────────────────────────┐   │
33//! │  │ generate_c_wrapper_for_method()                                 │   │
34//! │  │   └─▶ CWrapperContext (shared builder from c_wrapper_builder)   │   │
35//! │  │         - SEXP→Rust conversion                                  │   │
36//! │  │         - return handling                                       │   │
37//! │  └─────────────────────────────────────────────────────────────────┘   │
38//! │                                                                         │
39//! │  For the whole impl:                                                    │
40//! │  ┌─────────────────────────────────────────────────────────────────┐   │
41//! │  │ generate_{class_system}_r_wrapper()                             │   │
42//! │  │   - generate_env_r_wrapper()   → Type$method(self, ...)         │   │
43//! │  │   - generate_r6_r_wrapper()    → R6Class with methods           │   │
44//! │  │   - generate_s3_r_wrapper()    → generic + method.Type          │   │
45//! │  │   - generate_s4_r_wrapper()    → setClass + setMethod           │   │
46//! │  │   - generate_s7_r_wrapper()    → new_class + method<-           │   │
47//! │  └─────────────────────────────────────────────────────────────────┘   │
48//! └─────────────────────────────────────────────────────────────────────────┘
49//!                                    │
50//!                                    ▼
51//! ┌─────────────────────────────────────────────────────────────────────────┐
52//! │                              OUTPUTS                                    │
53//! │  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────────────┐ │
54//! │  │ C wrapper fns   │  │ R wrapper code  │  │  R_CallMethodDef       │ │
55//! │  │ C_*_Type__method│  │ (as const str)  │  │  registration entries  │ │
56//! │  └─────────────────┘  └─────────────────┘  └─────────────────────────┘ │
57//! └─────────────────────────────────────────────────────────────────────────┘
58//! ```
59//!
60//! ## Supported Class Systems
61//!
62//! | System | Syntax | R Pattern | Use Case |
63//! |--------|--------|-----------|----------|
64//! | **Env** | `#[miniextendr]` | `obj$method()` | Simple, environment-based dispatch |
65//! | **R6** | `#[miniextendr(r6)]` | `R6Class` with `$new()` | OOP with encapsulation |
66//! | **S3** | `#[miniextendr(s3)]` | `generic(obj)` dispatch | Idiomatic R generics |
67//! | **S4** | `#[miniextendr(s4)]` | `setClass`/`setMethod` | Formal OOP, multiple dispatch |
68//! | **S7** | `#[miniextendr(s7)]` | `new_class`/`new_generic` | Modern R OOP |
69//! | **vctrs** | `#[miniextendr(vctrs)]` | `new_vctr`/`new_rcrd`/`new_list_of` | vctrs-compatible vectors |
70//!
71//! ## Method Categorization
72//!
73//! Methods are categorized by their receiver type:
74//!
75//! | Receiver | [`ReceiverKind`] | Generated as |
76//! |----------|------------------|--------------|
77//! | `&self` | `Ref` | Instance method (immutable) |
78//! | `&mut self` | `RefMut` | Instance method (mutable, chainable) |
79//! | `self: ExternalPtrRef<'_, Self>` | `ExternalPtrRef` | Instance method (immutable, with the R object: sidecar fields) |
80//! | `self: ExternalPtrMut<'_, Self>` | `ExternalPtrMut` | Instance method (mutable, with the R object: sidecar fields) |
81//! | `self: ExternalPtr<Self>` | `ExternalPtrValue` | Instance method (the handle itself, unborrowed) |
82//! | `self` | `Value` | Consuming method: `-> Self` writes the result back into the same handle; `-> Result<Self, E>` / `Option<Self>` run on a clone (`T: Clone`) and overwrite on success; any other return consumes the handle (later use errors) |
83//! | (none) | `None` | Static method or constructor |
84//!
85//! Special methods:
86//! - **Constructor**: Returns `Self` with no receiver, marked with `#[miniextendr(constructor)]` or named `new`
87//! - **Finalizer**: R6 only, marked with `#[miniextendr(r6(finalize))]` (never inferred from the receiver)
88//! - **Private**: R6 only, marked with `#[miniextendr(r6(private))]`
89//!
90//! ## Shared Builders
91//!
92//! This module uses shared infrastructure from:
93//! - [`crate::c_wrapper_builder`]: C wrapper generation with thread strategy
94//! - [`crate::r_wrapper_builder`]: R function signatures and `.Call()` args
95//! - [`crate::method_return_builder`]: Return value handling per class system
96//! - [`crate::roxygen`]: Documentation extraction from Rust doc comments
97//!
98//! ## Example
99//!
100//! ```ignore
101//! #[miniextendr(r6)]
102//! impl Counter {
103//!     fn new(value: i32) -> Self { Counter { value } }
104//!     fn get(&self) -> i32 { self.value }
105//!     fn increment(&mut self) { self.value += 1; }
106//! }
107//! ```
108//!
109//! Generates:
110//! - C wrappers: `C_<crate>_Counter__new`, `C_<crate>_Counter__get`, `C_<crate>_Counter__increment`
111//! - R6Class with `initialize`, `get`, `increment` methods
112//! - Registration entries for R's `.Call()` interface
113
114use proc_macro2::TokenStream;
115use quote::quote;
116
117/// Check if a type is `ExternalPtr<...>` (possibly fully qualified).
118fn is_external_ptr_type(ty: &syn::Type) -> bool {
119    if let syn::Type::Path(type_path) = ty {
120        type_path
121            .path
122            .segments
123            .last()
124            .map(|seg| seg.ident == "ExternalPtr")
125            .unwrap_or(false)
126    } else {
127        false
128    }
129}
130
131/// Refuse the receivers `self: &ExternalPtr<Self>` / `self: &mut
132/// ExternalPtr<Self>`, which #2106 replaced by the views: a handle behind a
133/// reference reads its value unchecked, while a view holds the borrow.
134fn old_handle_receiver(sig: &syn::Signature) -> syn::Result<()> {
135    let Some(syn::FnArg::Receiver(receiver)) = sig.inputs.first() else {
136        return Ok(());
137    };
138    let syn::Type::Reference(reference) = receiver.ty.as_ref() else {
139        return Ok(());
140    };
141    if receiver.colon_token.is_none() || !is_external_ptr_type(&reference.elem) {
142        return Ok(());
143    }
144    let (view, binding) = if reference.mutability.is_some() {
145        ("ExternalPtrMut", "mut self")
146    } else {
147        ("ExternalPtrRef", "self")
148    };
149    Err(syn::Error::new_spanned(
150        &receiver.ty,
151        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a method takes its object as `{0}: {1}<\'_, Self>`: the wrapper borrows the value for the call, and the view carries the R object for the sidecar accessors (`Self::field(&self)`); use `&self` / `&mut self` when the body needs only the value, or `self: ExternalPtr<Self>` for the unborrowed handle",
                binding, view))
    })format!(
152            "a method takes its object as `{binding}: {view}<'_, Self>`: the wrapper borrows the \
153             value for the call, and the view carries the R object for the sidecar accessors \
154             (`Self::field(&self)`); use `&self` / `&mut self` when the body needs only the \
155             value, or `self: ExternalPtr<Self>` for the unborrowed handle"
156        ),
157    ))
158}
159
160/// Rewrite methods with handle receivers so they compile on stable Rust
161/// (which lacks `arbitrary_self_types`).
162///
163/// Handles:
164/// - `self: ExternalPtrRef<'_, Self>` → `__miniextendr_self: ExternalPtrRef<'_, Self>`
165/// - `self: ExternalPtrMut<'_, Self>` → `__miniextendr_self: ExternalPtrMut<'_, Self>`
166/// - `self: ExternalPtr<Self>` → `__miniextendr_self: ExternalPtr<Self>`
167///
168/// Also replaces all `self` references in the method body with `__miniextendr_self`.
169fn rewrite_external_ptr_receivers(mut item_impl: syn::ItemImpl) -> syn::ItemImpl {
170    for item in &mut item_impl.items {
171        let syn::ImplItem::Fn(method) = item else {
172            continue;
173        };
174        if crate::trait_receiver::owner_receiver(&method.sig).is_some() {
175            crate::trait_receiver::rewrite(&mut method.sig, Some(&mut method.block));
176            continue;
177        }
178        let Some(syn::FnArg::Receiver(receiver)) = method.sig.inputs.first() else {
179            continue;
180        };
181        if receiver.colon_token.is_none() || !is_external_ptr_type(receiver.ty.as_ref()) {
182            continue;
183        }
184
185        // self: ExternalPtr<Self> (by value)
186        let receiver_ident =
187            proc_macro2::Ident::new("__miniextendr_self", proc_macro2::Span::mixed_site());
188        let binding_mutability = receiver.mutability;
189        let inner_ty = &receiver.ty;
190        let new_param: syn::FnArg = ::syn::__private::parse_quote({
        let mut _s = ::quote::__private::TokenStream::new();
        ::quote::ToTokens::to_tokens(&binding_mutability, &mut _s);
        ::quote::ToTokens::to_tokens(&receiver_ident, &mut _s);
        ::quote::__private::push_colon(&mut _s);
        ::quote::ToTokens::to_tokens(&inner_ty, &mut _s);
        _s
    })syn::parse_quote! {
191            #binding_mutability #receiver_ident: #inner_ty
192        };
193
194        // Replace first parameter
195        let inputs: Vec<syn::FnArg> = method.sig.inputs.iter().cloned().collect();
196        let mut new_inputs: Vec<syn::FnArg> = Vec::with_capacity(inputs.len());
197        new_inputs.push(new_param);
198        new_inputs.extend(inputs.into_iter().skip(1));
199        method.sig.inputs = new_inputs.into_iter().collect();
200
201        crate::receiver_body::rewrite(&mut method.block, &receiver_ident);
202    }
203    item_impl
204}
205
206/// Strip `#[miniextendr(...)]` attributes and roxygen doc tags from an impl block and
207/// all of its items (functions, constants, types, macros).
208///
209/// Called before re-emitting the original impl block so that proc-macro attributes
210/// do not appear in the compiler output. Returns the cleaned impl block.
211fn strip_miniextendr_attrs_from_impl(mut item_impl: syn::ItemImpl) -> syn::ItemImpl {
212    item_impl.attrs = crate::roxygen::strip_roxygen_from_attrs(&item_impl.attrs);
213    item_impl
214        .attrs
215        .retain(|attr| !attr.path().is_ident("miniextendr"));
216    for item in &mut item_impl.items {
217        match item {
218            syn::ImplItem::Fn(fn_item) => {
219                fn_item.attrs = crate::roxygen::strip_roxygen_from_attrs(&fn_item.attrs);
220                fn_item
221                    .attrs
222                    .retain(|attr| !attr.path().is_ident("miniextendr"));
223            }
224            syn::ImplItem::Const(const_item) => {
225                const_item.attrs = crate::roxygen::strip_roxygen_from_attrs(&const_item.attrs);
226                const_item
227                    .attrs
228                    .retain(|attr| !attr.path().is_ident("miniextendr"));
229            }
230            syn::ImplItem::Type(type_item) => {
231                type_item.attrs = crate::roxygen::strip_roxygen_from_attrs(&type_item.attrs);
232                type_item
233                    .attrs
234                    .retain(|attr| !attr.path().is_ident("miniextendr"));
235            }
236            syn::ImplItem::Macro(macro_item) => {
237                macro_item.attrs = crate::roxygen::strip_roxygen_from_attrs(&macro_item.attrs);
238                macro_item
239                    .attrs
240                    .retain(|attr| !attr.path().is_ident("miniextendr"));
241            }
242            _ => {}
243        }
244    }
245    item_impl
246}
247
248/// Class system flavor for wrapper generation.
249#[derive(#[automatically_derived]impl ::core::fmt::Debug for ClassSystem {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "Env R6 S7 S3 S4 Vctrs",
            match self {
                ClassSystem::Env => 0usize,
                ClassSystem::R6 => 4usize,
                ClassSystem::S7 => 7usize,
                ClassSystem::S3 => 10usize,
                ClassSystem::S4 => 13usize,
                ClassSystem::Vctrs => 16usize,
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ClassSystem {
}
#[automatically_derived]impl ::core::clone::Clone for ClassSystem {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ClassSystem { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ClassSystem {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ClassSystem {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ClassSystem { }Eq)]
250pub enum ClassSystem {
251    /// Environment-style with `$`/`[[` dispatch
252    Env,
253    /// R6::R6Class
254    R6,
255    /// S7::new_class
256    S7,
257    /// S3 structure() with class attribute
258    S3,
259    /// S4 setClass
260    S4,
261    /// vctrs-compatible S3 class (vctr, rcrd, or list_of)
262    Vctrs,
263}
264
265impl ClassSystem {
266    /// Convert to an identifier for token transport (e.g., in macro_rules! expansion).
267    pub fn to_ident(self) -> syn::Ident {
268        let name = match self {
269            ClassSystem::Env => "env",
270            ClassSystem::R6 => "r6",
271            ClassSystem::S7 => "s7",
272            ClassSystem::S3 => "s3",
273            ClassSystem::S4 => "s4",
274            ClassSystem::Vctrs => "vctrs",
275        };
276        syn::Ident::new(name, proc_macro2::Span::call_site())
277    }
278
279    /// Parse from an identifier (inverse of `to_ident`).
280    pub fn from_ident(ident: &syn::Ident) -> Option<Self> {
281        match ident.to_string().as_str() {
282            "env" => Some(ClassSystem::Env),
283            "r6" => Some(ClassSystem::R6),
284            "s7" => Some(ClassSystem::S7),
285            "s3" => Some(ClassSystem::S3),
286            "s4" => Some(ClassSystem::S4),
287            "vctrs" => Some(ClassSystem::Vctrs),
288            _ => None,
289        }
290    }
291}
292
293/// Case-insensitive parsing of class system names from strings.
294///
295/// Accepts: `"env"`, `"r6"`, `"s3"`, `"s4"`, `"s7"`, `"vctrs"` (any casing).
296impl std::str::FromStr for ClassSystem {
297    type Err = String;
298
299    fn from_str(s: &str) -> Result<Self, Self::Err> {
300        match s.to_lowercase().as_str() {
301            "env" => Ok(ClassSystem::Env),
302            "r6" => Ok(ClassSystem::R6),
303            "s7" => Ok(ClassSystem::S7),
304            "s3" => Ok(ClassSystem::S3),
305            "s4" => Ok(ClassSystem::S4),
306            "vctrs" => Ok(ClassSystem::Vctrs),
307            _ => Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown class system: {0}", s))
    })format!("unknown class system: {}", s)),
308        }
309    }
310}
311
312/// What the impl option `r_data_accessors` asks for: the class-level form of
313/// the `pub` `#[r_data]` fields of `#[derive(ExternalPtr)]`, next to the
314/// standalone `Type_get_f()` / `Type_set_f()` every class gets.
315///
316/// R6 gets active bindings, S7 properties, and S3, S4 and env classes `$` /
317/// `[[` field methods (#1848, `field_syntax.rs`).
318#[derive(#[automatically_derived]impl ::core::fmt::Debug for RDataAccessors {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                RDataAccessors::Off => "Off",
                RDataAccessors::GetSet => "GetSet",
                RDataAccessors::GetOnly => "GetOnly",
                RDataAccessors::ReadOnly => "ReadOnly",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for RDataAccessors {
}
#[automatically_derived]impl ::core::clone::Clone for RDataAccessors {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for RDataAccessors { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    RDataAccessors {
}
#[automatically_derived]impl ::core::cmp::PartialEq for RDataAccessors {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for RDataAccessors { }Eq, #[automatically_derived]impl ::core::default::Default for RDataAccessors {
    #[inline]
    fn default() -> Self { Self::Off }
}Default)]
319pub enum RDataAccessors {
320    /// No option: only the standalone accessors.
321    #[default]
322    Off,
323    /// `r_data_accessors`: a getter and a setter per field.
324    GetSet,
325    /// `r_data_accessors = "get"` (S3, S4, env): `$` / `[[` read the fields
326    /// and no `$<-` / `[[<-` is generated, for a class whose own replacement
327    /// methods write them (for example copy-on-modify setters that return a
328    /// new object).
329    GetOnly,
330    /// `r_data_accessors = "read_only"` (S3, S4, env, #2268): `$` / `[[`
331    /// read the fields, and the generated `$<-` / `[[<-` refuse every field
332    /// with `miniextendr_read_only_field` (the derive's
333    /// `.rdata_read_only_<Type>`). The class's `ClassNameEntry::read_only_fields`
334    /// has the wrapper writer drop the standalone `Type_set_f()` too (the
335    /// derive's setter C entry points stay: it can't see this option). A
336    /// per-field `#[r_data(read_only)]` does the same for one field under
337    /// any class system.
338    ReadOnly,
339}
340
341impl RDataAccessors {
342    /// Whether the class wires its fields in at all.
343    pub fn enabled(self) -> bool {
344        self != RDataAccessors::Off
345    }
346
347    /// Whether the class gets `$<-` / `[[<-` field methods: the setters of
348    /// `r_data_accessors`, or the refusals of `r_data_accessors =
349    /// "read_only"`.
350    pub fn writers(self) -> bool {
351        #[allow(non_exhaustive_omitted_patterns)] match self {
    RDataAccessors::GetSet | RDataAccessors::ReadOnly => true,
    _ => false,
}matches!(self, RDataAccessors::GetSet | RDataAccessors::ReadOnly)
352    }
353
354    /// Whether the `$<-` / `[[<-` field methods write the fields (through
355    /// `.rdata_set_<Type>`) rather than refuse them.
356    pub fn setters(self) -> bool {
357        self == RDataAccessors::GetSet
358    }
359}
360
361/// How the S3 readers of `s3(r_data_accessors)` look a field up on a bare
362/// pointer (`field_syntax.rs`): `s3(r_data_accessors, lookup = "list")`.
363/// Neither lookup matches a prefix of a name (#1922).
364#[derive(#[automatically_derived]impl ::core::fmt::Debug for FieldLookup {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                FieldLookup::Strict => "Strict",
                FieldLookup::List => "List",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for FieldLookup {
}
#[automatically_derived]impl ::core::clone::Clone for FieldLookup {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for FieldLookup { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    FieldLookup {
}
#[automatically_derived]impl ::core::cmp::PartialEq for FieldLookup {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for FieldLookup { }Eq, #[automatically_derived]impl ::core::default::Default for FieldLookup {
    #[inline]
    fn default() -> Self { Self::Strict }
}Default)]
365pub enum FieldLookup {
366    /// The default (#1921): exact names and whole-number positions only; an
367    /// unknown name raises `miniextendr_no_field` and any other index the
368    /// bad-index error.
369    #[default]
370    Strict,
371    /// `lookup = "list"` (#1891): a list's lenience without its prefix
372    /// match. An unknown name or `NA` reads `NULL`, and `[[` takes a logical
373    /// or a fractional position.
374    List,
375}
376
377/// The fallback of the field readers of `s3(r_data_accessors)`,
378/// `s4(r_data_accessors)` and `env(r_data_accessors)` (#2150):
379/// `fallback = "Self::column"`, and optionally
380/// `fallback_names = "Self::column_names"`, in the path style of
381/// `#[r_data(get = "Self::f")]`.
382///
383/// `fallback` names a `fn(&Self, name: &str) -> Option<T>`, `T: IntoR`,
384/// which the readers call on the live Rust value for a name no field has, on
385/// the bare pointer (an S3 or env object's classed pointer, an S4 object's
386/// `ptr`); a list or environment carrying the pointer in `.ptr` keeps its own
387/// elements for those names. Fields win, a `[[` position counts the fields
388/// only, `names()` / `as.list()` stay the fields, and an assignment to a name
389/// no field has is refused as before. `None` reads what an unknown name
390/// reads without the fallback: `miniextendr_no_field` on S3 (default lookup)
391/// and S4, `NULL` under `lookup = "list"` and on an env class (whose `$`
392/// tries the methods before the fallback). The macro handles the `Option`
393/// itself, so `Some(x)` reads `x` and a scalar `T` is never `NA` for `None`.
394///
395/// `fallback_names` names a `fn(&Self) -> Vec<String>`: `.DollarNames()`
396/// offers its names after the fields (after the methods on an env class).
397/// Without it, completion offers the fields only.
398///
399/// The impl expansion emits one `.Call` entry for each
400/// (`field_syntax::fallback_c_entries`), so only one impl block of a type
401/// carries the option: it is not a class setting the blocks repeat
402/// ([`ParsedImpl::class_settings`]) but part of the class that block defines
403/// ([`ParsedImpl::class_definitions`]), next to the constructor.
404#[derive(#[automatically_derived]impl ::core::fmt::Debug for FieldFallback {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "FieldFallback get names", &self.get, &&self.names)
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for FieldFallback {
    #[inline]
    fn clone(&self) -> Self {
        FieldFallback {
            get: ::core::clone::Clone::clone(&self.get),
            names: ::core::clone::Clone::clone(&self.names),
        }
    }
}Clone)]
405pub struct FieldFallback {
406    /// `fallback = "Self::column"`: the path, as written.
407    pub get: syn::LitStr,
408    /// `fallback_names = "Self::column_names"`, as written.
409    pub names: Option<syn::LitStr>,
410}
411
412/// Parses the value of a `fallback` / `fallback_names` key inside `s3(...)` /
413/// `s4(...)` / `env(...)`, after the key: `= "path"`, where the path names a
414/// function (a leading `Self` is the impl's type).
415fn parse_fallback_value(
416    content: syn::parse::ParseStream,
417    key: &syn::Ident,
418) -> syn::Result<syn::LitStr> {
419    let example = if key == "fallback" {
420        "Self::column"
421    } else {
422        "Self::column_names"
423    };
424    if !content.peek(::syn::token::Eqsyn::Token![=]) {
425        return Err(syn::Error::new(
426            key.span(),
427            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` takes a path to a function in a string: `{0} = \"{1}\"`",
                key, example))
    })format!("`{key}` takes a path to a function in a string: `{key} = \"{example}\"`"),
428        ));
429    }
430    let _: ::syn::token::Eqsyn::Token![=] = content.parse()?;
431    if !content.peek(syn::LitStr) {
432        return Err(content.error(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` takes a path to a function in a string: `{0} = \"{1}\"`",
                key, example))
    })format!(
433            "`{key}` takes a path to a function in a string: `{key} = \"{example}\"`"
434        )));
435    }
436    let value: syn::LitStr = content.parse()?;
437    if let Err(err) = value.parse::<syn::Path>() {
438        return Err(syn::Error::new_spanned(
439            &value,
440            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` must be a path to a function, e.g. `{1}`: {2}",
                key, example, err))
    })format!("`{key}` must be a path to a function, e.g. `{example}`: {err}"),
441        ));
442    }
443    Ok(value)
444}
445
446/// The error for `fallback` / `fallback_names` under a class system without
447/// field syntax: R6 active bindings and S7 properties are a fixed set of
448/// names, and a vctr has no pointer.
449fn no_field_fallback_error(key: &syn::Ident, system: &str) -> syn::Error {
450    let why = match system {
451        "r6" => "an R6 object's `$` reads its environment, whose active bindings are fixed",
452        "s7" => "S7 properties are a fixed set, read with `@`",
453        _ => "a vctr is an R vector with no external pointer",
454    };
455    syn::Error::new(
456        key.span(),
457        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` applies to the `$` / `[[` readers of `s3(r_data_accessors)`, `s4(r_data_accessors)` and `env(r_data_accessors)`; {1}",
                key, why))
    })format!(
458            "`{key}` applies to the `$` / `[[` readers of `s3(r_data_accessors)`, \
459             `s4(r_data_accessors)` and `env(r_data_accessors)`; {why}"
460        ),
461    )
462}
463
464/// Parses an `r_data_accessors` key inside `s3(...)` / `s4(...)` / `env(...)`
465/// / `r6(...)` / `s7(...)`, after the key: nothing, `= "get"` or
466/// `= "read_only"` (#2268); the last two on S3, S4 and env only.
467fn parse_r_data_accessors_value(
468    content: syn::parse::ParseStream,
469    key: &syn::Ident,
470    system: ClassSystem,
471) -> syn::Result<RDataAccessors> {
472    if !content.peek(::syn::token::Eqsyn::Token![=]) {
473        return Ok(RDataAccessors::GetSet);
474    }
475    let _: ::syn::token::Eqsyn::Token![=] = content.parse()?;
476    let value: syn::LitStr = content.parse()?;
477    let accessors = match value.value().as_str() {
478        "get" => RDataAccessors::GetOnly,
479        "read_only" => RDataAccessors::ReadOnly,
480        other => {
481            return Err(syn::Error::new(
482                value.span(),
483                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown `r_data_accessors` value \"{0}\"; expected `r_data_accessors` (getters and setters), `r_data_accessors = \"get\"` (getters only) or `r_data_accessors = \"read_only\"` (getters, and setters that refuse)",
                other))
    })format!(
484                    "unknown `r_data_accessors` value \"{other}\"; expected `r_data_accessors` \
485                     (getters and setters), `r_data_accessors = \"get\"` (getters only) or \
486                     `r_data_accessors = \"read_only\"` (getters, and setters that refuse)"
487                ),
488            ));
489        }
490    };
491    if !#[allow(non_exhaustive_omitted_patterns)] match system {
    ClassSystem::S3 | ClassSystem::S4 | ClassSystem::Env => true,
    _ => false,
}matches!(system, ClassSystem::S3 | ClassSystem::S4 | ClassSystem::Env) {
492        let form = match accessors {
493            RDataAccessors::ReadOnly => {
494                "the read-only form `r_data_accessors = \"read_only\"` applies to `s3`, `s4` and \
495                 `env` classes; R6 active bindings and S7 properties take the bare \
496                 `r_data_accessors`, and a field they must not write is `#[r_data(read_only)]`"
497            }
498            _ => {
499                "the getters-only form `r_data_accessors = \"get\"` applies to `s3`, `s4` and \
500                 `env` classes; R6 active bindings and S7 properties take the bare \
501                 `r_data_accessors`, and a field they must not write is `#[r_data(read_only)]`"
502            }
503        };
504        return Err(syn::Error::new(key.span(), form));
505    }
506    Ok(accessors)
507}
508
509/// Kind of vctrs class being created.
510#[derive(#[automatically_derived]impl ::core::fmt::Debug for VctrsKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                VctrsKind::Vctr => "Vctr",
                VctrsKind::Rcrd => "Rcrd",
                VctrsKind::ListOf => "ListOf",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for VctrsKind {
}
#[automatically_derived]impl ::core::clone::Clone for VctrsKind {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for VctrsKind { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for VctrsKind
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for VctrsKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for VctrsKind { }Eq, #[automatically_derived]impl ::core::default::Default for VctrsKind {
    #[inline]
    fn default() -> Self { Self::Vctr }
}Default)]
511pub enum VctrsKind {
512    /// Simple vctr backed by a base vector (new_vctr)
513    #[default]
514    Vctr,
515    /// Record type with named fields (new_rcrd)
516    Rcrd,
517    /// Homogeneous list with ptype (new_list_of)
518    ListOf,
519}
520
521/// Case-insensitive parsing of vctrs kind names from strings.
522///
523/// Accepts: `"vctr"`, `"rcrd"` (or `"record"`), `"list_of"` (or `"listof"`).
524impl std::str::FromStr for VctrsKind {
525    type Err = String;
526
527    fn from_str(s: &str) -> Result<Self, Self::Err> {
528        match s.to_lowercase().as_str() {
529            "vctr" => Ok(VctrsKind::Vctr),
530            "rcrd" | "record" => Ok(VctrsKind::Rcrd),
531            "list_of" | "listof" => Ok(VctrsKind::ListOf),
532            _ => Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown vctrs kind: {0} (expected vctr, rcrd, or list_of)",
                s))
    })format!(
533                "unknown vctrs kind: {} (expected vctr, rcrd, or list_of)",
534                s
535            )),
536        }
537    }
538}
539
540/// Attributes for vctrs class generation.
541#[derive(#[automatically_derived]impl ::core::fmt::Debug for VctrsAttrs {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f,
            "VctrsAttrs kind base inherit_base_type ptype abbr", &self.kind,
            &self.base, &self.inherit_base_type, &self.ptype, &&self.abbr)
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for VctrsAttrs {
    #[inline]
    fn clone(&self) -> Self {
        VctrsAttrs {
            kind: ::core::clone::Clone::clone(&self.kind),
            base: ::core::clone::Clone::clone(&self.base),
            inherit_base_type: ::core::clone::Clone::clone(&self.inherit_base_type),
            ptype: ::core::clone::Clone::clone(&self.ptype),
            abbr: ::core::clone::Clone::clone(&self.abbr),
        }
    }
}Clone, #[automatically_derived]impl ::core::default::Default for VctrsAttrs {
    #[inline]
    fn default() -> Self {
        VctrsAttrs {
            kind: ::core::default::Default::default(),
            base: ::core::default::Default::default(),
            inherit_base_type: ::core::default::Default::default(),
            ptype: ::core::default::Default::default(),
            abbr: ::core::default::Default::default(),
        }
    }
}Default)]
542pub struct VctrsAttrs {
543    /// The vctrs kind (vctr, rcrd, list_of)
544    pub kind: VctrsKind,
545    /// Base type for vctr (e.g., "double", "integer", "character")
546    pub base: Option<String>,
547    /// Whether to inherit base type in class vector
548    pub inherit_base_type: Option<bool>,
549    /// Prototype type for list_of (R expression)
550    pub ptype: Option<String>,
551    /// Abbreviation for vec_ptype_abbr (for printing)
552    pub abbr: Option<String>,
553}
554
555/// Receiver kind for methods.
556#[derive(#[automatically_derived]impl ::core::fmt::Debug for ReceiverKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "None Ref RefMut Value ExternalPtrRef ExternalPtrMut ExternalPtrValue",
            match self {
                ReceiverKind::None => 0usize,
                ReceiverKind::Ref => 5usize,
                ReceiverKind::RefMut => 9usize,
                ReceiverKind::Value => 16usize,
                ReceiverKind::ExternalPtrRef => 22usize,
                ReceiverKind::ExternalPtrMut => 37usize,
                ReceiverKind::ExternalPtrValue => 52usize,
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ReceiverKind {
}
#[automatically_derived]impl ::core::clone::Clone for ReceiverKind {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ReceiverKind { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ReceiverKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ReceiverKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ReceiverKind { }Eq)]
557pub enum ReceiverKind {
558    /// No env - static/associated function
559    None,
560    /// `&self` - immutable borrow
561    Ref,
562    /// `&mut self` - mutable borrow
563    RefMut,
564    /// `self` (or `self: Self`) - consuming. The C wrapper moves the value out
565    /// of the R handle: `-> Self` writes the result back (same handle, in-place
566    /// semantics), `-> Result<Self, E>` / `-> Option<Self>` run on a clone and
567    /// overwrite on success, anything else leaves the handle consumed.
568    Value,
569    /// `self: ExternalPtrRef<'_, Self>` — shared borrow, with the R object
570    ExternalPtrRef,
571    /// `self: ExternalPtrMut<'_, Self>` — exclusive borrow, with the R object
572    ExternalPtrMut,
573    /// `self: ExternalPtr<Self>` — the handle, unborrowed (not consuming the inner T)
574    ExternalPtrValue,
575}
576
577impl ReceiverKind {
578    /// Returns true if this is an instance method (has self), including the
579    /// consuming `self` receiver.
580    pub fn is_instance(&self) -> bool {
581        #[allow(non_exhaustive_omitted_patterns)] match self {
    ReceiverKind::Ref | ReceiverKind::RefMut | ReceiverKind::Value |
        ReceiverKind::ExternalPtrRef | ReceiverKind::ExternalPtrMut |
        ReceiverKind::ExternalPtrValue => true,
    _ => false,
}matches!(
582            self,
583            ReceiverKind::Ref
584                | ReceiverKind::RefMut
585                | ReceiverKind::Value
586                | ReceiverKind::ExternalPtrRef
587                | ReceiverKind::ExternalPtrMut
588                | ReceiverKind::ExternalPtrValue
589        )
590    }
591
592    /// Returns true if this is a mutable instance receiver.
593    pub fn is_mut(&self) -> bool {
594        #[allow(non_exhaustive_omitted_patterns)] match self {
    ReceiverKind::RefMut | ReceiverKind::ExternalPtrMut => true,
    _ => false,
}matches!(self, ReceiverKind::RefMut | ReceiverKind::ExternalPtrMut)
595    }
596}
597
598/// Parsed method from an impl block.
599///
600/// # Default Parameters
601///
602/// Default parameters are specified using method-level syntax:
603/// - `#[miniextendr(defaults(param = "value", ...))]` on the method
604///
605/// Note: Parameter-level `#[miniextendr(default = "...")]` syntax is only supported
606/// for standalone functions, not impl methods (Rust language limitation).
607///
608/// Defaults cannot be specified for `self` parameters (compile error).
609#[derive(#[automatically_derived]impl ::core::fmt::Debug for ParsedMethod {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            "ParsedMethod visibility_marker return_wrap ident env sig param_markers vis doc_tags method_attrs param_defaults has_dots rng_guard";
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.visibility_marker, &self.return_wrap, &self.ident,
                        &self.env, &self.sig, &self.param_markers, &self.vis,
                        &self.doc_tags, &self.method_attrs, &self.param_defaults,
                        &self.has_dots, &&self.rng_guard];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
    }
}Debug)]
610pub struct ParsedMethod {
611    /// Return-type visibility marker (#1213): `Some(true)` for
612    /// `-> Invisible<T>`, `Some(false)` for `-> Visible<T>`. The marker is
613    /// peeled from [`Self::sig`] at parse time, so every return-shape
614    /// predicate sees `T`; the C wrapper unwraps the newtype before conversion.
615    pub visibility_marker: Option<bool>,
616    /// Explicit target class wrapping, shared by marker and attribute spellings.
617    pub return_wrap: Option<crate::return_wrap::ReturnWrap>,
618    /// The method's name (e.g., `new`, `get`, `set_value`).
619    pub ident: syn::Ident,
620    /// How this method receives `self`: `&self`, `&mut self`, by value, or not at all (static).
621    pub env: ReceiverKind,
622    /// Method signature with the `self` receiver stripped. Used for C wrapper generation
623    /// where `self` is handled separately as a SEXP parameter. The parameter
624    /// markers (`Checked<T>` / `Unchecked<T>`, #1566) are peeled from it, as
625    /// the visibility marker is from the output: every R-side consumer and
626    /// the conversion see the inner type.
627    pub sig: syn::Signature,
628    /// The parameter markers peeled from [`Self::sig`] (Rust name →
629    /// markers, outermost first): the C wrapper wraps the converted value in
630    /// them before the call.
631    pub param_markers: Vec<(String, Vec<crate::type_inspect::ParamMarker>)>,
632    /// Rust visibility of the method. Non-`pub` methods become private in R6;
633    /// only `pub` methods get `@export` in R wrappers.
634    pub vis: syn::Visibility,
635    /// Roxygen tag lines extracted from Rust doc comments
636    pub doc_tags: Vec<String>,
637    /// Per-method attributes for class system overrides. Also carries the
638    /// `match_arg(...)` / `choices(...)` / `several_ok` parameter annotations
639    /// via its `per_param_match_arg` / `per_param_choices` / `per_param_several_ok`
640    /// fields — see [`MethodAttrs`] for the parsing surface.
641    pub method_attrs: MethodAttrs,
642    /// Parameter default values from `#[miniextendr(defaults(...))]`, keyed
643    /// by Rust name; the R wrapper keys them by formal
644    /// ([`Formals::rekey`](crate::r_wrapper_builder::Formals::rekey)).
645    pub param_defaults: std::collections::HashMap<String, String>,
646    /// Whether this method accepts dots, either from raw `...` rewritten to
647    /// `&Dots` or from an explicit `&Dots` parameter, anywhere.
648    pub has_dots: bool,
649    /// Where the `&RngGuard` parameter (#2002) sat among the parameters of
650    /// [`Self::sig`], which no longer holds it: it is no R formal, and the C
651    /// wrapper passes the `rng` wrapper's guard at that position.
652    pub rng_guard: Option<usize>,
653}
654
655/// R6-specific per-method markers, separated from [`MethodAttrs`] so the
656/// `r6` parser branch and R6 class generator own a self-contained bag.
657///
658/// All R6 boolean flags live here.  Using any of these markers under a
659/// non-R6 class system (`#[miniextendr(s3)]`, `s4`, `s7`, `env`) is a
660/// compile-time error caught by [`ParsedMethod::validate_method_attrs`].
661#[derive(#[automatically_derived]impl ::core::fmt::Debug for R6MethodAttrs {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            "R6MethodAttrs active active_span setter prop private private_span finalize finalize_span deep_clone deep_clone_span";
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.active, &self.active_span, &self.setter, &self.prop,
                        &self.private, &self.private_span, &self.finalize,
                        &self.finalize_span, &self.deep_clone,
                        &&self.deep_clone_span];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
    }
}Debug, #[automatically_derived]impl ::core::default::Default for R6MethodAttrs {
    #[inline]
    fn default() -> Self {
        R6MethodAttrs {
            active: ::core::default::Default::default(),
            active_span: ::core::default::Default::default(),
            setter: ::core::default::Default::default(),
            prop: ::core::default::Default::default(),
            private: ::core::default::Default::default(),
            private_span: ::core::default::Default::default(),
            finalize: ::core::default::Default::default(),
            finalize_span: ::core::default::Default::default(),
            deep_clone: ::core::default::Default::default(),
            deep_clone_span: ::core::default::Default::default(),
        }
    }
}Default)]
662pub struct R6MethodAttrs {
663    /// Mark as active binding getter (`#[miniextendr(r6(active))]`).
664    pub active: bool,
665    /// Span of the `r6(active)` marker — used for error reporting when the
666    /// marker is misused in a non-R6 class generator.
667    pub active_span: Option<proc_macro2::Span>,
668    /// R6 active-binding *setter* (paired with an `active` getter by `prop`).
669    pub setter: bool,
670    /// R6 active-binding property name (defaults to the method name).
671    pub prop: Option<String>,
672    /// Mark as private method (`#[miniextendr(r6(private))]`).
673    /// Also inferred from non-`pub` Rust visibility.
674    pub private: bool,
675    /// Span of the `r6(private)` marker — points the validator's diagnostic
676    /// at the offending marker rather than the method ident.
677    pub private_span: Option<proc_macro2::Span>,
678    /// Mark as finalizer (`#[miniextendr(r6(finalize))]`).
679    /// Also inferred when the method consumes `self` and does not return `Self`.
680    pub finalize: bool,
681    /// Span of the `r6(finalize)` marker — see `private_span`.
682    pub finalize_span: Option<proc_macro2::Span>,
683    /// Mark as R6 deep-clone handler (`#[miniextendr(r6(deep_clone))]`).
684    /// This method is wired into `private$deep_clone` in the R6Class definition.
685    pub deep_clone: bool,
686    /// Span of the `r6(deep_clone)` marker — see `private_span`.
687    pub deep_clone_span: Option<proc_macro2::Span>,
688}
689
690/// S7-specific per-method markers, separated from [`MethodAttrs`] so the S7
691/// class generator has a self-contained bag of its own state (property
692/// getters/setters, generic-dispatch controls, convert() wiring) and the other
693/// class generators don't have to look past them.
694///
695/// # Mapping from `s7(...)` attribute keys
696///
697/// | Attribute | Field |
698/// |-----------|-------|
699/// | `s7(getter)` | `getter: true` |
700/// | `s7(setter)` | `setter: true` |
701/// | `s7(prop = "name")` | `prop: Some("name")` |
702/// | `s7(default = "expr")` | `default: Some("expr")` |
703/// | `s7(validate)` | `validate: true` |
704/// | `s7(required)` | `required: true` |
705/// | `s7(frozen)` | `frozen: true` |
706/// | `s7(deprecated = "msg")` | `deprecated: Some("msg")` |
707/// | `s7(no_dots)` | `no_dots: true` |
708/// | `s7(dispatch = "x,y")` | `dispatch: Some("x,y")` |
709/// | `s7(fallback)` | `fallback: true` |
710/// | `s7(convert_from = "T")` | `convert_from: Some("T")` |
711/// | `s7(convert_to = "T")` | `convert_to: Some("T")` |
712#[derive(#[automatically_derived]impl ::core::fmt::Debug for S7MethodAttrs {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            "S7MethodAttrs getter setter prop default validate required frozen deprecated no_dots dispatch fallback convert_from convert_to no_shortcut";
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.getter, &self.setter, &self.prop, &self.default,
                        &self.validate, &self.required, &self.frozen,
                        &self.deprecated, &self.no_dots, &self.dispatch,
                        &self.fallback, &self.convert_from, &self.convert_to,
                        &&self.no_shortcut];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
    }
}Debug, #[automatically_derived]impl ::core::default::Default for S7MethodAttrs {
    #[inline]
    fn default() -> Self {
        S7MethodAttrs {
            getter: ::core::default::Default::default(),
            setter: ::core::default::Default::default(),
            prop: ::core::default::Default::default(),
            default: ::core::default::Default::default(),
            validate: ::core::default::Default::default(),
            required: ::core::default::Default::default(),
            frozen: ::core::default::Default::default(),
            deprecated: ::core::default::Default::default(),
            no_dots: ::core::default::Default::default(),
            dispatch: ::core::default::Default::default(),
            fallback: ::core::default::Default::default(),
            convert_from: ::core::default::Default::default(),
            convert_to: ::core::default::Default::default(),
            no_shortcut: ::core::default::Default::default(),
        }
    }
}Default)]
713pub struct S7MethodAttrs {
714    pub getter: bool,
715    pub setter: bool,
716    pub prop: Option<String>,
717    pub default: Option<String>,
718    pub validate: bool,
719    pub required: bool,
720    pub frozen: bool,
721    pub deprecated: Option<String>,
722    pub no_dots: bool,
723    pub dispatch: Option<String>,
724    pub fallback: bool,
725    pub convert_from: Option<String>,
726    pub convert_to: Option<String>,
727    /// Opt out of the per-class `<ClassName>_<method>` fast-dispatch shortcut
728    /// (set via `#[miniextendr(s7(no_shortcut))]`). The S7 generic + method are
729    /// still emitted; only the standalone shortcut function is suppressed.
730    pub no_shortcut: bool,
731}
732
733/// Per-method attributes for class system customization.
734#[derive(#[automatically_derived]impl ::core::fmt::Debug for MethodAttrs {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            "MethodAttrs ignore constructor force_invisible r6 as_coercion as_coercion_span generic receiver no_dispatch_dots class check_interrupt coerce preconditions rng dots_spec dots_policy unwrap_in_r serde_error serialize wrap defaults defaults_span per_param match_arg_span s7 lifecycle vctrs_protocol r_name postfix r_entry r_post_checks r_on_exit internal noexport";
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.ignore, &self.constructor, &self.force_invisible,
                        &self.r6, &self.as_coercion, &self.as_coercion_span,
                        &self.generic, &self.receiver, &self.no_dispatch_dots,
                        &self.class, &self.check_interrupt, &self.coerce,
                        &self.preconditions, &self.rng, &self.dots_spec,
                        &self.dots_policy, &self.unwrap_in_r, &self.serde_error,
                        &self.serialize, &self.wrap, &self.defaults,
                        &self.defaults_span, &self.per_param, &self.match_arg_span,
                        &self.s7, &self.lifecycle, &self.vctrs_protocol,
                        &self.r_name, &self.postfix, &self.r_entry,
                        &self.r_post_checks, &self.r_on_exit, &self.internal,
                        &&self.noexport];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
    }
}Debug, #[automatically_derived]impl ::core::default::Default for MethodAttrs {
    #[inline]
    fn default() -> Self {
        MethodAttrs {
            ignore: ::core::default::Default::default(),
            constructor: ::core::default::Default::default(),
            force_invisible: ::core::default::Default::default(),
            r6: ::core::default::Default::default(),
            as_coercion: ::core::default::Default::default(),
            as_coercion_span: ::core::default::Default::default(),
            generic: ::core::default::Default::default(),
            receiver: ::core::default::Default::default(),
            no_dispatch_dots: ::core::default::Default::default(),
            class: ::core::default::Default::default(),
            check_interrupt: ::core::default::Default::default(),
            coerce: ::core::default::Default::default(),
            preconditions: ::core::default::Default::default(),
            rng: ::core::default::Default::default(),
            dots_spec: ::core::default::Default::default(),
            dots_policy: ::core::default::Default::default(),
            unwrap_in_r: ::core::default::Default::default(),
            serde_error: ::core::default::Default::default(),
            serialize: ::core::default::Default::default(),
            wrap: ::core::default::Default::default(),
            defaults: ::core::default::Default::default(),
            defaults_span: ::core::default::Default::default(),
            per_param: ::core::default::Default::default(),
            match_arg_span: ::core::default::Default::default(),
            s7: ::core::default::Default::default(),
            lifecycle: ::core::default::Default::default(),
            vctrs_protocol: ::core::default::Default::default(),
            r_name: ::core::default::Default::default(),
            postfix: ::core::default::Default::default(),
            r_entry: ::core::default::Default::default(),
            r_post_checks: ::core::default::Default::default(),
            r_on_exit: ::core::default::Default::default(),
            internal: ::core::default::Default::default(),
            noexport: ::core::default::Default::default(),
        }
    }
}Default)]
735pub struct MethodAttrs {
736    /// Skip this method
737    pub ignore: bool,
738    /// Mark as constructor
739    pub constructor: bool,
740    /// `invisible` / `visible` method option (#1213): `Some(true)` makes the R
741    /// wrapper return `invisible(...)`, `Some(false)` forces a visible return.
742    /// Same decision as an `Invisible<T>` / `Visible<T>` return-type marker;
743    /// the two must not disagree. Nothing is invisible by default.
744    pub force_invisible: Option<bool>,
745    /// R6-specific method markers. All R6 boolean flags live here.
746    /// Only consumed by the R6 class generator and R6-aware accessor methods
747    /// (`ParsedMethod::is_active`, `is_private`, `is_finalizer`).
748    pub r6: R6MethodAttrs,
749    /// Generate as `as.<class>()` S3 method (e.g., "data.frame", "list", "character").
750    ///
751    /// When set, generates an S3 method for R's `as.<class>()` generic:
752    /// ```r
753    /// as.data.frame.MyType <- function(x, ...) {
754    ///     .Call(C_MyType__as_data_frame, .call = sys.call(), x)
755    /// }
756    /// ```
757    ///
758    /// Valid values: data.frame, list, character, numeric, double, integer,
759    /// logical, matrix, vector, factor, Date, POSIXct, complex, raw,
760    /// environment, function
761    pub as_coercion: Option<String>,
762    /// Span of `as = "..."` for error reporting.
763    pub as_coercion_span: Option<proc_macro2::Span>,
764    /// Override generic name for S3/S4/S7 methods.
765    ///
766    /// Use this to implement methods for existing generics (like `print`, `format`, `length`)
767    /// without creating a new generic. When set, the generated code:
768    /// - Uses the specified generic name instead of the method name
769    /// - Skips creating a new generic (assumes it already exists)
770    /// - Creates only the method implementation (e.g., `print.MyClass`)
771    ///
772    /// # Example
773    /// ```ignore
774    /// #[miniextendr(s3)]
775    /// impl MyType {
776    ///     #[miniextendr(generic = "print")]
777    ///     fn show(&self) -> String {
778    ///         format!("MyType: {}", self.value)
779    ///     }
780    /// }
781    /// ```
782    /// This generates `print.MyType` that calls the `show` method.
783    pub generic: Option<String>,
784    /// First formal of an existing S3/S4 generic (for example `object` for show).
785    pub receiver: Option<String>,
786    /// Omit the automatic dispatch dots for an existing S3/S4 generic.
787    pub no_dispatch_dots: bool,
788    /// Override class suffix for S3 methods.
789    ///
790    /// Use this to implement double-dispatch methods (like vctrs coercion)
791    /// where the class suffix differs from the type name or contains multiple classes.
792    ///
793    /// # Example
794    /// ```ignore
795    /// #[miniextendr(s3(generic = "vec_ptype2", class = "my_vctr.my_vctr"))]
796    /// fn ptype2_self(x: Robj, y: Robj, dots: ...) -> Robj {
797    ///     // Return prototype
798    /// }
799    /// ```
800    /// This generates `vec_ptype2.my_vctr.my_vctr` for vctrs double-dispatch.
801    pub class: Option<String>,
802    /// Enable R interrupt checking
803    pub check_interrupt: bool,
804    /// Enable coercion for this method's parameters
805    pub coerce: bool,
806    /// The method's own `preconditions` / `no_preconditions` (bare; #1017,
807    /// #1566): `Some(true)` keeps the type-derived R-side checks of the
808    /// parameters that do not decide for themselves, `Some(false)` drops
809    /// them; the last one written wins. `None` defers to the impl block,
810    /// the crate default and the feature. The list forms
811    /// `preconditions(p)` / `no_preconditions(p)` land in
812    /// [`Self::per_param`].
813    pub preconditions: Option<bool>,
814    /// Enable RNG state management (GetRNGstate/PutRNGstate)
815    pub rng: bool,
816    /// `typed_list!(...)` spec from `#[miniextendr(dots = typed_list!(...))]` on
817    /// this method, mirroring `MiniextendrFnAttrs.dots_spec`. When set, a
818    /// `dots_typed` binding is injected at the top of the method body. Per-method
819    /// (dots apply to an individual signature), not an impl-block-level option.
820    pub dots_spec: Option<proc_macro2::TokenStream>,
821    /// What the method's `...` takes: `dots = empty | empty(allow = [..]) |
822    /// forward(allow = [..]) | data` (#2157, [`crate::dots_policy`]), checked
823    /// in the R wrapper's prelude
824    /// ([`emit_method_prelude`](crate::r_class_formatter::MethodContext::emit_method_prelude)).
825    pub dots_policy: Option<crate::dots_policy::DotsPolicy>,
826    /// Return `Result<T, E>` to R without unwrapping.
827    pub unwrap_in_r: bool,
828    /// Build the `Err` arm's condition from the error's serde output
829    /// (`#[miniextendr(serde_error(shape = .., tag = .., prefix = .., ..))]`).
830    pub serde_error: Option<crate::miniextendr_fn::SerdeErrorSpec>,
831    /// Serialize the complete return value through `AsSerialize<T>`.
832    pub serialize: bool,
833    /// Explicit return class system (`wrap = "r6"` and siblings).
834    pub wrap: Option<ClassSystem>,
835    /// Parameter defaults from `#[miniextendr(defaults(param = "value", ...))]`
836    pub defaults: std::collections::HashMap<String, String>,
837    /// Span of `defaults(...)` for error reporting.
838    pub defaults_span: Option<proc_macro2::Span>,
839    /// Per-parameter `match_arg` / `several_ok` / `choices` state for this
840    /// method, keyed by the Rust parameter name.
841    ///
842    /// Method-level (not parameter-level) because Rust's parser rejects
843    /// attribute macros on fn parameters inside impl items. Standalone
844    /// functions take the per-param syntax directly; impl methods spell the
845    /// same data through `#[miniextendr(match_arg(p1, p2))]`,
846    /// `#[miniextendr(match_arg_several_ok(p))]`,
847    /// `#[miniextendr(choices(p = "a, b"))]`,
848    /// `#[miniextendr(no_default(p))]` and
849    /// `#[miniextendr(formal(p = "p.name"))]` (#1842) on the method attribute.
850    ///
851    /// Uses the shared [`ParamAttrs`](crate::miniextendr_fn::ParamAttrs)
852    /// struct — the `coerce` / `default` fields are unused on the impl path.
853    pub per_param: std::collections::HashMap<String, crate::miniextendr_fn::ParamAttrs>,
854    /// Span of `match_arg(...)` / `choices(...)` for error reporting.
855    pub match_arg_span: Option<proc_macro2::Span>,
856    /// S7-specific method markers. Only consumed by the S7 class generator;
857    /// all other generators ignore this field.
858    pub s7: S7MethodAttrs,
859    // region: Lifecycle support
860    /// Lifecycle specification for deprecation/experimental status on methods.
861    ///
862    /// Use `#[miniextendr(lifecycle = "deprecated")]` or
863    /// `#[miniextendr(lifecycle(stage = "deprecated", when = "0.4.0", with = "new_method()"))]`
864    /// on methods in impl blocks.
865    ///
866    /// # Example
867    /// ```ignore
868    /// #[miniextendr(r6)]
869    /// impl MyType {
870    ///     #[miniextendr(lifecycle = "deprecated")]
871    ///     pub fn old_method(&self) -> i32 { 0 }
872    /// }
873    /// ```
874    pub lifecycle: Option<crate::lifecycle::LifecycleSpec>,
875    /// vctrs protocol method override.
876    ///
877    /// Use `#[miniextendr(vctrs(format))]` to mark a method as implementing a vctrs
878    /// protocol S3 generic. The method will be generated as `format.<class>` instead
879    /// of the default Rust method name.
880    ///
881    /// Supported protocols: format, vec_proxy, vec_proxy_equal, vec_proxy_compare,
882    /// vec_proxy_order, vec_restore, obj_print_data, obj_print_header, obj_print_footer.
883    pub vctrs_protocol: Option<String>,
884    /// Override R method name.
885    ///
886    /// Use `#[miniextendr(r_name = "add_one")]` to give the R method a different name
887    /// than the Rust method. The C symbol is still derived from the Rust name.
888    /// Cannot be combined with `generic = "..."` on the same method.
889    pub r_name: Option<String>,
890    /// Append a fixed suffix to the Rust method name for the R-facing name
891    /// (`#[miniextendr(postfix = "_impl")]` on `fn bump` yields `bump_impl`).
892    /// Exclusive with `r_name` and `generic`; the C symbol is unchanged.
893    pub postfix: Option<String>,
894    /// R code to inject at the very top of the method body (before all built-in checks).
895    pub r_entry: Option<String>,
896    /// R code to inject after all built-in checks, immediately before `.Call()`.
897    pub r_post_checks: Option<String>,
898    /// Register `on.exit()` cleanup code in the R method wrapper.
899    ///
900    /// Short form: `#[miniextendr(r_on_exit = "close(con)")]`
901    /// Long form: `#[miniextendr(r_on_exit(expr = "close(con)", add = false))]`
902    pub r_on_exit: Option<crate::miniextendr_fn::ROnExit>,
903    /// Mark this method as internal: adds `@keywords internal`, suppresses export.
904    ///
905    /// For R6 active bindings this emits a class-level
906    /// `#' @field name (internal)` so the binding stays satisfied for roxygen2
907    /// (which warns on undocumented R6 bindings even when `@field name NULL` is
908    /// present) but is clearly marked internal in the docs.
909    pub internal: bool,
910    /// Suppress export for this method without adding `@keywords internal`.
911    ///
912    /// For R6 active bindings this emits a class-level
913    /// `#' @field name (internal)` (see `internal` above for why we don't use
914    /// roxygen2's `@field name NULL` opt-out).
915    pub noexport: bool,
916}
917
918/// Fully parsed `#[miniextendr]` impl block, ready for code generation.
919///
920/// Contains the type identity, chosen class system, all parsed methods, the original
921/// impl block (with miniextendr attrs stripped for re-emission), and all class-system-specific
922/// configuration options. Created by [`ParsedImpl::parse`] and consumed by the per-class-system
923/// R wrapper generators and [`generate_method_c_wrapper`].
924#[derive(#[automatically_derived]impl ::core::fmt::Debug for ParsedImpl {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            "ParsedImpl type_ident class_system class_name doc_tags methods original_impl cfg_attrs vctrs_attrs r6_inherit r6_portable r6_cloneable r6_lock_objects r6_lock_class s7_parent s7_abstract r_data_accessors field_lookup field_fallback strict preconditions internal noexport constructor_demoted param_warnings class_param_names";
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.type_ident, &self.class_system, &self.class_name,
                        &self.doc_tags, &self.methods, &self.original_impl,
                        &self.cfg_attrs, &self.vctrs_attrs, &self.r6_inherit,
                        &self.r6_portable, &self.r6_cloneable,
                        &self.r6_lock_objects, &self.r6_lock_class, &self.s7_parent,
                        &self.s7_abstract, &self.r_data_accessors,
                        &self.field_lookup, &self.field_fallback, &self.strict,
                        &self.preconditions, &self.internal, &self.noexport,
                        &self.constructor_demoted, &self.param_warnings,
                        &&self.class_param_names];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
    }
}Debug)]
925pub struct ParsedImpl {
926    /// The Rust type name being implemented (e.g., `Counter`).
927    pub type_ident: syn::Ident,
928    /// Which R class system to generate wrappers for.
929    pub class_system: ClassSystem,
930    /// Optional override for the R class name. When `None`, uses `type_ident` as the class name.
931    pub class_name: Option<String>,
932    /// Roxygen tag lines extracted from `///` doc comments on the impl block.
933    /// Used for class-level documentation (e.g., the R6 class docstring or S3 type description).
934    pub doc_tags: Vec<String>,
935    /// All parsed methods in this impl block, in source order.
936    pub methods: Vec<ParsedMethod>,
937    /// The original impl block with `#[miniextendr]` and roxygen attrs stripped.
938    /// Re-emitted as-is so the Rust compiler sees the actual method implementations.
939    pub original_impl: syn::ItemImpl,
940    /// `#[cfg(...)]` attributes from the impl block, propagated to all generated items
941    /// (C wrappers, R wrapper constants, call def arrays) for conditional compilation.
942    pub cfg_attrs: Vec<syn::Attribute>,
943    /// vctrs-specific attributes (only used when class_system is Vctrs)
944    pub vctrs_attrs: VctrsAttrs,
945    /// R6 parent class name for inheritance (e.g., `"ParentClass"`).
946    /// Propagated from [`ImplAttrs::r6_inherit`].
947    pub r6_inherit: Option<String>,
948    /// R6 portable flag. When `Some(true)`, generates a portable R6 class.
949    /// Propagated from [`ImplAttrs::r6_portable`].
950    pub r6_portable: Option<bool>,
951    /// R6 cloneable flag. Controls whether `$clone()` is available on instances.
952    /// Propagated from [`ImplAttrs::r6_cloneable`].
953    pub r6_cloneable: Option<bool>,
954    /// R6 lock_objects flag. When `Some(true)`, prevents adding new fields after creation.
955    /// Propagated from [`ImplAttrs::r6_lock_objects`].
956    pub r6_lock_objects: Option<bool>,
957    /// R6 lock_class flag. When `Some(true)`, prevents modifying the class definition.
958    /// Propagated from [`ImplAttrs::r6_lock_class`].
959    pub r6_lock_class: Option<bool>,
960    /// S7 parent class name for inheritance (e.g., `"ParentClass"`).
961    /// Propagated from [`ImplAttrs::s7_parent`].
962    pub s7_parent: Option<String>,
963    /// When true, marks this as an abstract S7 class that cannot be instantiated.
964    /// Propagated from [`ImplAttrs::s7_abstract`].
965    pub s7_abstract: bool,
966    /// The class-level form of the sidecar `#[r_data]` fields
967    /// (`r_data_accessors`, see [`RDataAccessors`]).
968    /// For R6: active bindings are added via `$set("active", ...)` after class creation.
969    /// For S7: properties are spliced from `.rdata_properties_{Type}` into `new_class()`.
970    /// For S3, S4 and env: `$` / `[[` field methods (`field_syntax.rs`, #1848).
971    pub r_data_accessors: RDataAccessors,
972    /// `s3(r_data_accessors, lookup = "list")`: how the S3 readers look a
973    /// field up (see [`FieldLookup`]).
974    pub field_lookup: FieldLookup,
975    /// `fallback = "Self::f"` (and `fallback_names`) on an S3, S4 or env
976    /// class with `r_data_accessors`: what the readers call for a name no
977    /// field has (see [`FieldFallback`], #2150).
978    pub field_fallback: Option<FieldFallback>,
979    /// Strict conversion mode: methods returning lossy types use checked conversions.
980    pub strict: bool,
981    /// The impl block's `preconditions` / `no_preconditions`, inherited by
982    /// every method wrapper. See [`ImplAttrs::preconditions`].
983    pub preconditions: Option<bool>,
984    /// Mark class as internal: adds `@keywords internal`, suppresses `@export`.
985    pub internal: bool,
986    /// Suppress `@export` without adding `@keywords internal`.
987    pub noexport: bool,
988    /// Generate the block as it reads when another impl block of the type
989    /// has the constructor: the constructor this block would infer stays a
990    /// static method. `expand_impl` sets it for the second rendering of a
991    /// block that infers one ([`ParsedImpl::inferred_constructor`]).
992    pub constructor_demoted: bool,
993    /// Deprecation warnings for `@param` tags found on the impl block.
994    /// Appended to the final TokenStream output.
995    pub param_warnings: proc_macro2::TokenStream,
996    /// Parameter names declared via `@param` in the impl-block doc comments.
997    ///
998    /// For R6 classes, roxygen2 8.0.0 inherits class-level `@param` tags into
999    /// all methods. These are the names that appeared in impl-block-level `@param`
1000    /// tags (extracted before stripping). The R6 generator uses this set to suppress
1001    /// `(no documentation available)` placeholders for covered params and to emit
1002    /// class-level `@param` lines in the class header.
1003    pub class_param_names: std::collections::HashSet<String>,
1004}
1005
1006/// Attributes parsed from `#[miniextendr(...)]` on an impl block.
1007///
1008/// These control which R class system to use, class naming, and
1009/// class-system-specific options (R6 inheritance, S7 parent, vctrs kind, etc.).
1010///
1011/// Parsed by the [`syn::parse::Parse`] implementation which handles all supported
1012/// attribute formats like `#[miniextendr(r6, class = "Custom")]`.
1013#[derive(#[automatically_derived]impl ::core::fmt::Debug for ImplAttrs {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            "ImplAttrs class_system class_name vctrs_attrs r6_inherit r6_portable r6_cloneable r6_lock_objects r6_lock_class s7_parent s7_abstract r_data_accessors field_lookup field_fallback strict method_coerce_default preconditions internal noexport blanket";
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.class_system, &self.class_name, &self.vctrs_attrs,
                        &self.r6_inherit, &self.r6_portable, &self.r6_cloneable,
                        &self.r6_lock_objects, &self.r6_lock_class, &self.s7_parent,
                        &self.s7_abstract, &self.r_data_accessors,
                        &self.field_lookup, &self.field_fallback, &self.strict,
                        &self.method_coerce_default, &self.preconditions,
                        &self.internal, &self.noexport, &&self.blanket];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
    }
}Debug)]
1014pub struct ImplAttrs {
1015    /// Which R class system to generate wrappers for.
1016    /// Defaults to `Env` unless overridden by feature flags (`r6-default`, `s7-default`).
1017    pub class_system: ClassSystem,
1018    /// Optional override for the R class name. When `None`, the Rust type name is used.
1019    pub class_name: Option<String>,
1020    /// vctrs-specific attributes (only used when class_system is Vctrs)
1021    pub vctrs_attrs: VctrsAttrs,
1022    // endregion
1023    // region: R6-specific configuration
1024    /// R6 parent class for inheritance.
1025    /// Use `#[miniextendr(r6(inherit = "ParentClass"))]` to specify the parent.
1026    pub r6_inherit: Option<String>,
1027    /// R6 portable flag. Default TRUE. Set to false for non-portable R6 classes.
1028    pub r6_portable: Option<bool>,
1029    /// R6 cloneable flag. Controls whether `$clone()` is available.
1030    pub r6_cloneable: Option<bool>,
1031    /// R6 lock_objects flag. Controls whether fields can be added after creation.
1032    pub r6_lock_objects: Option<bool>,
1033    /// R6 lock_class flag. Controls whether the class definition can be modified.
1034    pub r6_lock_class: Option<bool>,
1035    // endregion
1036    // region: S7-specific configuration
1037    /// S7 parent class for inheritance.
1038    /// Use `#[miniextendr(s7(parent = "ParentClass"))]` to specify the parent.
1039    pub s7_parent: Option<String>,
1040    /// S7 abstract class flag. Abstract classes cannot be instantiated.
1041    pub s7_abstract: bool,
1042    // endregion
1043    // region: Sidecar integration
1044    /// The class-level form of the `#[r_data]` field accessors
1045    /// (`r6(r_data_accessors)`, `s3(r_data_accessors = "get")`, ...).
1046    /// For R6: active bindings via `$set("active", ...)` post-creation.
1047    /// For S7: properties spliced from `.rdata_properties_{Type}`.
1048    /// For S3, S4 and env: `$` / `[[` field methods (#1848).
1049    pub r_data_accessors: RDataAccessors,
1050    /// How the S3 readers look a field up (`lookup = "list"`, #1921).
1051    pub field_lookup: FieldLookup,
1052    /// What the S3, S4 and env readers call for a name no field has
1053    /// (`fallback = "Self::f"`, #2150).
1054    pub field_fallback: Option<FieldFallback>,
1055    // endregion
1056    // region: Strict conversion mode
1057    /// When true, methods returning lossy types (i64/u64/isize/usize + Vec variants)
1058    /// use `strict::checked_*()` instead of `IntoR::into_sexp()`, panicking on overflow.
1059    pub strict: bool,
1060    // endregion
1061    // region: Argument coercion
1062    /// Whether a method that spells neither `coerce` nor `no_coerce` coerces
1063    /// its arguments: the `coerce-default` feature, read when the impl
1064    /// attribute is parsed, as `strict` is. No impl option sets it. Inherent
1065    /// methods only: a trait impl's methods read the feature themselves
1066    /// (`miniextendr_impl_trait/vtable.rs`).
1067    pub method_coerce_default: bool,
1068    // endregion
1069    // region: Preconditions
1070    /// `Some(false)` drops the R-side type-check guards from the generated
1071    /// method wrappers, `Some(true)` keeps them: those of an inherent impl,
1072    /// including the setter branch of an R6 active binding, and those of a
1073    /// trait impl, including the empty-body (TPIE) form. TryFromSexp still
1074    /// raises on bad input, with the same argument-error condition; the
1075    /// message comes from the conversion. Set by the bare
1076    /// `#[miniextendr(no_preconditions)]` / `preconditions` (the last one
1077    /// written wins). A method's own `preconditions` / `no_preconditions` and
1078    /// each parameter's spelling come first; `None` defers to the crate
1079    /// default, then the `no-preconditions-default` feature
1080    /// (`crate::r_preconditions::resolve_type_checks`).
1081    pub preconditions: Option<bool>,
1082    // endregion
1083    /// Mark class as internal: adds `@keywords internal`, suppresses `@export`.
1084    pub internal: bool,
1085    /// Suppress `@export` without adding `@keywords internal`.
1086    pub noexport: bool,
1087    /// When true on a trait impl (`impl Trait for Type`), the impl block is NOT
1088    /// emitted (a blanket impl already provides it), but C wrappers and R wrappers
1089    /// ARE generated from the method signatures in the body.
1090    pub blanket: bool,
1091}
1092
1093/// The impl doc tags that are class settings rather than class documentation:
1094/// they decide whether every block's members are documented and exported, so
1095/// each impl block of a type repeats them ([`ParsedImpl::class_settings`]).
1096const CLASS_SETTING_TAGS: [&str; 2] = ["noRd", "keywords internal"];
1097
1098/// Every impl-block option, for the "unknown impl block option" errors of the
1099/// bare and the `key = value` forms.
1100const IMPL_OPTIONS_HELP: &str = "env, env(...), r6, r6(...), s3, s3(...), s4, s4(...), s7, \
1101     s7(...), vctrs, vctrs(...) (class system), class = \"...\" (R class name), \
1102     blanket, strict, no_strict, preconditions, no_preconditions, internal, noexport";
1103
1104impl syn::parse::Parse for ImplAttrs {
1105    /// Parses `#[miniextendr(...)]` impl-level options.
1106    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
1107        let mut class_system = if falsecfg!(feature = "r6-default") {
1108            ClassSystem::R6
1109        } else if falsecfg!(feature = "s7-default") {
1110            ClassSystem::S7
1111        } else {
1112            ClassSystem::Env
1113        };
1114        let mut class_system_span: Option<(&str, proc_macro2::Span)> = None;
1115        let mut class_name = None;
1116        let mut vctrs_attrs = VctrsAttrs::default();
1117        let mut r6_inherit = None;
1118        let mut r6_portable = None;
1119        let mut r6_cloneable = None;
1120        let mut r6_lock_objects = None;
1121        let mut r6_lock_class = None;
1122        let mut s7_parent = None;
1123        let mut s7_abstract = false;
1124        let mut r_data_accessors = RDataAccessors::Off;
1125        let mut field_lookup: Option<(FieldLookup, proc_macro2::Span)> = None;
1126        let mut fallback: Option<(syn::LitStr, proc_macro2::Span)> = None;
1127        let mut fallback_names: Option<(syn::LitStr, proc_macro2::Span)> = None;
1128        let mut strict: Option<bool> = None;
1129        let mut preconditions: Option<bool> = None;
1130        let mut internal = false;
1131        let mut noexport = false;
1132        let mut blanket = false;
1133
1134        // Parse attributes. The first identifier can be either:
1135        // - A class system (env, r6, s3, s4, s7, vctrs)
1136        // - A key in a key=value pair (class)
1137        //
1138        // Valid formats:
1139        // - #[miniextendr]
1140        // - #[miniextendr(r6)]
1141        // - #[miniextendr(r6, class = "CustomName")]
1142        // - #[miniextendr(vctrs)]
1143        // - #[miniextendr(vctrs(kind = "rcrd", base = "double", abbr = "my_abbr"))]
1144        while !input.is_empty() {
1145            let ident: syn::Ident = input.parse()?;
1146            let ident_str = ident.to_string();
1147
1148            // Check if this is a key=value pair
1149            if input.peek(::syn::token::Eqsyn::Token![=]) {
1150                let _: ::syn::token::Eqsyn::Token![=] = input.parse()?;
1151                match ident_str.as_str() {
1152                    "class" => {
1153                        let value: syn::LitStr = input.parse()?;
1154                        class_name = Some(value.value());
1155                    }
1156                    _ => {
1157                        return Err(syn::Error::new(
1158                            ident.span(),
1159                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown impl block option `{0}`; expected one of: {1}",
                ident_str, IMPL_OPTIONS_HELP))
    })format!(
1160                                "unknown impl block option `{ident_str}`; expected one of: \
1161                                 {IMPL_OPTIONS_HELP}"
1162                            ),
1163                        ));
1164                    }
1165                }
1166            } else if ident_str == "vctrs" {
1167                // vctrs class system with optional nested attributes
1168                if let Some((prev_name, _prev_span)) = class_system_span {
1169                    return Err(syn::Error::new(
1170                        ident.span(),
1171                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("multiple class systems specified (`{0}` and `{1}`); use only one of: env, r6, s3, s4, s7, vctrs",
                prev_name, ident_str))
    })format!(
1172                            "multiple class systems specified (`{}` and `{}`); use only one of: env, r6, s3, s4, s7, vctrs",
1173                            prev_name, ident_str
1174                        ),
1175                    ));
1176                }
1177                class_system_span = Some(("vctrs", ident.span()));
1178                class_system = ClassSystem::Vctrs;
1179
1180                // Check for nested vctrs options: vctrs(kind = "rcrd", base = "double", ...)
1181                if input.peek(syn::token::Paren) {
1182                    let content;
1183                    match ::syn::__private::parse_parens(&input) {
    ::syn::__private::Ok(parens) => {
        content = parens.content;
        _ = content;
        parens.token
    }
    ::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
};syn::parenthesized!(content in input);
1184
1185                    while !content.is_empty() {
1186                        let key: syn::Ident = content.parse()?;
1187                        if key == "r_data_accessors" {
1188                            return Err(syn::Error::new(
1189                                key.span(),
1190                                "vctrs classes have no `r_data_accessors`: a vctr is an R \
1191                                 vector with no external pointer, and vctrs keeps `$` on a \
1192                                 record for its own fields. Use the standalone \
1193                                 `Type_get_<field>()` / `Type_set_<field>()`",
1194                            ));
1195                        }
1196                        if key == "fallback" || key == "fallback_names" {
1197                            return Err(no_field_fallback_error(&key, "vctrs"));
1198                        }
1199                        let _: ::syn::token::Eqsyn::Token![=] = content.parse()?;
1200                        let key_str = key.to_string();
1201
1202                        match key_str.as_str() {
1203                            "kind" => {
1204                                let value: syn::LitStr = content.parse()?;
1205                                vctrs_attrs.kind = value
1206                                    .value()
1207                                    .parse()
1208                                    .map_err(|e| syn::Error::new(value.span(), e))?;
1209                            }
1210                            "base" => {
1211                                let value: syn::LitStr = content.parse()?;
1212                                vctrs_attrs.base = Some(value.value());
1213                            }
1214                            "inherit_base_type" => {
1215                                let value: syn::LitBool = content.parse()?;
1216                                vctrs_attrs.inherit_base_type = Some(value.value());
1217                            }
1218                            "ptype" => {
1219                                let value: syn::LitStr = content.parse()?;
1220                                vctrs_attrs.ptype = Some(value.value());
1221                            }
1222                            "abbr" => {
1223                                let value: syn::LitStr = content.parse()?;
1224                                vctrs_attrs.abbr = Some(value.value());
1225                            }
1226                            _ => {
1227                                return Err(syn::Error::new(
1228                                    key.span(),
1229                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown vctrs option: {0} (expected kind, base, inherit_base_type, ptype, abbr)",
                key_str))
    })format!(
1230                                        "unknown vctrs option: {} (expected kind, base, inherit_base_type, ptype, abbr)",
1231                                        key_str
1232                                    ),
1233                                ));
1234                            }
1235                        }
1236
1237                        // Consume trailing comma if present
1238                        if content.peek(::syn::token::Commasyn::Token![,]) {
1239                            let _: ::syn::token::Commasyn::Token![,] = content.parse()?;
1240                        }
1241                    }
1242                }
1243            } else if ident_str == "r6" {
1244                // R6 class system with optional nested attributes
1245                // r6 or r6(inherit = "Parent", portable = false, cloneable, lock_class)
1246                if let Some((prev_name, _prev_span)) = class_system_span {
1247                    return Err(syn::Error::new(
1248                        ident.span(),
1249                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("multiple class systems specified (`{0}` and `{1}`); use only one of: env, r6, s3, s4, s7, vctrs",
                prev_name, ident_str))
    })format!(
1250                            "multiple class systems specified (`{}` and `{}`); use only one of: env, r6, s3, s4, s7, vctrs",
1251                            prev_name, ident_str
1252                        ),
1253                    ));
1254                }
1255                class_system_span = Some(("r6", ident.span()));
1256                class_system = ClassSystem::R6;
1257
1258                if input.peek(syn::token::Paren) {
1259                    let content;
1260                    match ::syn::__private::parse_parens(&input) {
    ::syn::__private::Ok(parens) => {
        content = parens.content;
        _ = content;
        parens.token
    }
    ::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
};syn::parenthesized!(content in input);
1261
1262                    while !content.is_empty() {
1263                        let key: syn::Ident = content.parse()?;
1264                        let key_str = key.to_string();
1265
1266                        match key_str.as_str() {
1267                            "inherit" => {
1268                                let _: ::syn::token::Eqsyn::Token![=] = content.parse()?;
1269                                let value: syn::LitStr = content.parse()?;
1270                                r6_inherit = Some(value.value());
1271                            }
1272                            "portable" => {
1273                                if content.peek(::syn::token::Eqsyn::Token![=]) {
1274                                    let _: ::syn::token::Eqsyn::Token![=] = content.parse()?;
1275                                    let value: syn::LitBool = content.parse()?;
1276                                    r6_portable = Some(value.value());
1277                                } else {
1278                                    r6_portable = Some(true);
1279                                }
1280                            }
1281                            "cloneable" => {
1282                                if content.peek(::syn::token::Eqsyn::Token![=]) {
1283                                    let _: ::syn::token::Eqsyn::Token![=] = content.parse()?;
1284                                    let value: syn::LitBool = content.parse()?;
1285                                    r6_cloneable = Some(value.value());
1286                                } else {
1287                                    r6_cloneable = Some(true);
1288                                }
1289                            }
1290                            "lock_objects" => {
1291                                if content.peek(::syn::token::Eqsyn::Token![=]) {
1292                                    let _: ::syn::token::Eqsyn::Token![=] = content.parse()?;
1293                                    let value: syn::LitBool = content.parse()?;
1294                                    r6_lock_objects = Some(value.value());
1295                                } else {
1296                                    r6_lock_objects = Some(true);
1297                                }
1298                            }
1299                            "lock_class" => {
1300                                if content.peek(::syn::token::Eqsyn::Token![=]) {
1301                                    let _: ::syn::token::Eqsyn::Token![=] = content.parse()?;
1302                                    let value: syn::LitBool = content.parse()?;
1303                                    r6_lock_class = Some(value.value());
1304                                } else {
1305                                    r6_lock_class = Some(true);
1306                                }
1307                            }
1308                            "r_data_accessors" => {
1309                                r_data_accessors =
1310                                    parse_r_data_accessors_value(&content, &key, ClassSystem::R6)?;
1311                            }
1312                            "fallback" | "fallback_names" => {
1313                                return Err(no_field_fallback_error(&key, "r6"));
1314                            }
1315                            _ => {
1316                                return Err(syn::Error::new(
1317                                    key.span(),
1318                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown r6 option: {0} (expected inherit, portable, cloneable, lock_objects, lock_class, r_data_accessors)",
                key_str))
    })format!(
1319                                        "unknown r6 option: {} (expected inherit, portable, cloneable, lock_objects, lock_class, r_data_accessors)",
1320                                        key_str
1321                                    ),
1322                                ));
1323                            }
1324                        }
1325
1326                        // Consume trailing comma if present
1327                        if content.peek(::syn::token::Commasyn::Token![,]) {
1328                            let _: ::syn::token::Commasyn::Token![,] = content.parse()?;
1329                        }
1330                    }
1331                }
1332            } else if ident_str == "s7" {
1333                // S7 class system with optional nested attributes
1334                // s7 or s7(parent = "Parent", abstract)
1335                if let Some((prev_name, _prev_span)) = class_system_span {
1336                    return Err(syn::Error::new(
1337                        ident.span(),
1338                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("multiple class systems specified (`{0}` and `{1}`); use only one of: env, r6, s3, s4, s7, vctrs",
                prev_name, ident_str))
    })format!(
1339                            "multiple class systems specified (`{}` and `{}`); use only one of: env, r6, s3, s4, s7, vctrs",
1340                            prev_name, ident_str
1341                        ),
1342                    ));
1343                }
1344                class_system_span = Some(("s7", ident.span()));
1345                class_system = ClassSystem::S7;
1346
1347                if input.peek(syn::token::Paren) {
1348                    let content;
1349                    match ::syn::__private::parse_parens(&input) {
    ::syn::__private::Ok(parens) => {
        content = parens.content;
        _ = content;
        parens.token
    }
    ::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
};syn::parenthesized!(content in input);
1350
1351                    while !content.is_empty() {
1352                        // Use parse_any to accept `abstract` (a reserved keyword)
1353                        use syn::ext::IdentExt;
1354                        let key = syn::Ident::parse_any(&content)?;
1355                        let key_str = key.to_string();
1356
1357                        match key_str.as_str() {
1358                            "parent" => {
1359                                let _: ::syn::token::Eqsyn::Token![=] = content.parse()?;
1360                                let value: syn::LitStr = content.parse()?;
1361                                s7_parent = Some(value.value());
1362                            }
1363                            "abstract" => {
1364                                if content.peek(::syn::token::Eqsyn::Token![=]) {
1365                                    let _: ::syn::token::Eqsyn::Token![=] = content.parse()?;
1366                                    let value: syn::LitBool = content.parse()?;
1367                                    s7_abstract = value.value();
1368                                } else {
1369                                    s7_abstract = true;
1370                                }
1371                            }
1372                            "r_data_accessors" => {
1373                                r_data_accessors =
1374                                    parse_r_data_accessors_value(&content, &key, ClassSystem::S7)?;
1375                            }
1376                            "fallback" | "fallback_names" => {
1377                                return Err(no_field_fallback_error(&key, "s7"));
1378                            }
1379                            _ => {
1380                                return Err(syn::Error::new(
1381                                    key.span(),
1382                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown s7 option: {0} (expected parent, abstract, r_data_accessors)",
                key_str))
    })format!(
1383                                        "unknown s7 option: {} (expected parent, abstract, r_data_accessors)",
1384                                        key_str
1385                                    ),
1386                                ));
1387                            }
1388                        }
1389
1390                        // Consume trailing comma if present
1391                        if content.peek(::syn::token::Commasyn::Token![,]) {
1392                            let _: ::syn::token::Commasyn::Token![,] = content.parse()?;
1393                        }
1394                    }
1395                }
1396            } else if ident_str == "blanket" {
1397                blanket = true;
1398            } else if ident_str == "strict" {
1399                strict = Some(true);
1400            } else if ident_str == "no_strict" {
1401                strict = Some(false);
1402            } else if ident_str == "preconditions" {
1403                preconditions = Some(true);
1404            } else if ident_str == "no_preconditions" {
1405                preconditions = Some(false);
1406            } else if ident_str == "internal" {
1407                internal = true;
1408            } else if ident_str == "noexport" {
1409                noexport = true;
1410            } else {
1411                // A class system identifier, or no option at all.
1412                let parsed_system: ClassSystem = ident_str.parse().map_err(|_| {
1413                    syn::Error::new(
1414                        ident.span(),
1415                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown impl block option `{0}`; expected one of: {1}",
                ident_str, IMPL_OPTIONS_HELP))
    })format!(
1416                            "unknown impl block option `{ident_str}`; expected one of: \
1417                             {IMPL_OPTIONS_HELP}"
1418                        ),
1419                    )
1420                })?;
1421                if let Some((prev_name, _prev_span)) = class_system_span {
1422                    return Err(syn::Error::new(
1423                        ident.span(),
1424                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("multiple class systems specified (`{0}` and `{1}`); use only one of: env, r6, s3, s4, s7, vctrs",
                prev_name, ident_str))
    })format!(
1425                            "multiple class systems specified (`{}` and `{}`); use only one of: env, r6, s3, s4, s7, vctrs",
1426                            prev_name, ident_str
1427                        ),
1428                    ));
1429                }
1430                class_system_span = Some((
1431                    match parsed_system {
1432                        ClassSystem::Env => "env",
1433                        ClassSystem::R6 => "r6",
1434                        ClassSystem::S3 => "s3",
1435                        ClassSystem::S4 => "s4",
1436                        ClassSystem::S7 => "s7",
1437                        ClassSystem::Vctrs => "vctrs",
1438                    },
1439                    ident.span(),
1440                ));
1441                class_system = parsed_system;
1442
1443                // `s3(...)`, `s4(...)`, `env(...)`: the field syntax option.
1444                if input.peek(syn::token::Paren) {
1445                    let content;
1446                    match ::syn::__private::parse_parens(&input) {
    ::syn::__private::Ok(parens) => {
        content = parens.content;
        _ = content;
        parens.token
    }
    ::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
};syn::parenthesized!(content in input);
1447                    while !content.is_empty() {
1448                        let key: syn::Ident = content.parse()?;
1449                        if key == "lookup" && parsed_system == ClassSystem::S3 {
1450                            if field_lookup.is_some() {
1451                                return Err(syn::Error::new(key.span(), "`lookup` is given twice"));
1452                            }
1453                            let _: ::syn::token::Eqsyn::Token![=] = content.parse()?;
1454                            let value: syn::LitStr = content.parse()?;
1455                            let lookup = match value.value().as_str() {
1456                                "strict" => FieldLookup::Strict,
1457                                "list" => FieldLookup::List,
1458                                other => {
1459                                    return Err(syn::Error::new(
1460                                        value.span(),
1461                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown `lookup` value \"{0}\"; expected \"strict\" (exact names and whole-number positions, the default) or \"list\" (an unknown name or `NA` reads `NULL`)",
                other))
    })format!(
1462                                            "unknown `lookup` value \"{other}\"; expected \
1463                                             \"strict\" (exact names and whole-number \
1464                                             positions, the default) or \"list\" (an unknown \
1465                                             name or `NA` reads `NULL`)"
1466                                        ),
1467                                    ));
1468                                }
1469                            };
1470                            field_lookup = Some((lookup, key.span()));
1471                        } else if key == "r_data_accessors" {
1472                            r_data_accessors =
1473                                parse_r_data_accessors_value(&content, &key, parsed_system)?;
1474                        } else if key == "fallback" || key == "fallback_names" {
1475                            let slot = if key == "fallback" {
1476                                &mut fallback
1477                            } else {
1478                                &mut fallback_names
1479                            };
1480                            if slot.is_some() {
1481                                return Err(syn::Error::new(
1482                                    key.span(),
1483                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is given twice", key))
    })format!("`{key}` is given twice"),
1484                                ));
1485                            }
1486                            *slot = Some((parse_fallback_value(&content, &key)?, key.span()));
1487                        } else {
1488                            let lookup = if parsed_system == ClassSystem::S3 {
1489                                ", lookup = \"list\""
1490                            } else {
1491                                ""
1492                            };
1493                            return Err(syn::Error::new(
1494                                key.span(),
1495                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown {0} option: {1} (expected r_data_accessors, or r_data_accessors = \"get\" for getters only, or r_data_accessors = \"read_only\" for setters that refuse{2}, fallback = \"Self::f\", fallback_names = \"Self::g\")",
                ident_str, key, lookup))
    })format!(
1496                                    "unknown {ident_str} option: {key} (expected \
1497                                     r_data_accessors, or r_data_accessors = \"get\" for \
1498                                     getters only, or r_data_accessors = \"read_only\" for \
1499                                     setters that refuse{lookup}, fallback = \"Self::f\", \
1500                                     fallback_names = \"Self::g\")"
1501                                ),
1502                            ));
1503                        }
1504                        if content.peek(::syn::token::Commasyn::Token![,]) {
1505                            let _: ::syn::token::Commasyn::Token![,] = content.parse()?;
1506                        }
1507                    }
1508                    if let Some((_, span)) = field_lookup
1509                        && !r_data_accessors.enabled()
1510                    {
1511                        return Err(syn::Error::new(
1512                            span,
1513                            "`lookup` sets how the readers of `s3(r_data_accessors)` look a \
1514                             field up; add `r_data_accessors` (or `r_data_accessors = \"get\"`)",
1515                        ));
1516                    }
1517                    if let Some((_, span)) = &fallback
1518                        && !r_data_accessors.enabled()
1519                    {
1520                        return Err(syn::Error::new(
1521                            *span,
1522                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`fallback` answers the names no field has for the `$` / `[[` readers of `{0}(r_data_accessors)`; add `r_data_accessors` (or `r_data_accessors = \"get\"`)",
                ident_str))
    })format!(
1523                                "`fallback` answers the names no field has for the `$` / `[[` \
1524                                 readers of `{ident_str}(r_data_accessors)`; add \
1525                                 `r_data_accessors` (or `r_data_accessors = \"get\"`)"
1526                            ),
1527                        ));
1528                    }
1529                    if let Some((_, span)) = &fallback_names
1530                        && fallback.is_none()
1531                    {
1532                        return Err(syn::Error::new(
1533                            *span,
1534                            "`fallback_names` lists the names `fallback` answers, for \
1535                             `.DollarNames()`; add `fallback = \"Self::f\"`",
1536                        ));
1537                    }
1538                }
1539            }
1540
1541            // Consume trailing comma if present
1542            if input.peek(::syn::token::Commasyn::Token![,]) {
1543                let _: ::syn::token::Commasyn::Token![,] = input.parse()?;
1544            }
1545        }
1546
1547        Ok(ImplAttrs {
1548            class_system,
1549            class_name,
1550            vctrs_attrs,
1551            r6_inherit,
1552            r6_portable,
1553            r6_cloneable,
1554            r6_lock_objects,
1555            r6_lock_class,
1556            s7_parent,
1557            s7_abstract,
1558            r_data_accessors,
1559            field_lookup: field_lookup.map(|(lookup, _)| lookup).unwrap_or_default(),
1560            field_fallback: fallback.map(|(get, _)| FieldFallback {
1561                get,
1562                names: fallback_names.map(|(names, _)| names),
1563            }),
1564            strict: strict.unwrap_or(falsecfg!(feature = "strict-default")),
1565            method_coerce_default: falsecfg!(feature = "coerce-default"),
1566            preconditions,
1567            internal,
1568            noexport,
1569            blanket,
1570        })
1571    }
1572}
1573
1574impl ParsedMethod {
1575    /// Validate method attributes for the given class system.
1576    /// Returns an error if unsupported attributes are used.
1577    fn validate_method_attrs(
1578        attrs: &MethodAttrs,
1579        class_system: ClassSystem,
1580        span: proc_macro2::Span,
1581    ) -> syn::Result<()> {
1582        if (attrs.receiver.is_some() || attrs.no_dispatch_dots)
1583            && (!#[allow(non_exhaustive_omitted_patterns)] match class_system {
    ClassSystem::S3 | ClassSystem::S4 => true,
    _ => false,
}matches!(class_system, ClassSystem::S3 | ClassSystem::S4)
1584                || attrs.generic.is_none())
1585        {
1586            return Err(syn::Error::new(
1587                span,
1588                "`receiver` and `no_dots` require an explicit S3/S4 `generic = \"...\"`",
1589            ));
1590        }
1591
1592        // R6-only boolean markers must not appear under any other class system.
1593        if class_system != ClassSystem::R6 {
1594            if attrs.r6.active {
1595                return Err(syn::Error::new(
1596                    attrs.r6.active_span.unwrap_or(span),
1597                    "`active` is only valid for R6 class systems",
1598                ));
1599            }
1600            if attrs.r6.private {
1601                return Err(syn::Error::new(
1602                    attrs.r6.private_span.unwrap_or(span),
1603                    "`private` is only valid for R6 class systems",
1604                ));
1605            }
1606            if attrs.r6.finalize {
1607                return Err(syn::Error::new(
1608                    attrs.r6.finalize_span.unwrap_or(span),
1609                    "`finalize` is only valid for R6 class systems",
1610                ));
1611            }
1612            if attrs.r6.deep_clone {
1613                return Err(syn::Error::new(
1614                    attrs.r6.deep_clone_span.unwrap_or(span),
1615                    "`deep_clone` is only valid for R6 class systems",
1616                ));
1617            }
1618        }
1619
1620        // convert_from and convert_to are mutually exclusive on the same method
1621        // - convert_from expects a static method (no &self, takes source type)
1622        // - convert_to expects an instance method (&self, returns target type)
1623        if attrs.s7.convert_from.is_some() && attrs.s7.convert_to.is_some() {
1624            return Err(syn::Error::new(
1625                span,
1626                "cannot specify both `convert_from` and `convert_to` on the same method; \
1627                 convert_from is for static methods, convert_to is for instance methods",
1628            ));
1629        }
1630
1631        // postfix derives the R name from the Rust name; it cannot combine
1632        // with another naming source.
1633        if attrs.postfix.is_some() && attrs.r_name.is_some() {
1634            return Err(syn::Error::new(
1635                span,
1636                "`postfix` and `r_name` both set the R method name; use one of them.",
1637            ));
1638        }
1639        if attrs.postfix.is_some() && attrs.generic.is_some() {
1640            return Err(syn::Error::new(
1641                span,
1642                "`postfix` and `generic` cannot be used on the same method. \
1643                 Generic dispatch names the R method after the generic.",
1644            ));
1645        }
1646
1647        if attrs.serialize && (attrs.unwrap_in_r || attrs.serde_error.is_some()) {
1648            return Err(syn::Error::new(
1649                proc_macro2::Span::call_site(),
1650                "`serialize` cannot be combined with `unwrap_in_r` or `serde_error`: it serializes the complete return value, including any Result variant",
1651            ));
1652        }
1653
1654        // serde_error classes the raised condition; unwrap_in_r never raises.
1655        if attrs.serde_error.is_some() && attrs.unwrap_in_r {
1656            return Err(syn::Error::new(
1657                span,
1658                "`serde_error` cannot be used with `unwrap_in_r`: `unwrap_in_r` returns the \
1659                 `Result` to R as a value, so there is no raised condition to class.",
1660            ));
1661        }
1662
1663        // r_name and generic are mutually exclusive
1664        if attrs.r_name.is_some() && attrs.generic.is_some() {
1665            return Err(syn::Error::new(
1666                span,
1667                "`r_name` and `generic` cannot be used on the same method. \
1668                 Use `r_name` for a simple rename, or `generic`/`class` for S3/S4/S7 generic dispatch.",
1669            ));
1670        }
1671
1672        Ok(())
1673    }
1674
1675    /// Parse method attributes in #[miniextendr(class_system(...))] format.
1676    ///
1677    /// Supported formats:
1678    /// - `#[miniextendr(r6(ignore, constructor, finalize, private, generic = "...")]`
1679    /// - `#[miniextendr(s3(ignore, constructor, generic = "..."))]`
1680    /// - `#[miniextendr(s7(ignore, constructor, generic = "..."))]`
1681    /// - etc.
1682    ///
1683    /// `coerce_default` is the `coerce` of a method that spells neither
1684    /// `coerce` nor `no_coerce` (`ImplAttrs::method_coerce_default`).
1685    fn parse_method_attrs(
1686        attrs: &[syn::Attribute],
1687        coerce_default: bool,
1688    ) -> syn::Result<MethodAttrs> {
1689        use syn::spanned::Spanned;
1690        let mut method_attrs = MethodAttrs::default();
1691        // Use Option<bool> for fields that support feature defaults.
1692        let mut coerce: Option<bool> = None;
1693
1694        for attr in attrs {
1695            // Parse new-style #[miniextendr(class_system(...))] attributes
1696            if !attr.path().is_ident("miniextendr") {
1697                continue;
1698            }
1699
1700            // Parse the nested content: miniextendr(class_system(options...)) or miniextendr(defaults(...))
1701            attr.parse_nested_meta(|meta| {
1702                // Note: "vctrs" is handled separately below for protocol method overrides
1703                let is_class_meta = meta.path.is_ident("env")
1704                    || meta.path.is_ident("r6")
1705                    || meta.path.is_ident("s7")
1706                    || meta.path.is_ident("s3")
1707                    || meta.path.is_ident("s4");
1708
1709                if is_class_meta {
1710                    // Parse the inner options: r6(ignore, constructor, ...)
1711                    meta.parse_nested_meta(|inner| {
1712                        if inner.path.is_ident("ignore") {
1713                            method_attrs.ignore = true;
1714                        } else if inner.path.is_ident("invisible") {
1715                            method_attrs.force_invisible = Some(true);
1716                        } else if inner.path.is_ident("visible") {
1717                            method_attrs.force_invisible = Some(false);
1718                        } else if inner.path.is_ident("constructor") {
1719                            method_attrs.constructor = true;
1720                        } else if inner.path.is_ident("finalize") {
1721                            method_attrs.r6.finalize = true;
1722                            method_attrs.r6.finalize_span = Some(inner.path.span());
1723                        } else if inner.path.is_ident("private") {
1724                            method_attrs.r6.private = true;
1725                            method_attrs.r6.private_span = Some(inner.path.span());
1726                        } else if inner.path.is_ident("active") {
1727                            method_attrs.r6.active = true;
1728                            method_attrs.r6.active_span = Some(inner.path.span());
1729                        } else if inner.path.is_ident("setter") {
1730                            // Active binding setter: works for both R6 and S7
1731                            method_attrs.r6.setter = true;
1732                            method_attrs.s7.setter = true;
1733                        } else if inner.path.is_ident("check_interrupt") {
1734                            method_attrs.check_interrupt = true;
1735                        } else if inner.path.is_ident("coerce") {
1736                            coerce = Some(true);
1737                        } else if inner.path.is_ident("no_coerce") {
1738                            coerce = Some(false);
1739                        } else if inner.path.is_ident("rng") {
1740                            if inner.input.peek(syn::token::Paren) {
1741                                return crate::miniextendr_fn::refuse_rng_seed_on_method(
1742                                    &inner,
1743                                    "an impl method",
1744                                );
1745                            }
1746                            method_attrs.rng = true;
1747                        } else if inner.path.is_ident("unwrap_in_r") {
1748                            method_attrs.unwrap_in_r = true;
1749                        } else if inner.path.is_ident("wrap") {
1750                            let value: syn::LitStr = inner.value()?.parse()?;
1751                            method_attrs.wrap = Some(crate::return_wrap::parse_system(&value)?);
1752                        } else if inner.path.is_ident("serialize") {
1753                            method_attrs.serialize = true;
1754                        } else if inner.path.is_ident("serde_error") {
1755                            method_attrs.serde_error =
1756                                Some(crate::miniextendr_fn::parse_serde_error_nested(&inner)?);
1757                        } else if inner.path.is_ident("generic") {
1758                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1759                            let value: syn::LitStr = inner.input.parse()?;
1760                            method_attrs.generic = Some(crate::naming::parse_generic(&value)?);
1761                        } else if inner.path.is_ident("receiver") {
1762                            let value: syn::LitStr = inner.value()?.parse()?;
1763                            let name = crate::naming::parse_r_receiver(&value)?;
1764                            if method_attrs.receiver.replace(name).is_some() {
1765                                return Err(inner.error("receiver may be specified only once"));
1766                            }
1767                        } else if inner.path.is_ident("class") {
1768                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1769                            let value: syn::LitStr = inner.input.parse()?;
1770                            method_attrs.class = Some(value.value());
1771                        } else if inner.path.is_ident("getter") {
1772                            method_attrs.s7.getter = true;
1773                        } else if inner.path.is_ident("validate") {
1774                            method_attrs.s7.validate = true;
1775                        } else if inner.path.is_ident("prop") {
1776                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1777                            let value: syn::LitStr = inner.input.parse()?;
1778                            let prop_value = value.value();
1779                            // Set both S7 and R6 prop - the class system will use the appropriate one
1780                            method_attrs.s7.prop = Some(prop_value.clone());
1781                            method_attrs.r6.prop = Some(prop_value);
1782                        } else if inner.path.is_ident("default") {
1783                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1784                            let value: syn::LitStr = inner.input.parse()?;
1785                            method_attrs.s7.default = Some(value.value());
1786                        } else if inner.path.is_ident("required") {
1787                            method_attrs.s7.required = true;
1788                        } else if inner.path.is_ident("frozen") {
1789                            method_attrs.s7.frozen = true;
1790                        } else if inner.path.is_ident("deprecated") {
1791                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1792                            let value: syn::LitStr = inner.input.parse()?;
1793                            method_attrs.s7.deprecated = Some(value.value());
1794                        } else if inner.path.is_ident("no_dots") {
1795                            if meta.path.is_ident("s3") || meta.path.is_ident("s4") {
1796                                method_attrs.no_dispatch_dots = true;
1797                            } else {
1798                                method_attrs.s7.no_dots = true;
1799                            }
1800                        } else if inner.path.is_ident("dispatch") {
1801                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1802                            let value: syn::LitStr = inner.input.parse()?;
1803                            method_attrs.s7.dispatch = Some(value.value());
1804                        } else if inner.path.is_ident("fallback") {
1805                            method_attrs.s7.fallback = true;
1806                        } else if inner.path.is_ident("no_shortcut") {
1807                            method_attrs.s7.no_shortcut = true;
1808                        } else if inner.path.is_ident("convert_from") {
1809                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1810                            let value: syn::LitStr = inner.input.parse()?;
1811                            method_attrs.s7.convert_from = Some(value.value());
1812                        } else if inner.path.is_ident("convert_to") {
1813                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1814                            let value: syn::LitStr = inner.input.parse()?;
1815                            method_attrs.s7.convert_to = Some(value.value());
1816                        } else if inner.path.is_ident("deep_clone") {
1817                            method_attrs.r6.deep_clone = true;
1818                            method_attrs.r6.deep_clone_span = Some(inner.path.span());
1819                        } else if inner.path.is_ident("r_name") {
1820                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1821                            let value: syn::LitStr = inner.input.parse()?;
1822                            let val = value.value();
1823                            if val.is_empty() {
1824                                return Err(syn::Error::new_spanned(value, "r_name must not be empty"));
1825                            }
1826                            method_attrs.r_name = Some(val);
1827                        } else if inner.path.is_ident("postfix") {
1828                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1829                            let value: syn::LitStr = inner.input.parse()?;
1830                            let val = value.value();
1831                            crate::miniextendr_fn::validate_postfix(&val, &value)?;
1832                            method_attrs.postfix = Some(val);
1833                        } else if inner.path.is_ident("call") {
1834                            return Err(inner.error(
1835                                "`call = caller` is only supported on standalone `#[miniextendr]` \
1836                                 functions (the internal-entry-point pattern); class methods keep \
1837                                 their own call attribution",
1838                            ));
1839                        } else if inner.path.is_ident("r_entry") {
1840                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1841                            let value: syn::LitStr = inner.input.parse()?;
1842                            method_attrs.r_entry = Some(value.value());
1843                        } else if inner.path.is_ident("r_post_checks") {
1844                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1845                            let value: syn::LitStr = inner.input.parse()?;
1846                            method_attrs.r_post_checks = Some(value.value());
1847                        } else if inner.path.is_ident("r_on_exit") {
1848                            if inner.input.peek(::syn::token::Eqsyn::Token![=]) {
1849                                // Short form: r_on_exit = "expr"
1850                                let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1851                                let value: syn::LitStr = inner.input.parse()?;
1852                                method_attrs.r_on_exit = Some(crate::miniextendr_fn::ROnExit {
1853                                    expr: value.value(),
1854                                    add: true,
1855                                    after: true,
1856                                });
1857                            } else {
1858                                // Long form: r_on_exit(expr = "...", add = false, after = false)
1859                                let mut expr = None;
1860                                let mut add = true;
1861                                let mut after = true;
1862                                inner.parse_nested_meta(|meta| {
1863                                    if meta.path.is_ident("expr") {
1864                                        let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
1865                                        let value: syn::LitStr = meta.input.parse()?;
1866                                        expr = Some(value.value());
1867                                    } else if meta.path.is_ident("add") {
1868                                        let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
1869                                        let value: syn::LitBool = meta.input.parse()?;
1870                                        add = value.value;
1871                                    } else if meta.path.is_ident("after") {
1872                                        let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
1873                                        let value: syn::LitBool = meta.input.parse()?;
1874                                        after = value.value;
1875                                    } else {
1876                                        return Err(meta.error(
1877                                            "unknown r_on_exit option; expected `expr`, `add`, or `after`",
1878                                        ));
1879                                    }
1880                                    Ok(())
1881                                })?;
1882                                let expr = expr.ok_or_else(|| {
1883                                    inner.error("r_on_exit(...) requires `expr = \"...\"` specifying the R expression")
1884                                })?;
1885                                method_attrs.r_on_exit = Some(crate::miniextendr_fn::ROnExit { expr, add, after });
1886                            }
1887                        } else {
1888                            return Err(inner.error(
1889                                "unknown method option; expected one of: ignore, constructor, finalize, private, active, check_interrupt, coerce, no_coerce, rng, unwrap_in_r, serialize, serde_error, generic, class, getter, setter, validate, prop, default, required, frozen, deprecated, no_dots, dispatch, fallback, no_shortcut, convert_from, convert_to, deep_clone, r_on_exit, r_name, postfix, invisible, visible"
1890                            ));
1891                        }
1892                        Ok(())
1893                    })?;
1894                } else if meta.path.is_ident("defaults") {
1895                    // Capture span for error reporting
1896                    method_attrs.defaults_span = Some(meta.path.span());
1897                    // Parse defaults(param = "value", param2 = "value2", ...)
1898                    meta.parse_nested_meta(|inner| {
1899                        // Get parameter name
1900                        let param_name = inner
1901                            .path
1902                            .get_ident()
1903                            .ok_or_else(|| inner.error("expected parameter name"))?
1904                            .to_string();
1905                        // Parse = "value"
1906                        let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1907                        let value: syn::LitStr = inner.input.parse()?;
1908                        method_attrs.defaults.insert(param_name, value.value());
1909                        Ok(())
1910                    })?;
1911                } else if meta.path.is_ident("preconditions")
1912                    || meta.path.is_ident("no_preconditions")
1913                {
1914                    // Bare: the whole method keeps / drops its type-derived
1915                    // R-side checks. `preconditions(p, q)` /
1916                    // `no_preconditions(p)`: those parameters. Last one wins.
1917                    let keep = meta.path.is_ident("preconditions");
1918                    if meta.input.peek(syn::token::Paren) {
1919                        method_attrs.match_arg_span.get_or_insert(meta.path.span());
1920                        crate::miniextendr_fn::parse_method_preconditions(
1921                            &meta,
1922                            &mut method_attrs.per_param,
1923                            keep,
1924                        )?;
1925                    } else {
1926                        method_attrs.preconditions = Some(keep);
1927                    }
1928                } else if meta.path.is_ident("convert") {
1929                    method_attrs.match_arg_span.get_or_insert(meta.path.span());
1930                    crate::miniextendr_fn::parse_method_convert(&meta, &mut method_attrs.per_param)?;
1931                } else if meta.path.is_ident("no_na") {
1932                    // `no_na(p, q(message = "..."))` — R-side `!anyNA(p)` checks.
1933                    method_attrs.match_arg_span.get_or_insert(meta.path.span());
1934                    crate::miniextendr_fn::parse_method_no_na(&meta, &mut method_attrs.per_param)?;
1935                } else if let Some(check) = crate::miniextendr_fn::ClassCheck::of(&meta.path) {
1936                    // `inherits(p = "cls_a, cls_b", q(class = "cls", message = "..."))` —
1937                    // R-side `inherits(p, c(...))` checks; `not_inherits(...)` the
1938                    // same shape, `!inherits(p, c(...))`.
1939                    method_attrs.match_arg_span.get_or_insert(meta.path.span());
1940                    crate::miniextendr_fn::parse_method_class_check(
1941                        &meta,
1942                        &mut method_attrs.per_param,
1943                        check,
1944                    )?;
1945                } else if meta.path.is_ident("match_arg") {
1946                    // `match_arg(param1, param2, ...)` — scalar match_arg params.
1947                    method_attrs.match_arg_span.get_or_insert(meta.path.span());
1948                    meta.parse_nested_meta(|inner| {
1949                        let name = crate::miniextendr_fn::method_check_param(&inner)?;
1950                        method_attrs
1951                            .per_param
1952                            .entry(name)
1953                            .or_default()
1954                            .match_arg = true;
1955                        Ok(())
1956                    })?;
1957                } else if meta.path.is_ident("match_arg_several_ok") {
1958                    // `match_arg_several_ok(param1, param2, ...)` — match_arg + several_ok,
1959                    // for Vec/slice/array/Box<[_]>-typed parameters.
1960                    method_attrs.match_arg_span.get_or_insert(meta.path.span());
1961                    meta.parse_nested_meta(|inner| {
1962                        let name = crate::miniextendr_fn::method_check_param(&inner)?;
1963                        let entry = method_attrs.per_param.entry(name).or_default();
1964                        entry.match_arg = true;
1965                        entry.several_ok = true;
1966                        Ok(())
1967                    })?;
1968                } else if meta.path.is_ident("no_default") {
1969                    // `no_default(param1, param2, ...)` — choice params whose R
1970                    // formal has no default (#1828).
1971                    method_attrs.match_arg_span.get_or_insert(meta.path.span());
1972                    crate::miniextendr_fn::parse_method_no_default(
1973                        &meta,
1974                        &mut method_attrs.per_param,
1975                    )?;
1976                } else if meta.path.is_ident("formal") {
1977                    // `formal(conf_int = "conf.int", ...)` — the R formal of each
1978                    // named parameter (#1842).
1979                    method_attrs.match_arg_span.get_or_insert(meta.path.span());
1980                    crate::miniextendr_fn::parse_method_formal(&meta, &mut method_attrs.per_param)?;
1981                } else if meta.path.is_ident("choices") {
1982                    // `choices(param = "a, b, c", param2 = "x, y")` — explicit string choice lists.
1983                    method_attrs.match_arg_span.get_or_insert(meta.path.span());
1984                    meta.parse_nested_meta(|inner| {
1985                        let name = crate::miniextendr_fn::method_check_param(&inner)?;
1986                        let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1987                        let value: syn::LitStr = inner.input.parse()?;
1988                        let choices = crate::r_wrapper_builder::split_choice_list(&value.value());
1989                        method_attrs.per_param.entry(name).or_default().choices = Some(choices);
1990                        Ok(())
1991                    })?;
1992                } else if meta.path.is_ident("choices_several_ok") {
1993                    // `choices_several_ok(param = "a, b, c")` — choices + several_ok.
1994                    method_attrs.match_arg_span.get_or_insert(meta.path.span());
1995                    meta.parse_nested_meta(|inner| {
1996                        let name = crate::miniextendr_fn::method_check_param(&inner)?;
1997                        let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
1998                        let value: syn::LitStr = inner.input.parse()?;
1999                        let choices = crate::r_wrapper_builder::split_choice_list(&value.value());
2000                        let entry = method_attrs.per_param.entry(name).or_default();
2001                        entry.choices = Some(choices);
2002                        entry.several_ok = true;
2003                        Ok(())
2004                    })?;
2005                } else if meta.path.is_ident("check_interrupt") {
2006                    method_attrs.check_interrupt = true;
2007                } else if meta.path.is_ident("coerce") {
2008                    coerce = Some(true);
2009                } else if meta.path.is_ident("no_coerce") {
2010                    coerce = Some(false);
2011                } else if meta.path.is_ident("rng") {
2012                    if meta.input.peek(syn::token::Paren) {
2013                        return crate::miniextendr_fn::refuse_rng_seed_on_method(
2014                            &meta,
2015                            "an impl method",
2016                        );
2017                    }
2018                    method_attrs.rng = true;
2019                } else if meta.path.is_ident("unwrap_in_r") {
2020                    method_attrs.unwrap_in_r = true;
2021                } else if meta.path.is_ident("wrap") {
2022                    let value: syn::LitStr = meta.value()?.parse()?;
2023                    method_attrs.wrap = Some(crate::return_wrap::parse_system(&value)?);
2024                } else if meta.path.is_ident("serialize") {
2025                    method_attrs.serialize = true;
2026                } else if meta.path.is_ident("serde_error") {
2027                    method_attrs.serde_error =
2028                        Some(crate::miniextendr_fn::parse_serde_error_nested(&meta)?);
2029                } else if meta.path.is_ident("as") {
2030                    // Parse as = "data.frame", as = "list", etc.
2031                    method_attrs.as_coercion_span = Some(meta.path.span());
2032                    let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
2033                    let value: syn::LitStr = meta.input.parse()?;
2034                    let coercion_type = value.value();
2035
2036                    // Validate the coercion type
2037                    const SUPPORTED_AS_TYPES: &[&str] = &[
2038                        "data.frame",
2039                        "list",
2040                        "character",
2041                        "numeric",
2042                        "double",
2043                        "integer",
2044                        "logical",
2045                        "matrix",
2046                        "vector",
2047                        "factor",
2048                        "Date",
2049                        "POSIXct",
2050                        "complex",
2051                        "raw",
2052                        "environment",
2053                        "function",
2054                        "tibble",
2055                        "data.table",
2056                        "array",
2057                        "ts",
2058                    ];
2059
2060                    if !SUPPORTED_AS_TYPES.contains(&coercion_type.as_str()) {
2061                        return Err(syn::Error::new(
2062                            value.span(),
2063                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unsupported `as` type: \"{0}\". Supported types: {1}",
                coercion_type, SUPPORTED_AS_TYPES.join(", ")))
    })format!(
2064                                "unsupported `as` type: \"{}\". Supported types: {}",
2065                                coercion_type,
2066                                SUPPORTED_AS_TYPES.join(", ")
2067                            ),
2068                        ));
2069                    }
2070
2071                    method_attrs.as_coercion = Some(coercion_type);
2072                } else if meta.path.is_ident("lifecycle") {
2073                    // lifecycle = "stage" or lifecycle(stage = "deprecated", when = "0.4.0", ...)
2074                    if meta.input.peek(::syn::token::Eqsyn::Token![=]) {
2075                        // lifecycle = "stage"
2076                        let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
2077                        let value: syn::LitStr = meta.input.parse()?;
2078                        let stage = crate::lifecycle::LifecycleStage::from_str(&value.value())
2079                            .ok_or_else(|| {
2080                                syn::Error::new(
2081                                    value.span(),
2082                                    "invalid lifecycle stage; expected one of: experimental, stable, superseded, soft-deprecated, deprecated, defunct",
2083                                )
2084                            })?;
2085                        method_attrs.lifecycle = Some(crate::lifecycle::LifecycleSpec::new(stage));
2086                    } else {
2087                        // lifecycle(stage = "deprecated", when = "0.4.0", ...)
2088                        let mut spec = crate::lifecycle::LifecycleSpec::default();
2089                        meta.parse_nested_meta(|inner| {
2090                            let key = inner.path.get_ident()
2091                                .ok_or_else(|| inner.error("expected identifier"))?
2092                                .to_string();
2093                            let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
2094                            let value: syn::LitStr = inner.input.parse()?;
2095                            match key.as_str() {
2096                                "stage" => {
2097                                    spec.stage = crate::lifecycle::LifecycleStage::from_str(&value.value())
2098                                        .ok_or_else(|| syn::Error::new(value.span(), "invalid lifecycle stage"))?;
2099                                }
2100                                "when" => spec.when = Some(value.value()),
2101                                "what" => spec.what = Some(value.value()),
2102                                "with" => spec.with = Some(value.value()),
2103                                "details" => spec.details = Some(value.value()),
2104                                "id" => spec.id = Some(value.value()),
2105                                _ => return Err(inner.error(
2106                                    "unknown lifecycle option; expected: stage, when, what, with, details, id"
2107                                )),
2108                            }
2109                            Ok(())
2110                        })?;
2111                        method_attrs.lifecycle = Some(spec);
2112                    }
2113                } else if meta.path.is_ident("vctrs") {
2114                    // vctrs protocol method: vctrs(format), vctrs(vec_proxy), etc.
2115                    meta.parse_nested_meta(|inner| {
2116                        let raw_name = inner.path.get_ident()
2117                            .ok_or_else(|| inner.error("expected protocol name"))?
2118                            .to_string();
2119
2120                        // Normalize short aliases to full protocol names
2121                        const PROTOCOL_ALIASES: &[(&str, &str)] = &[
2122                            ("print_data", "obj_print_data"),
2123                            ("print_header", "obj_print_header"),
2124                            ("print_footer", "obj_print_footer"),
2125                            ("proxy", "vec_proxy"),
2126                            ("proxy_equal", "vec_proxy_equal"),
2127                            ("proxy_compare", "vec_proxy_compare"),
2128                            ("proxy_order", "vec_proxy_order"),
2129                            ("restore", "vec_restore"),
2130                        ];
2131                        let protocol = PROTOCOL_ALIASES
2132                            .iter()
2133                            .find(|(alias, _)| *alias == raw_name)
2134                            .map(|(_, full)| full.to_string())
2135                            .unwrap_or_else(|| raw_name.to_string());
2136
2137                        const VALID_PROTOCOLS: &[&str] = &[
2138                            "format", "vec_proxy", "vec_proxy_equal", "vec_proxy_compare",
2139                            "vec_proxy_order", "vec_restore", "obj_print_data",
2140                            "obj_print_header", "obj_print_footer",
2141                        ];
2142                        if !VALID_PROTOCOLS.contains(&protocol.as_str()) {
2143                            return Err(inner.error(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown vctrs protocol: {0}; expected one of: {1}",
                raw_name, VALID_PROTOCOLS.join(", ")))
    })format!(
2144                                "unknown vctrs protocol: {}; expected one of: {}",
2145                                raw_name,
2146                                VALID_PROTOCOLS.join(", ")
2147                            )));
2148                        }
2149                        method_attrs.vctrs_protocol = Some(protocol);
2150                        Ok(())
2151                    })?;
2152                } else if meta.path.is_ident("r_name") {
2153                    let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
2154                    let value: syn::LitStr = meta.input.parse()?;
2155                    let val = value.value();
2156                    if val.is_empty() {
2157                        return Err(syn::Error::new_spanned(value, "r_name must not be empty"));
2158                    }
2159                    method_attrs.r_name = Some(val);
2160                } else if meta.path.is_ident("postfix") {
2161                    let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
2162                    let value: syn::LitStr = meta.input.parse()?;
2163                    let val = value.value();
2164                    crate::miniextendr_fn::validate_postfix(&val, &value)?;
2165                    method_attrs.postfix = Some(val);
2166                } else if meta.path.is_ident("call") {
2167                    return Err(meta.error(
2168                        "`call = caller` is only supported on standalone `#[miniextendr]` \
2169                         functions (the internal-entry-point pattern); class methods keep \
2170                         their own call attribution",
2171                    ));
2172                } else if meta.path.is_ident("r_entry") {
2173                    let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
2174                    let value: syn::LitStr = meta.input.parse()?;
2175                    method_attrs.r_entry = Some(value.value());
2176                } else if meta.path.is_ident("r_post_checks") {
2177                    let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
2178                    let value: syn::LitStr = meta.input.parse()?;
2179                    method_attrs.r_post_checks = Some(value.value());
2180                } else if meta.path.is_ident("r_on_exit") {
2181                    if meta.input.peek(::syn::token::Eqsyn::Token![=]) {
2182                        // Short form: r_on_exit = "expr"
2183                        let _: ::syn::token::Eqsyn::Token![=] = meta.input.parse()?;
2184                        let value: syn::LitStr = meta.input.parse()?;
2185                        method_attrs.r_on_exit = Some(crate::miniextendr_fn::ROnExit {
2186                            expr: value.value(),
2187                            add: true,
2188                            after: true,
2189                        });
2190                    } else {
2191                        // Long form: r_on_exit(expr = "...", add = false, after = false)
2192                        let mut expr = None;
2193                        let mut add = true;
2194                        let mut after = true;
2195                        meta.parse_nested_meta(|inner| {
2196                            if inner.path.is_ident("expr") {
2197                                let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
2198                                let value: syn::LitStr = inner.input.parse()?;
2199                                expr = Some(value.value());
2200                            } else if inner.path.is_ident("add") {
2201                                let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
2202                                let value: syn::LitBool = inner.input.parse()?;
2203                                add = value.value;
2204                            } else if inner.path.is_ident("after") {
2205                                let _: ::syn::token::Eqsyn::Token![=] = inner.input.parse()?;
2206                                let value: syn::LitBool = inner.input.parse()?;
2207                                after = value.value;
2208                            } else {
2209                                return Err(inner.error(
2210                                    "unknown r_on_exit option; expected `expr`, `add`, or `after`",
2211                                ));
2212                            }
2213                            Ok(())
2214                        })?;
2215                        let expr = expr.ok_or_else(|| {
2216                            meta.error("r_on_exit(...) requires `expr = \"...\"` specifying the R expression")
2217                        })?;
2218                        method_attrs.r_on_exit = Some(crate::miniextendr_fn::ROnExit { expr, add, after });
2219                    }
2220                } else if meta.path.is_ident("noexport") {
2221                    method_attrs.noexport = true;
2222                } else if meta.path.is_ident("internal") {
2223                    method_attrs.internal = true;
2224                } else if meta.path.is_ident("invisible") {
2225                    method_attrs.force_invisible = Some(true);
2226                } else if meta.path.is_ident("visible") {
2227                    method_attrs.force_invisible = Some(false);
2228                } else if meta.path.is_ident("dots") {
2229                    // `dots = typed_list!(...)` — attribute sugar mirroring the
2230                    // standalone-fn path (`miniextendr_fn.rs`): capture the
2231                    // `typed_list!(...)` spec so a `dots_typed` binding can be
2232                    // injected at the top of the method body in `from_impl_item`.
2233                    // Or the role of `...` (#2157), checked in the R wrapper.
2234                    let value: syn::Expr = meta.value()?.parse()?;
2235                    match crate::dots_policy::parse_dots_attr(&value)? {
2236                        crate::dots_policy::DotsAttr::TypedList(spec) => {
2237                            method_attrs.dots_spec = Some(spec);
2238                        }
2239                        crate::dots_policy::DotsAttr::Policy(policy) => {
2240                            method_attrs.dots_policy = Some(policy);
2241                        }
2242                    }
2243                } else {
2244                    return Err(meta.error(
2245                        "unknown attribute; expected one of: env, r6, s3, s4, s7, vctrs, defaults, check_interrupt, coerce, no_coerce, preconditions, no_preconditions, rng, unwrap_in_r, serialize, serde_error, as, lifecycle, r_name, postfix, r_entry, r_post_checks, r_on_exit, noexport, internal, invisible, visible, match_arg, match_arg_several_ok, choices, choices_several_ok, no_default, inherits, not_inherits, no_na, formal, dots = typed_list!(...) | empty | forward(allow = [...]) | data"
2246                    ));
2247                }
2248                Ok(())
2249            })?;
2250        }
2251
2252        // Resolve feature defaults for fields not explicitly set
2253        method_attrs.coerce = coerce.unwrap_or(coerce_default);
2254
2255        // Method-level `internal` / `noexport` are currently only honoured by the R6
2256        // active-binding doc path (emits a class-level
2257        // `#' @field <name> (internal)` — the documented roxygen2 8.0.0
2258        // `@field name NULL` opt-out doesn't actually silence
2259        // `r6_resolve_fields`'s "Undocumented R6 active binding" warning, so we
2260        // use a minimal real description instead). Accepting them silently
2261        // elsewhere would be a no-op surface: regular instance methods, static
2262        // methods, and trait methods don't currently consume these flags. Reject
2263        // them at parse time so the failure is loud rather than silent.
2264        // Class-level `#[miniextendr(internal)]` / `noexport` continue to work for whole
2265        // impl blocks via `parsed_impl.internal` / `parsed_impl.noexport`.
2266        if (method_attrs.internal || method_attrs.noexport) && !method_attrs.r6.active {
2267            return Err(syn::Error::new(
2268                proc_macro2::Span::call_site(),
2269                "method-level `internal` / `noexport` are currently only supported on R6 \
2270                 active bindings (use `#[miniextendr(r6(active), noexport)]`). For other \
2271                 method positions, set `internal` / `noexport` at the impl-block level \
2272                 (`#[miniextendr(s7, internal)] impl Foo { ... }`) instead.",
2273            ));
2274        }
2275
2276        Ok(method_attrs)
2277    }
2278
2279    /// Detect the [`ReceiverKind`] from a method's function signature.
2280    ///
2281    /// Inspects the first parameter to determine whether this is a static function
2282    /// (`None`), immutable borrow (`Ref`), mutable borrow (`RefMut`), consuming
2283    /// method (`Value`), or handle receiver (`ExternalPtrRef`, `ExternalPtrMut`,
2284    /// `ExternalPtrValue`). Handles both standard receivers (`&self`, `&mut self`) and
2285    /// typed receivers (`self: &Self`, `self: ExternalPtr<Self>`, etc.).
2286    fn detect_env(sig: &syn::Signature) -> ReceiverKind {
2287        match crate::trait_receiver::owner_receiver(sig) {
2288            Some(crate::trait_receiver::OwnerReceiver::Shared) => {
2289                return ReceiverKind::ExternalPtrRef;
2290            }
2291            Some(crate::trait_receiver::OwnerReceiver::Mutable) => {
2292                return ReceiverKind::ExternalPtrMut;
2293            }
2294            None => {}
2295        }
2296        match sig.inputs.first() {
2297            Some(syn::FnArg::Receiver(r)) => {
2298                // Check for standard &self / &mut self
2299                if r.reference.is_some() {
2300                    if r.mutability.is_some() {
2301                        ReceiverKind::RefMut
2302                    } else {
2303                        ReceiverKind::Ref
2304                    }
2305                } else if r.colon_token.is_some() {
2306                    // Check for typed receiver (self: &Self, self: &mut Self;
2307                    // `old_handle_receiver` refuses `self: &ExternalPtr<Self>`)
2308                    if let syn::Type::Reference(type_ref) = r.ty.as_ref() {
2309                        if type_ref.mutability.is_some() {
2310                            ReceiverKind::RefMut
2311                        } else {
2312                            ReceiverKind::Ref
2313                        }
2314                    } else if is_external_ptr_type(r.ty.as_ref()) {
2315                        // self: ExternalPtr<Self> — owned ExternalPtr
2316                        ReceiverKind::ExternalPtrValue
2317                    } else {
2318                        // self: Box<Self>, self: Rc<Self>, etc. - treat as by value
2319                        ReceiverKind::Value
2320                    }
2321                } else {
2322                    ReceiverKind::Value
2323                }
2324            }
2325            _ => ReceiverKind::None,
2326        }
2327    }
2328
2329    /// Create a copy of the method signature with the `self` receiver removed.
2330    ///
2331    /// The C wrapper receives `self` as a separate SEXP argument and extracts it
2332    /// from an `ErasedExternalPtr`, so the receiver must not appear in the
2333    /// parameter list used for SEXP-to-Rust conversion codegen.
2334    fn sig_without_env(sig: &syn::Signature) -> syn::Signature {
2335        let mut sig = sig.clone();
2336        if let Some(syn::FnArg::Receiver(_)) = sig.inputs.first() {
2337            sig.inputs = sig.inputs.into_iter().skip(1).collect();
2338        }
2339        sig
2340    }
2341
2342    /// Parse a method from an impl item.
2343    ///
2344    /// Regular doc comments are auto-converted to `@description` for all class
2345    /// systems. `class_page` is whether the class block renders a help page:
2346    /// the method's docs go nowhere else when it does not. `coerce_default`
2347    /// is the impl's `method_coerce_default`.
2348    pub fn from_impl_item(
2349        item: &mut syn::ImplItemFn,
2350        class_page: crate::roxygen::RdPage,
2351        coerce_default: bool,
2352    ) -> syn::Result<Self> {
2353        use syn::spanned::Spanned;
2354        old_handle_receiver(&item.sig)?;
2355        let env = Self::detect_env(&item.sig);
2356        let mut method_attrs = Self::parse_method_attrs(&item.attrs, coerce_default)?;
2357        // An ignored method gets no wrapper, like a skipped trait method.
2358        if !method_attrs.ignore {
2359            crate::miniextendr_fn::require_safe_wrapper(
2360                &item.sig,
2361                "move it to an `impl` block without `#[miniextendr]`",
2362            )?;
2363        }
2364
2365        // The `&Dots` parameter is R's `...` wherever it sits (Rust `...`
2366        // becomes a trailing one); at most one per method.
2367        crate::miniextendr_fn::rewrite_variadic_dots(&mut item.sig)?;
2368        let dots_ident = crate::miniextendr_fn::find_dots_param(&item.sig.inputs)?;
2369        let has_dots = dots_ident.is_some();
2370
2371        // Parameter markers (`Checked<T>` / `Unchecked<T>`, #1566; `NonNa<T>`):
2372        // peeled from the signature the codegen sees (the re-emitted impl
2373        // keeps them), and merged with the method's `preconditions(p)` /
2374        // `no_preconditions(p)`, which a marker must not contradict, and
2375        // `no_na(p)`.
2376        let param_markers = crate::miniextendr_fn::collect_param_markers(&item.sig.inputs)?;
2377        for arg in &item.sig.inputs {
2378            let syn::FnArg::Typed(pt) = arg else {
2379                continue;
2380            };
2381            let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
2382                continue;
2383            };
2384            let name = crate::naming::ident_name(&pat_ident.ident);
2385            let Some((_, markers)) = param_markers.iter().find(|(n, _)| *n == name) else {
2386                continue;
2387            };
2388            let entry = method_attrs.per_param.entry(name.clone()).or_default();
2389            entry.preconditions = crate::miniextendr_fn::merge_param_policy(
2390                markers,
2391                entry.preconditions,
2392                &name,
2393                true,
2394                &pt.ty,
2395            )?;
2396            // `NonNa<T>` is the method's `no_na(p)` written in the type.
2397            if markers.contains(&crate::type_inspect::ParamMarker::NonNa) {
2398                entry.checks.no_na = true;
2399            }
2400        }
2401        let mut peeled_sig = item.sig.clone();
2402        peeled_sig.inputs = crate::miniextendr_fn::peeled_inputs(&item.sig.inputs, &param_markers)?;
2403
2404        // `dots = typed_list!(...)` sugar: inject the `dots_typed` binding at the
2405        // top of the method body, reusing the shared helper that the standalone-fn
2406        // path uses. This mutates `item.block`, which is the same node re-emitted
2407        // as `original_impl` (see `ParsedImpl::parse`), so it covers all six class
2408        // systems by construction (they emit only R/C wrappers, not the Rust body).
2409        if let Some(spec) = &method_attrs.dots_spec {
2410            let dots_ident = dots_ident.as_ref().ok_or_else(|| {
2411                syn::Error::new(
2412                    item.sig.ident.span(),
2413                    "dots = typed_list!(...) requires the method to take a dots parameter \
2414                     (`...` or a `&Dots` parameter)",
2415                )
2416            })?;
2417            if let Some(err) =
2418                crate::miniextendr_fn::typed_list_on_lazy_dots(&item.sig.inputs, None)
2419            {
2420                return Err(err);
2421            }
2422            let stmt = crate::build_dots_validation_stmt(dots_ident, spec);
2423            item.block.stmts.insert(0, stmt);
2424        }
2425
2426        // Validate: no defaults on self parameter (any kind: &self, &mut self, self)
2427        if env != ReceiverKind::None && method_attrs.defaults.contains_key("self") {
2428            return Err(syn::Error::new(
2429                method_attrs
2430                    .defaults_span
2431                    .unwrap_or_else(|| item.sig.ident.span()),
2432                "cannot specify default for self parameter in defaults(...)",
2433            ));
2434        }
2435
2436        // Validate: all defaults reference existing parameters
2437        let param_names: std::collections::HashSet<String> = item
2438            .sig
2439            .inputs
2440            .iter()
2441            .filter_map(|input| {
2442                if let syn::FnArg::Typed(pat_type) = input
2443                    && let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref()
2444                {
2445                    Some(crate::naming::ident_name(&pat_ident.ident))
2446                } else {
2447                    None
2448                }
2449            })
2450            .collect();
2451
2452        let mut invalid_params: Vec<String> = method_attrs
2453            .defaults
2454            .keys()
2455            .filter(|key| *key != "self" && !param_names.contains(*key))
2456            .cloned()
2457            .collect();
2458        invalid_params.sort();
2459
2460        if !invalid_params.is_empty() {
2461            return Err(syn::Error::new(
2462                method_attrs
2463                    .defaults_span
2464                    .unwrap_or_else(|| item.sig.ident.span()),
2465                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("defaults(...) references non-existent parameter(s): {0}",
                invalid_params.join(", ")))
    })format!(
2466                    "defaults(...) references non-existent parameter(s): {}",
2467                    invalid_params.join(", ")
2468                ),
2469            ));
2470        }
2471
2472        // Validate type-based constraints on each parameter
2473        for input in &peeled_sig.inputs {
2474            let syn::FnArg::Typed(pat_type) = input else {
2475                continue;
2476            };
2477            let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref() else {
2478                continue;
2479            };
2480            let param_name = crate::naming::ident_name(&pat_ident.ident);
2481
2482            // Validate Missing nesting and Missing<Dots>
2483            crate::miniextendr_fn::validate_param_type(pat_type.ty.as_ref(), pat_type.ty.span())?;
2484
2485            // Validate: no defaults on Dots-type parameters
2486            if crate::miniextendr_fn::is_dots_type(pat_type.ty.as_ref())
2487                && method_attrs.defaults.contains_key(&param_name)
2488            {
2489                return Err(syn::Error::new(
2490                    method_attrs
2491                        .defaults_span
2492                        .unwrap_or_else(|| pat_ident.ident.span()),
2493                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("variadic (...) parameter `{0}` cannot have a default value",
                param_name))
    })format!(
2494                        "variadic (...) parameter `{}` cannot have a default value",
2495                        param_name
2496                    ),
2497                ));
2498            }
2499        }
2500
2501        // Extract lifecycle from #[deprecated] attribute if not already set via #[miniextendr(lifecycle = ...)]
2502        if method_attrs.lifecycle.is_none() {
2503            method_attrs.lifecycle = item
2504                .attrs
2505                .iter()
2506                .find_map(crate::lifecycle::parse_rust_deprecated);
2507        }
2508
2509        // Auto-convert regular doc comments to @description for all class systems
2510        let mut doc_tags =
2511            crate::roxygen::roxygen_tags_from_attrs_for_r6_method(&item.attrs, class_page);
2512
2513        // Inject lifecycle badge into method roxygen tags if present
2514        if let Some(ref spec) = method_attrs.lifecycle {
2515            crate::lifecycle::inject_lifecycle_badge(&mut doc_tags, spec);
2516        }
2517
2518        // Get parameter defaults from method-level #[miniextendr(defaults(...))] attribute
2519        let param_defaults = method_attrs.defaults.clone();
2520
2521        // match_arg / choices / inherits / not_inherits / no_na on impl methods: unlike standalone
2522        // functions, Rust doesn't accept `#[miniextendr(...)]` on method parameters
2523        // inside an impl (attribute macros aren't allowed there — "expected
2524        // non-macro attribute"). The surface is instead method-level:
2525        // `#[miniextendr(match_arg(p), choices(q = "a, b"))]`. Every named param
2526        // must exist on the signature, so typos fail at compile time; `Option<T>`
2527        // scalar match_arg/choices params are the optional form (#1473) and
2528        // `Missing<..>` ones the omittable form (#1551), and neither takes a
2529        // default. Any other `Missing<T>` parameter does (#2161).
2530        crate::miniextendr_fn::finalize_method_param_attrs(
2531            &mut method_attrs.per_param,
2532            &peeled_sig.inputs,
2533            &param_markers,
2534            &param_defaults,
2535            method_attrs
2536                .match_arg_span
2537                .unwrap_or_else(|| item.sig.ident.span()),
2538        )?;
2539
2540        // The RNG guard (#2002): a `&RngGuard` parameter needs `rng` and takes
2541        // no option, which the method-level forms would name.
2542        crate::miniextendr_fn::check_rng_guard_params(
2543            &peeled_sig.inputs,
2544            method_attrs.rng,
2545            |name| method_attrs.per_param.contains_key(name) || param_defaults.contains_key(name),
2546        )?;
2547
2548        // Consuming `self` receivers (#1432): supported for every return shape
2549        // (see `ReceiverKind::Value`). Two things stay rejected: a receiver type
2550        // the wrapper cannot hand over (`self: Box<Self>` / `Rc<Self>` ...), and
2551        // the `constructor` marker, which describes receiverless `fn new()`.
2552        if env == ReceiverKind::Value {
2553            if let Some(syn::FnArg::Receiver(r)) = item.sig.inputs.first()
2554                && r.colon_token.is_some()
2555                && !#[allow(non_exhaustive_omitted_patterns)] match r.ty.as_ref() {
    syn::Type::Path(tp) if
        tp.path.segments.last().is_some_and(|seg| seg.ident == "Self") &&
            tp.path.segments.len() == 1 => true,
    _ => false,
}matches!(r.ty.as_ref(), syn::Type::Path(tp)
2556                    if tp.path.segments.last().is_some_and(|seg| seg.ident == "Self")
2557                        && tp.path.segments.len() == 1)
2558            {
2559                return Err(syn::Error::new_spanned(
2560                    &r.ty,
2561                    "unsupported receiver type: the R handle stores the value itself, so a \
2562                     method can take `self`, `self: Self`, `&self`, `&mut self`, \
2563                     `self: ExternalPtrRef<'_, Self>`, `self: ExternalPtrMut<'_, Self>` or \
2564                     `self: ExternalPtr<Self>` — not a smart pointer around `Self`",
2565                ));
2566            }
2567            if method_attrs.constructor {
2568                return Err(syn::Error::new(
2569                    item.sig.fn_token.span,
2570                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("method `{0}` takes `self` and is marked `constructor`; a constructor has no receiver (`fn new(...) -> Self`). A consuming builder step needs no marker: `fn {1}(self, ...) -> Self` writes its result back into the same R object.",
                item.sig.ident, item.sig.ident))
    })format!(
2571                        "method `{}` takes `self` and is marked `constructor`; a constructor has no \
2572                         receiver (`fn new(...) -> Self`). A consuming builder step needs no marker: \
2573                         `fn {}(self, ...) -> Self` writes its result back into the same R object.",
2574                        item.sig.ident, item.sig.ident
2575                    ),
2576                ));
2577            }
2578        }
2579
2580        // Return-visibility marker (#1213): validate, record, and strip it from
2581        // the signature the codegen sees (whose parameters are already peeled).
2582        let mut sig = Self::sig_without_env(&peeled_sig);
2583        // The RNG guard leaves the signature every R-side consumer and the
2584        // argument conversion see; the C wrapper puts the guard back in the
2585        // call at its position.
2586        let rng_guard = sig.inputs.iter().position(|arg| {
2587            #[allow(non_exhaustive_omitted_patterns)] match arg {
    syn::FnArg::Typed(pt) if crate::type_inspect::is_rng_guard_param(&pt.ty)
        => true,
    _ => false,
}matches!(arg, syn::FnArg::Typed(pt) if crate::type_inspect::is_rng_guard_param(&pt.ty))
2588        });
2589        if rng_guard.is_some() {
2590            sig.inputs = std::mem::take(&mut sig.inputs)
2591                .into_iter()
2592                .filter(|arg| {
2593                    !#[allow(non_exhaustive_omitted_patterns)] match arg {
    syn::FnArg::Typed(pt) if crate::type_inspect::is_rng_guard_param(&pt.ty)
        => true,
    _ => false,
}matches!(arg, syn::FnArg::Typed(pt)
2594                        if crate::type_inspect::is_rng_guard_param(&pt.ty))
2595                })
2596                .collect();
2597        }
2598        let visibility_marker = match &item.sig.output {
2599            syn::ReturnType::Type(_, ty) => {
2600                if let Some(err) = crate::type_inspect::visibility_marker_error(ty, "return") {
2601                    return Err(err);
2602                }
2603                let (marker, peeled) =
2604                    crate::type_inspect::peel_return_visibility(&item.sig.output);
2605                sig.output = peeled;
2606                marker
2607            }
2608            syn::ReturnType::Default => None,
2609        };
2610        if let (Some(marker), Some(attr)) = (visibility_marker, method_attrs.force_invisible)
2611            && marker != attr
2612        {
2613            return Err(syn::Error::new_spanned(
2614                &item.sig.output,
2615                "the return type's visibility marker and the `invisible` / `visible` method option disagree; keep one of them (or make them agree)",
2616            ));
2617        }
2618
2619        let (return_wrap, output) = crate::return_wrap::resolve(&sig.output, method_attrs.wrap)?;
2620        if return_wrap.is_some() && (method_attrs.serialize || method_attrs.unwrap_in_r) {
2621            return Err(syn::Error::new_spanned(
2622                &item.sig.output,
2623                "explicit class wrapping cannot be combined with serialize or unwrap_in_r",
2624            ));
2625        }
2626        sig.output = crate::type_inspect::serialize_return_type(&output, method_attrs.serialize);
2627        Ok(ParsedMethod {
2628            visibility_marker,
2629            return_wrap,
2630            ident: item.sig.ident.clone(),
2631            env,
2632            sig,
2633            param_markers,
2634            vis: item.vis.clone(),
2635            doc_tags,
2636            method_attrs,
2637            param_defaults,
2638            has_dots,
2639            rng_guard,
2640        })
2641    }
2642
2643    /// Returns true if this method should be included in the class.
2644    pub fn should_include(&self) -> bool {
2645        // Skip ignored methods
2646        !self.method_attrs.ignore
2647    }
2648
2649    /// Returns true if this method should be private in R6.
2650    /// Inferred from Rust visibility: anything not `pub` is private.
2651    pub fn is_private(&self) -> bool {
2652        // Explicit attribute takes precedence
2653        if self.method_attrs.r6.private {
2654            return true;
2655        }
2656        // Infer from visibility: anything not `pub` is private
2657        !#[allow(non_exhaustive_omitted_patterns)] match self.vis {
    syn::Visibility::Public(_) => true,
    _ => false,
}matches!(self.vis, syn::Visibility::Public(_))
2658    }
2659
2660    /// Returns true if this is likely a constructor.
2661    /// Inferred from: no env + named "new" + returns Self.
2662    pub fn is_constructor(&self) -> bool {
2663        self.method_attrs.constructor
2664            || (self.env == ReceiverKind::None && self.ident == "new" && self.returns_self())
2665    }
2666
2667    /// Returns true if this method is the R6 finalizer.
2668    ///
2669    /// Only the explicit `#[miniextendr(r6(finalize))]` marker qualifies. It
2670    /// used to be inferred from "takes `self` by value and does not return
2671    /// `Self`", which silently hid consuming methods on every class system
2672    /// (#1432).
2673    pub fn is_finalizer(&self) -> bool {
2674        self.method_attrs.r6.finalize
2675    }
2676
2677    /// Returns true if this method should be an R6 active binding.
2678    /// Active bindings provide property-like access (obj$name instead of obj$name()).
2679    pub fn is_active(&self) -> bool {
2680        self.method_attrs.r6.active
2681    }
2682
2683    /// R-facing method name.
2684    ///
2685    /// Returns `r_name` if set, otherwise the Rust ident with `postfix`
2686    /// appended when given, otherwise the Rust ident as a string.
2687    pub fn r_method_name(&self) -> String {
2688        if let Some(r_name) = &self.method_attrs.r_name {
2689            return r_name.clone();
2690        }
2691        match &self.method_attrs.postfix {
2692            Some(postfix) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}",
                crate::naming::ident_name(&self.ident), postfix))
    })format!("{}{postfix}", crate::naming::ident_name(&self.ident)),
2693            None => crate::naming::ident_name(&self.ident),
2694        }
2695    }
2696
2697    /// C wrapper identifier for this method.
2698    ///
2699    /// Format: `C_{crate}_{Type}__{method}` — crate-prefixed for webR
2700    /// cross-package symbol uniqueness (#1273). Unique per type: two impl
2701    /// blocks of one type can't both define a method (E0592).
2702    pub fn c_wrapper_ident(&self, type_ident: &syn::Ident) -> syn::Ident {
2703        crate::naming::impl_method_c_wrapper_ident(type_ident, &self.ident)
2704    }
2705
2706    /// The R formal of each parameter (#1842), from the method's
2707    /// `formal(p = "...")`.
2708    pub fn formals(&self) -> crate::r_wrapper_builder::Formals {
2709        crate::r_wrapper_builder::Formals::from_param_attrs(&self.method_attrs.per_param)
2710    }
2711
2712    /// Generate lifecycle prelude R code for this method, if lifecycle is specified.
2713    ///
2714    /// The `what` parameter describes the method in the format appropriate for the class system:
2715    /// - Env/R6: `"Type$method()"`
2716    /// - S3: `"method.Type()"`
2717    /// - S7: `"method()`" (dispatched generics)
2718    pub fn lifecycle_prelude(&self, what: &str) -> Option<String> {
2719        self.method_attrs
2720            .lifecycle
2721            .as_ref()
2722            .and_then(|spec| spec.r_prelude(what))
2723    }
2724
2725    /// Returns true if this method returns Self.
2726    pub fn returns_self(&self) -> bool {
2727        #[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)
2728            if matches!(ty.as_ref(), syn::Type::Path(p)
2729                if p.path.segments.last().map(|s| s.ident == "Self").unwrap_or(false)))
2730    }
2731
2732    /// Returns true if this method returns `Result<Self, E>` — a fallible
2733    /// constructor-shaped method (e.g. `from_r`, `try_new`). On the R side this
2734    /// is treated exactly like a bare `Self` return (wrapped class object via
2735    /// [`crate::ReturnStrategy::for_method`]); the C wrapper still raises on
2736    /// `Err` via the normal `Result` error path (see
2737    /// [`crate::c_wrapper_builder::ReturnHandling::ResultExternalPtr`]).
2738    pub fn returns_result_self(&self) -> bool {
2739        let syn::ReturnType::Type(_, ty) = &self.sig.output else {
2740            return false;
2741        };
2742        let syn::Type::Path(p) = ty.as_ref() else {
2743            return false;
2744        };
2745        let Some(seg) = p.path.segments.last() else {
2746            return false;
2747        };
2748        if seg.ident != "Result" {
2749            return false;
2750        }
2751        let syn::PathArguments::AngleBracketed(ab) = &seg.arguments else {
2752            return false;
2753        };
2754        let Some(syn::GenericArgument::Type(ok_ty)) = ab.args.first() else {
2755            return false;
2756        };
2757        #[allow(non_exhaustive_omitted_patterns)] match ok_ty {
    syn::Type::Path(ip) if
        ip.path.segments.last().map(|s| s.ident == "Self").unwrap_or(false) =>
        true,
    _ => false,
}matches!(ok_ty, syn::Type::Path(ip)
2758            if ip.path.segments.last().map(|s| s.ident == "Self").unwrap_or(false))
2759    }
2760
2761    /// Returns true if this method returns `Option<Self>` — a lookup-shaped
2762    /// fallible constructor (e.g. `try_find`). On the R side this is treated
2763    /// exactly like a bare `Self` return (wrapped class object via
2764    /// [`crate::ReturnStrategy::for_method`]); the C wrapper still raises on
2765    /// `None` via the normal `Option` error path (see
2766    /// [`crate::c_wrapper_builder::ReturnHandling::OptionExternalPtr`]).
2767    /// Symmetric with [`Self::returns_result_self`].
2768    pub fn returns_option_self(&self) -> bool {
2769        let syn::ReturnType::Type(_, ty) = &self.sig.output else {
2770            return false;
2771        };
2772        let syn::Type::Path(p) = ty.as_ref() else {
2773            return false;
2774        };
2775        let Some(seg) = p.path.segments.last() else {
2776            return false;
2777        };
2778        if seg.ident != "Option" {
2779            return false;
2780        }
2781        let syn::PathArguments::AngleBracketed(ab) = &seg.arguments else {
2782            return false;
2783        };
2784        let Some(syn::GenericArgument::Type(some_ty)) = ab.args.first() else {
2785            return false;
2786        };
2787        #[allow(non_exhaustive_omitted_patterns)] match some_ty {
    syn::Type::Path(ip) if
        ip.path.segments.last().map(|s| s.ident == "Self").unwrap_or(false) =>
        true,
    _ => false,
}matches!(some_ty, syn::Type::Path(ip)
2788            if ip.path.segments.last().map(|s| s.ident == "Self").unwrap_or(false))
2789    }
2790
2791    /// Returns the bare type name when this method returns a type that may be a
2792    /// different registered ExternalPtr-backed class.
2793    ///
2794    /// This is deliberately syntactic and conservative about primitives and
2795    /// common containers. The write-time wrapper resolver checks the complete
2796    /// class registry, so an unregistered capitalized type falls back to the
2797    /// direct `.val` return.
2798    ///
2799    /// Four shapes are recognized:
2800    /// - A bare capitalized path, e.g. `-> Board`.
2801    /// - `Option<T>` where `T` is a bare capitalized path. The C wrapper
2802    ///   converts the whole `Option` (`ReturnHandling::OptionIntoR`, as a
2803    ///   function's), so `.val` is a bare pointer for `Some`, wrapped as in the
2804    ///   bare-class case, and `NULL` for `None`, which the wrap passes through
2805    ///   ([`returns_option`](Self::returns_option)).
2806    /// - `Result<T, E>` where `T` is a bare capitalized path and `E` is not
2807    ///   `()`. `Result<T, ()>` is excluded: the unit-error sentinel maps to
2808    ///   `ReturnHandling::ResultNullOnErr`, where `.val` can be `NULL` on
2809    ///   `Ok`, and wrapping `NULL` in a class constructor would break.
2810    /// - `ExternalPtr<T>` (the explicit-handle spelling, #1375), including
2811    ///   through the `Option`/`Result` wrappers above (e.g.
2812    ///   `Option<ExternalPtr<Board>>`) — `IntoR for ExternalPtr<T>` already
2813    ///   produces a bare `EXTPTRSXP` `.val`, identical in shape to the bare
2814    ///   `T` case, so [`inner_class_ident`](Self::inner_class_ident) peels
2815    ///   through it to the same wrapped name.
2816    ///
2817    /// `Option<Self>` / `Result<Self, _>` are excluded here too (the inner
2818    /// ident is `Self`) — `ReturnStrategy::for_method` checks
2819    /// `returns_result_self()` / `returns_option_self()` before this method,
2820    /// so those already take the `ReturnSelf` path regardless.
2821    /// List-shaped returns (`Vec<Class>` and its `Option`/`Result` wrappers)
2822    /// are handled separately by
2823    /// [`returns_other_class_list`](Self::returns_other_class_list); any other
2824    /// nested container is not recognized: the inner type must be a bare path
2825    /// (or an `ExternalPtr<...>` wrapping one) with no other path arguments.
2826    pub fn returns_other_class(&self) -> Option<syn::Ident> {
2827        let syn::ReturnType::Type(_, ty) = &self.sig.output else {
2828            return None;
2829        };
2830        let syn::Type::Path(p) = ty.as_ref() else {
2831            return None;
2832        };
2833        let seg = p.path.segments.last()?;
2834
2835        match &seg.arguments {
2836            syn::PathArguments::None => Self::class_ident_from_ident(&seg.ident),
2837            syn::PathArguments::AngleBracketed(_) if seg.ident == "Option" => {
2838                Self::inner_class_ident(crate::first_type_argument(seg)?)
2839            }
2840            syn::PathArguments::AngleBracketed(_) if seg.ident == "Result" => {
2841                // `Result<T, ()>` is a deliberate NULL-on-Err sentinel
2842                // (`ResultNullOnErr`) rather than a fallible constructor —
2843                // `.val` may be `NULL`, which a class constructor can't wrap.
2844                let err_is_unit = crate::second_type_argument(seg)
2845                    .is_some_and(|ty| #[allow(non_exhaustive_omitted_patterns)] match ty {
    syn::Type::Tuple(t) if t.elems.is_empty() => true,
    _ => false,
}matches!(ty, syn::Type::Tuple(t) if t.elems.is_empty()));
2846                if err_is_unit {
2847                    return None;
2848                }
2849                Self::inner_class_ident(crate::first_type_argument(seg)?)
2850            }
2851            // Bare explicit-handle return (#1375): `-> ExternalPtr<Class>`
2852            // wraps identically to `-> Class` — delegate to
2853            // `inner_class_ident`, which peels the `ExternalPtr` segment.
2854            syn::PathArguments::AngleBracketed(_) if seg.ident == "ExternalPtr" => {
2855                Self::inner_class_ident(ty.as_ref())
2856            }
2857            _ => None,
2858        }
2859    }
2860
2861    /// Returns the bare element type name when this method returns a *list* of
2862    /// values that may be a different registered ExternalPtr-backed class.
2863    ///
2864    /// The list-shaped sibling of
2865    /// [`returns_other_class`](Self::returns_other_class) (#1284). Like the
2866    /// scalar detector it is deliberately syntactic: the write-time resolver
2867    /// checks the complete class registry, and an unregistered element type
2868    /// falls back to the bare list of external pointers.
2869    ///
2870    /// Four shapes are recognized (the element type must pass the same bare
2871    /// capitalized-path filter as the scalar case, optionally through a
2872    /// trailing `ExternalPtr<...>` segment):
2873    /// - `Vec<Class>` — the C wrapper converts via `IntoR` into a `VECSXP` of
2874    ///   external pointers (the `IntoRVecElement` impl emitted by
2875    ///   `#[derive(ExternalPtr)]`), so `.val` is a bare list.
2876    /// - `Option<Vec<Class>>` — the C wrapper converts the whole `Option`
2877    ///   (`ReturnHandling::OptionIntoR`), so `.val` is the same bare list for
2878    ///   `Some` and `NULL` for `None`, which the `lapply` wrap passes through
2879    ///   rather than turning it into `list()`.
2880    /// - `Result<Vec<Class>, E>` where `E` is not `()` — the C wrapper raises
2881    ///   on `Err` (`ReturnHandling::ResultIntoR`); same bare list on `Ok`.
2882    ///   `Result<Vec<Class>, ()>` is excluded: the unit-error sentinel maps to
2883    ///   `ReturnHandling::ResultNullOnErr`, where `.val` can be `NULL`, and
2884    ///   `lapply(NULL, ...)` would silently turn that `NULL` into `list()`.
2885    /// - `Vec<ExternalPtr<Class>>` (the explicit-handle spelling, #1375),
2886    ///   including through the `Option`/`Result` wrappers above — the element
2887    ///   filter is [`inner_class_ident`](Self::inner_class_ident), which peels
2888    ///   the `ExternalPtr` segment, so this resolves identically to
2889    ///   `Vec<Class>`.
2890    ///
2891    /// Not recognized (deliberately):
2892    /// - `Vec<Self>` — `ParsedMethod` doesn't carry the enclosing impl's type
2893    ///   ident, so this detector can't name the target class. Handled instead
2894    ///   by [`returns_self_list`](Self::returns_self_list), a boolean sibling
2895    ///   that `ReturnStrategy::for_method` treats the same as this method
2896    ///   returning `Some`; `MethodReturnBuilder::with_return_class_from_method`
2897    ///   substitutes the actual name using the `type_ident` every call site
2898    ///   already has in scope (#1375).
2899    /// - `Vec<Option<Class>>` — has no `IntoR` impl (the `Vec<Option<T>>`
2900    ///   blanket slot is occupied by the newtype funnel) and would need a
2901    ///   NULL-tolerant per-element wrap; tracked as a follow-up.
2902    pub fn returns_other_class_list(&self) -> Option<syn::Ident> {
2903        let syn::ReturnType::Type(_, ty) = &self.sig.output else {
2904            return None;
2905        };
2906        let syn::Type::Path(p) = ty.as_ref() else {
2907            return None;
2908        };
2909        let seg = p.path.segments.last()?;
2910
2911        match &seg.arguments {
2912            syn::PathArguments::AngleBracketed(_) if seg.ident == "Vec" => {
2913                Self::vec_inner_class_ident(ty)
2914            }
2915            syn::PathArguments::AngleBracketed(_) if seg.ident == "Option" => {
2916                Self::vec_inner_class_ident(crate::first_type_argument(seg)?)
2917            }
2918            syn::PathArguments::AngleBracketed(_) if seg.ident == "Result" => {
2919                // `Result<T, ()>` maps to `ResultNullOnErr` — `.val` may be
2920                // `NULL`, which `lapply` would silently coerce to `list()`.
2921                let err_is_unit = crate::second_type_argument(seg)
2922                    .is_some_and(|ty| #[allow(non_exhaustive_omitted_patterns)] match ty {
    syn::Type::Tuple(t) if t.elems.is_empty() => true,
    _ => false,
}matches!(ty, syn::Type::Tuple(t) if t.elems.is_empty()));
2923                if err_is_unit {
2924                    return None;
2925                }
2926                Self::vec_inner_class_ident(crate::first_type_argument(seg)?)
2927            }
2928            _ => None,
2929        }
2930    }
2931
2932    /// Applies [`inner_class_ident`](Self::inner_class_ident) to the element
2933    /// type of a `Vec<T>`: `ty` must be a `Vec` path whose single type
2934    /// argument is either a bare `syn::Type::Path` or an `ExternalPtr<...>`
2935    /// wrapping one (peeled by `inner_class_ident`, #1375).
2936    pub(crate) fn vec_inner_class_ident(ty: &syn::Type) -> Option<syn::Ident> {
2937        let syn::Type::Path(p) = ty else {
2938            return None;
2939        };
2940        let seg = p.path.segments.last()?;
2941        if seg.ident != "Vec" {
2942            return None;
2943        }
2944        Self::inner_class_ident(crate::first_type_argument(seg)?)
2945    }
2946
2947    /// Shared name filter for [`returns_other_class`](Self::returns_other_class):
2948    /// rejects `Self`, builtin scalar/string names, and known container names;
2949    /// accepts only idents starting with an ASCII-uppercase letter.
2950    fn class_ident_from_ident(ident: &syn::Ident) -> Option<syn::Ident> {
2951        let name = ident.to_string();
2952        if name == "Self"
2953            || is_builtin_return_type_name(&name)
2954            || is_known_return_container_name(&name)
2955        {
2956            return None;
2957        }
2958
2959        name.chars()
2960            .next()
2961            .is_some_and(|c| c.is_ascii_uppercase())
2962            .then(|| ident.clone())
2963    }
2964
2965    /// Applies [`class_ident_from_ident`](Self::class_ident_from_ident) to a
2966    /// container's inner type argument (e.g. the `T` in `Option<T>`).
2967    ///
2968    /// Two shapes qualify:
2969    /// - A bare `syn::Type::Path` with no path arguments of its own — this is
2970    ///   what excludes nested containers like `Option<Vec<T>>`, whose inner
2971    ///   `Vec<T>` carries `PathArguments::AngleBracketed`.
2972    /// - `ExternalPtr<T>` (#1375): the explicit-handle spelling wraps
2973    ///   identically to a bare `T` at the value level (`IntoR for
2974    ///   ExternalPtr<T>` already produces a bare `EXTPTRSXP`), so the handle
2975    ///   is peeled with the same helper the explicit `wrap` path uses.
2976    pub(crate) fn inner_class_ident(ty: &syn::Type) -> Option<syn::Ident> {
2977        let syn::Type::Path(p) = crate::type_inspect::peel_external_ptr(ty) else {
2978            return None;
2979        };
2980        let seg = p.path.segments.last()?;
2981        match &seg.arguments {
2982            syn::PathArguments::None => Self::class_ident_from_ident(&seg.ident),
2983            _ => None,
2984        }
2985    }
2986
2987    /// Returns `true` when this method returns `Vec<Self>` — the
2988    /// receiver-class sibling of
2989    /// [`returns_other_class_list`](Self::returns_other_class_list) that this
2990    /// syntactic detector can't resolve to a *name* on its own, because
2991    /// `ParsedMethod` doesn't carry the enclosing impl's type ident (#1375).
2992    ///
2993    /// `ReturnStrategy::for_method` treats a `true` result exactly like
2994    /// `returns_other_class_list()` returning `Some` (both select
2995    /// `ReturnOtherClassList`); `MethodReturnBuilder::with_return_class_from_method`
2996    /// does the actual name substitution, using the `type_ident` every
2997    /// class-system generator already has in scope — preferred over widening
2998    /// `ParsedMethod` to carry the impl ident (see that method's rustdoc for
2999    /// why: the substituted name must be the Rust type name, which is not
3000    /// always the same string as the R-facing class name).
3001    ///
3002    /// Same three container shapes as `returns_other_class_list`, with the
3003    /// element check inverted (the element must *be* `Self`, not be excluded
3004    /// for being `Self`): `Vec<Self>`, `Option<Vec<Self>>`,
3005    /// `Result<Vec<Self>, E>` (`E` not `()`).
3006    pub fn returns_self_list(&self) -> bool {
3007        let syn::ReturnType::Type(_, ty) = &self.sig.output else {
3008            return false;
3009        };
3010        let syn::Type::Path(p) = ty.as_ref() else {
3011            return false;
3012        };
3013        let Some(seg) = p.path.segments.last() else {
3014            return false;
3015        };
3016
3017        match &seg.arguments {
3018            syn::PathArguments::AngleBracketed(_) if seg.ident == "Vec" => Self::is_vec_of_self(ty),
3019            syn::PathArguments::AngleBracketed(_) if seg.ident == "Option" => {
3020                crate::first_type_argument(seg).is_some_and(Self::is_vec_of_self)
3021            }
3022            syn::PathArguments::AngleBracketed(_) if seg.ident == "Result" => {
3023                // Mirrors the `Result<T, ()>` exclusion in
3024                // `returns_other_class_list`: `ResultNullOnErr`'s `.val` may
3025                // be `NULL`, which `lapply` would silently coerce to `list()`.
3026                let err_is_unit = crate::second_type_argument(seg)
3027                    .is_some_and(|ty| #[allow(non_exhaustive_omitted_patterns)] match ty {
    syn::Type::Tuple(t) if t.elems.is_empty() => true,
    _ => false,
}matches!(ty, syn::Type::Tuple(t) if t.elems.is_empty()));
3028                !err_is_unit && crate::first_type_argument(seg).is_some_and(Self::is_vec_of_self)
3029            }
3030            _ => false,
3031        }
3032    }
3033
3034    /// True when `ty` is `Vec<Self>` — a bare `Self` ident, matching the
3035    /// looser ident-only check [`returns_self`](Self::returns_self) uses (no
3036    /// generic-argument check on `Self` itself, which cannot carry any in
3037    /// this position).
3038    fn is_vec_of_self(ty: &syn::Type) -> bool {
3039        let syn::Type::Path(p) = ty else {
3040            return false;
3041        };
3042        let Some(seg) = p.path.segments.last() else {
3043            return false;
3044        };
3045        if seg.ident != "Vec" {
3046            return false;
3047        }
3048        #[allow(non_exhaustive_omitted_patterns)] match crate::first_type_argument(seg)
    {
    Some(syn::Type::Path(ip)) if
        ip.path.segments.last().map(|s| s.ident == "Self").unwrap_or(false) =>
        true,
    _ => false,
}matches!(crate::first_type_argument(seg), Some(syn::Type::Path(ip))
3049            if ip.path.segments.last().map(|s| s.ident == "Self").unwrap_or(false))
3050    }
3051
3052    /// Returns true if this method returns a reference to `Self` (`&Self` or
3053    /// `&mut Self`) — the idiomatic Rust in-place builder signature.
3054    ///
3055    /// These methods mutate (`&mut self`) or read (`&self`) the receiver and
3056    /// return a borrow of the same value so calls can be chained in Rust
3057    /// (`b.set_a(1).set_b(2)`). On the R side this maps to a pipe-friendly free
3058    /// function (S3) / chainable instance method that returns the *same*
3059    /// ExternalPtr handle, so the R idiom `obj |> set_a(1) |> set_b(2)` works
3060    /// with in-place value semantics (no clone). See
3061    /// [`crate::c_wrapper_builder::ReturnHandling::SelfHandle`].
3062    pub fn returns_self_ref(&self) -> bool {
3063        #[allow(non_exhaustive_omitted_patterns)] match &self.sig.output {
    syn::ReturnType::Type(_, ty) if Self::is_self_ref_type(ty) => true,
    _ => false,
}matches!(&self.sig.output, syn::ReturnType::Type(_, ty) if Self::is_self_ref_type(ty))
3064    }
3065
3066    /// `&Self` / `&mut Self` test shared by the bare and wrapped forms.
3067    fn is_self_ref_type(ty: &syn::Type) -> bool {
3068        #[allow(non_exhaustive_omitted_patterns)] match ty {
    syn::Type::Reference(r) if
        #[allow(non_exhaustive_omitted_patterns)] match r.elem.as_ref() {
            syn::Type::Path(p) if
                p.path.segments.last().map(|s|
                            s.ident == "Self").unwrap_or(false) => true,
            _ => false,
        } => true,
    _ => false,
}matches!(ty, syn::Type::Reference(r)
3069            if matches!(r.elem.as_ref(), syn::Type::Path(p)
3070                if p.path.segments.last().map(|s| s.ident == "Self").unwrap_or(false)))
3071    }
3072
3073    /// First type argument of `Wrapper<..>` when the output's last path segment
3074    /// is `wrapper` (`Result` / `Option`).
3075    fn wrapped_output_arg(&self, wrapper: &str) -> Option<&syn::Type> {
3076        let syn::ReturnType::Type(_, ty) = &self.sig.output else {
3077            return None;
3078        };
3079        let syn::Type::Path(p) = ty.as_ref() else {
3080            return None;
3081        };
3082        let seg = p.path.segments.last()?;
3083        if seg.ident != wrapper {
3084            return None;
3085        }
3086        let syn::PathArguments::AngleBracketed(ab) = &seg.arguments else {
3087            return None;
3088        };
3089        match ab.args.first()? {
3090            syn::GenericArgument::Type(t) => Some(t),
3091            _ => None,
3092        }
3093    }
3094
3095    /// `-> Result<&Self, E>` / `-> Result<&mut Self, E>`: a fallible in-place
3096    /// builder step (#1433). `Ok` hands back the same handle like
3097    /// [`Self::returns_self_ref`]; `Err` raises through the normal `Result`
3098    /// error path.
3099    pub fn returns_result_self_ref(&self) -> bool {
3100        self.wrapped_output_arg("Result")
3101            .is_some_and(Self::is_self_ref_type)
3102    }
3103
3104    /// `-> Option<&Self>` / `-> Option<&mut Self>`: the `Option` sibling of
3105    /// [`Self::returns_result_self_ref`]; `None` returns `NULL` and leaves the
3106    /// object as it was.
3107    pub fn returns_option_self_ref(&self) -> bool {
3108        self.wrapped_output_arg("Option")
3109            .is_some_and(Self::is_self_ref_type)
3110    }
3111
3112    /// `-> Option<..>`: `.val` is `NULL` for `None`, so a cross-class wrap of
3113    /// the value has to let `NULL` through.
3114    pub fn returns_option(&self) -> bool {
3115        self.wrapped_output_arg("Option").is_some()
3116    }
3117
3118    /// Returns true if this method has no return type (returns unit `()`).
3119    pub fn returns_unit(&self) -> bool {
3120        match &self.sig.output {
3121            syn::ReturnType::Default => true,
3122            syn::ReturnType::Type(_, ty) => {
3123                #[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())
3124            }
3125        }
3126    }
3127
3128    /// Whether the R wrapper returns this method's value with `invisible()`
3129    /// (#1213): an `Invisible<T>` return-type marker or the `invisible` method
3130    /// option. Methods are visible by default, including the receiver-returning
3131    /// chainable tails.
3132    pub fn is_invisible(&self) -> bool {
3133        self.visibility_marker
3134            .or(self.method_attrs.force_invisible)
3135            .unwrap_or(false)
3136    }
3137}
3138
3139fn is_builtin_return_type_name(name: &str) -> bool {
3140    #[allow(non_exhaustive_omitted_patterns)] match name {
    "i8" | "i16" | "i32" | "i64" | "i128" | "u8" | "u16" | "u32" | "u64" |
        "u128" | "f32" | "f64" | "bool" | "char" | "str" | "String" | "usize"
        | "isize" | "RLogical" | "Rboolean" | "Rcomplex" => true,
    _ => false,
}matches!(
3141        name,
3142        "i8" | "i16"
3143            | "i32"
3144            | "i64"
3145            | "i128"
3146            | "u8"
3147            | "u16"
3148            | "u32"
3149            | "u64"
3150            | "u128"
3151            | "f32"
3152            | "f64"
3153            | "bool"
3154            | "char"
3155            | "str"
3156            | "String"
3157            | "usize"
3158            | "isize"
3159            | "RLogical"
3160            | "Rboolean"
3161            | "Rcomplex"
3162    )
3163}
3164
3165fn is_known_return_container_name(name: &str) -> bool {
3166    #[allow(non_exhaustive_omitted_patterns)] match name {
    "Vec" | "Option" | "Result" | "Box" | "HashMap" | "BTreeMap" => true,
    _ => false,
}matches!(
3167        name,
3168        "Vec" | "Option" | "Result" | "Box" | "HashMap" | "BTreeMap"
3169    )
3170}
3171
3172impl ParsedImpl {
3173    /// Parse an impl block with class system attribute.
3174    ///
3175    /// Note: Trait impls (`impl Trait for Type`) are handled by `expand_impl`
3176    /// before this function is called, so we only handle inherent impls here.
3177    pub fn parse(attrs: ImplAttrs, item_impl: syn::ItemImpl) -> syn::Result<Self> {
3178        // Extract type identifier
3179        let type_ident =
3180            match item_impl.self_ty.as_ref() {
3181                syn::Type::Path(p) => p.path.segments.last().map(|s| s.ident.clone()).ok_or_else(
3182                    || {
3183                        syn::Error::new_spanned(
3184                            &item_impl.self_ty,
3185                            "#[miniextendr] impl blocks require a named type (e.g., `impl MyType`)",
3186                        )
3187                    },
3188                )?,
3189                _ => {
3190                    return Err(syn::Error::new_spanned(
3191                        &item_impl.self_ty,
3192                        "#[miniextendr] impl blocks require a named struct type. \
3193                     Found a non-path type. Use `impl MyStruct { ... }` with a concrete struct.",
3194                    ));
3195                }
3196            };
3197
3198        // Reject type/const generics — the generated #[no_mangle] C wrappers are
3199        // incompatible with type/const params (they require monomorphization → multiple
3200        // symbols). Lifetime params ARE allowed: lifetimes are erased at codegen and the
3201        // wrapper generation uses `type_ident` (the bare struct ident) without generic
3202        // args, which is correct because lifetime arguments are never needed in generated
3203        // code (they are inferred or elided).
3204        {
3205            let params = &item_impl.generics.params;
3206            let has_type_or_const = params
3207                .iter()
3208                .any(|p| #[allow(non_exhaustive_omitted_patterns)] match p {
    syn::GenericParam::Type(_) | syn::GenericParam::Const(_) => true,
    _ => false,
}matches!(p, syn::GenericParam::Type(_) | syn::GenericParam::Const(_)));
3209
3210            if has_type_or_const {
3211                return Err(syn::Error::new_spanned(
3212                    &item_impl.generics,
3213                    "generic impl blocks are not supported by #[miniextendr]. \
3214                     R's .Call interface requires monomorphic C symbols, so generic type \
3215                     parameters cannot be used. Remove the generic parameters and use a \
3216                     concrete type instead. \
3217                     Explicit lifetime parameters are allowed (lifetimes are erased at codegen).",
3218                ));
3219            }
3220        }
3221
3222        // Reject unsupported attributes on the impl block
3223        for attr in &item_impl.attrs {
3224            if attr.path().is_ident("export_name") {
3225                return Err(syn::Error::new_spanned(
3226                    attr,
3227                    "#[export_name] is not supported with #[miniextendr]; \
3228                     the macro generates its own C symbol names",
3229                ));
3230            }
3231        }
3232
3233        // The class block renders no page under `@noRd` or a plain `noexport`
3234        // (`ClassDocBuilder::build`'s gate: `internal`, as the attribute or the
3235        // `@keywords internal` tag, keeps the page). Its docs and every
3236        // method's (R6 folds its method blocks into the class block) then
3237        // keep no links (#1818).
3238        let class_page = crate::roxygen::RdPage::suppressed_if(
3239            crate::roxygen::attrs_have_roxygen_tag(&item_impl.attrs, "noRd")
3240                || (attrs.noexport
3241                    && !attrs.internal
3242                    && !crate::roxygen::attrs_have_roxygen_tag(
3243                        &item_impl.attrs,
3244                        "keywords internal",
3245                    )),
3246        );
3247
3248        // Parse methods and validate attributes. Method parsing also normalizes
3249        // raw variadic `...` syntax in the impl clone that gets re-emitted.
3250        let mut original_impl = item_impl.clone();
3251        let mut methods = Vec::new();
3252        for item in &mut original_impl.items {
3253            if let syn::ImplItem::Fn(fn_item) = item {
3254                let mut method =
3255                    ParsedMethod::from_impl_item(fn_item, class_page, attrs.method_coerce_default)?;
3256                crate::s7_conversion::configure(
3257                    &mut method,
3258                    fn_item,
3259                    attrs.class_system,
3260                    &type_ident,
3261                )?;
3262                // Validate method attributes for this class system
3263                ParsedMethod::validate_method_attrs(
3264                    &method.method_attrs,
3265                    attrs.class_system,
3266                    fn_item.sig.ident.span(),
3267                )?;
3268                if method.method_attrs.serde_error.is_some()
3269                    && !crate::return_type_analysis::output_is_result(&fn_item.sig.output)
3270                {
3271                    return Err(syn::Error::new(
3272                        fn_item.sig.ident.span(),
3273                        "`#[miniextendr(serde_error(..))]` requires a `Result<T, E>` return type: it \
3274                         classes the condition raised from the `Err` arm",
3275                    ));
3276                }
3277                methods.push(method);
3278            }
3279        }
3280
3281        // MXL120: For vctrs impls, reject constructors that return Self or the named type,
3282        // and reject all instance-method receivers (&self, &mut self, self, self: ExternalPtr<Self>).
3283        //
3284        // The generated R wrapper passes the constructor result to vctrs::new_vctr() (or
3285        // new_rcrd/new_list_of), which requires a plain vector — not an ExternalPtr.
3286        // Returning Self produces an EXTPTRSXP which new_vctr rejects with
3287        // ".data must be a vector type".
3288        //
3289        // Instance-method receivers (&self, &mut self, etc.) are equally broken: the vctrs
3290        // S3 dispatch passes the R object (an S3-classed base vector — REALSXP, INTSXP, etc.)
3291        // as `self_sexp`. The C wrapper's receiver prelude (`resolve_receiver`, then
3292        // `ErasedExternalPtr::from_sexp`) panics because the base vector is not an ExternalPtr
3293        // and carries no `.ptr`.  There is no Rust `Self`
3294        // stored anywhere — the vector payload IS the R object.  Instance methods must be
3295        // expressed as static methods receiving the vector data by parameter.
3296        if attrs.class_system == ClassSystem::Vctrs {
3297            for method in &methods {
3298                // Check 1: constructor return type
3299                let is_ctor = (method.method_attrs.constructor
3300                    || (method.env == ReceiverKind::None && method.ident == "new"))
3301                    && method.env != ReceiverKind::Ref
3302                    && method.env != ReceiverKind::RefMut;
3303                if is_ctor && vctrs_ctor_returns_self_or_type(&method.sig.output, &type_ident) {
3304                    return Err(syn::Error::new_spanned(
3305                        &method.sig.output,
3306                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("[MXL120] vctrs constructor `{0}` must not return `Self` or `{1}`.\n\nThe generated R wrapper passes the constructor result to `vctrs::new_vctr()` (or `new_rcrd`/`new_list_of`), which requires a plain vector payload — not an ExternalPtr (`EXTPTRSXP`).\n\nFix: return the vector payload directly instead of `Self`.\nFor example, return `Vec<f64>` (for vctr), a `std::collections::HashMap` / named-list struct (for rcrd), or a `Vec<Vec<T>>` (for list_of).",
                method.ident, type_ident))
    })format!(
3307                            "[MXL120] vctrs constructor `{}` must not return `Self` or `{}`.\n\
3308                             \n\
3309                             The generated R wrapper passes the constructor result to \
3310                             `vctrs::new_vctr()` (or `new_rcrd`/`new_list_of`), which requires a \
3311                             plain vector payload — not an ExternalPtr (`EXTPTRSXP`).\n\
3312                             \n\
3313                             Fix: return the vector payload directly instead of `Self`.\n\
3314                             For example, return `Vec<f64>` (for vctr), a `std::collections::HashMap` \
3315                             / named-list struct (for rcrd), or a `Vec<Vec<T>>` (for list_of).",
3316                            method.ident, type_ident
3317                        ),
3318                    ));
3319                }
3320
3321                // Check 2: instance-method receivers are not supported on vctrs impls
3322                if method.env.is_instance() {
3323                    let receiver_spelling = match method.env {
3324                        ReceiverKind::Ref => "&self",
3325                        ReceiverKind::RefMut => "&mut self",
3326                        ReceiverKind::Value => "self",
3327                        ReceiverKind::ExternalPtrRef => "self: ExternalPtrRef<'_, Self>",
3328                        ReceiverKind::ExternalPtrMut => "self: ExternalPtrMut<'_, Self>",
3329                        ReceiverKind::ExternalPtrValue => "self: ExternalPtr<Self>",
3330                        ReceiverKind::None => ::core::panicking::unreachable_default_msg()unreachable!(),
3331                    };
3332                    return Err(syn::Error::new_spanned(
3333                        &method.ident,
3334                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("[MXL120] vctrs impl method `{0}` uses a `{1}` receiver, which is not supported on `#[miniextendr(vctrs(...))]` impls.\n\nA vctrs object is an S3-classed base vector (REALSXP, INTSXP, etc.). There is no Rust `Self` stored inside the R SEXP — the vector payload IS the R object.  The C wrapper cannot reconstruct `Self` from a base vector, so calling an instance method would panic at runtime.\n\nFix: convert this method to a static method whose parameters receive the vector data directly.  For example:\n\n// Before (broken):\n// pub fn value(&self) -> f64 {{ ... }}\n\n// After (correct):\n// pub fn value(amounts: Vec<f64>) -> Vec<f64> {{ ... }}",
                method.ident, receiver_spelling))
    })format!(
3335                            "[MXL120] vctrs impl method `{}` uses a `{}` receiver, which is not \
3336                             supported on `#[miniextendr(vctrs(...))]` impls.\n\
3337                             \n\
3338                             A vctrs object is an S3-classed base vector (REALSXP, INTSXP, etc.). \
3339                             There is no Rust `Self` stored inside the R SEXP — the vector payload \
3340                             IS the R object.  The C wrapper cannot reconstruct `Self` from a base \
3341                             vector, so calling an instance method would panic at runtime.\n\
3342                             \n\
3343                             Fix: convert this method to a static method whose parameters receive \
3344                             the vector data directly.  For example:\n\
3345                             \n\
3346                             // Before (broken):\n\
3347                             // pub fn value(&self) -> f64 {{ ... }}\n\
3348                             \n\
3349                             // After (correct):\n\
3350                             // pub fn value(amounts: Vec<f64>) -> Vec<f64> {{ ... }}",
3351                            method.ident, receiver_spelling
3352                        ),
3353                    ));
3354                }
3355            }
3356        }
3357
3358        // Extract cfg attributes
3359        let cfg_attrs: Vec<_> = item_impl
3360            .attrs
3361            .iter()
3362            .filter(|attr| attr.path().is_ident("cfg"))
3363            .cloned()
3364            .collect();
3365        let raw_doc_tags = crate::roxygen::roxygen_tags_from_attrs(&item_impl.attrs, class_page);
3366        // For R6: keep class-level @param tags (roxygen2 8.0.0 inherits them into
3367        // all methods); for other class systems use the stricter filter. Each
3368        // stripped tag's warning lives in its own anonymous `const _: () = { .. };`
3369        // scope (#1118), so no per-block disambiguator is needed here.
3370        let (doc_tags, param_warnings) = if attrs.class_system == ClassSystem::R6 {
3371            crate::roxygen::strip_method_tags_r6(
3372                &raw_doc_tags,
3373                &type_ident.to_string(),
3374                item_impl.impl_token.span,
3375            )
3376        } else {
3377            crate::roxygen::strip_method_tags(
3378                &raw_doc_tags,
3379                &type_ident.to_string(),
3380                item_impl.impl_token.span,
3381            )
3382        };
3383        // Build the set of parameter names declared at class level so the R6
3384        // generator can suppress placeholder lines for covered params.
3385        let class_param_names = crate::roxygen::extract_param_names(&doc_tags);
3386
3387        let parsed = ParsedImpl {
3388            type_ident,
3389            class_system: attrs.class_system,
3390            class_name: attrs.class_name,
3391            doc_tags,
3392            methods,
3393            // Strip miniextendr attributes (and roxygen tags) before re-emitting,
3394            // then rewrite ExternalPtr receivers for stable Rust compatibility.
3395            original_impl: rewrite_external_ptr_receivers(strip_miniextendr_attrs_from_impl(
3396                original_impl,
3397            )),
3398            cfg_attrs,
3399            vctrs_attrs: attrs.vctrs_attrs,
3400            r6_inherit: attrs.r6_inherit,
3401            r6_portable: attrs.r6_portable,
3402            r6_cloneable: attrs.r6_cloneable,
3403            r6_lock_objects: attrs.r6_lock_objects,
3404            r6_lock_class: attrs.r6_lock_class,
3405            s7_parent: attrs.s7_parent,
3406            s7_abstract: attrs.s7_abstract,
3407            r_data_accessors: attrs.r_data_accessors,
3408            field_lookup: attrs.field_lookup,
3409            field_fallback: attrs.field_fallback,
3410            strict: attrs.strict,
3411            preconditions: attrs.preconditions,
3412            internal: attrs.internal,
3413            noexport: attrs.noexport,
3414            constructor_demoted: false,
3415            param_warnings,
3416            class_param_names,
3417        };
3418        parsed.check_constructor_markers()?;
3419        parsed.reject_unsupported_describe_in()?;
3420        field_syntax::check_collisions(&parsed)?;
3421        Ok(parsed)
3422    }
3423
3424    /// Reject a method-level `@describeIn` that roxygen2 cannot honour (#1590).
3425    ///
3426    /// roxygen2 lists a `@describeIn` block in its destination's "Functions"
3427    /// section through the R object the block documents, and rejects the tag
3428    /// next to `@name` / `@rdname`, so `MethodDocBuilder` drops both for it.
3429    /// That only works where the method's block sits on a plain R function or
3430    /// S3 method: S3 instance methods (`generic.Class`), the static methods of
3431    /// S3 / S4 / S7 / vctrs (`class_method()`), and the S4 constructor
3432    /// (`Class()`). Everywhere else the block has no object to list:
3433    ///
3434    /// - S4 / S7 instance methods are registered by `setMethod()` /
3435    ///   `S7::method<-` after the `if (!exists(...))` generic guard the block
3436    ///   is attached to;
3437    /// - Env and R6 methods are `Class$method <-` assignments or live inside
3438    ///   `R6Class()`;
3439    /// - the S3 / vctrs / S7 constructor is documented by the class block.
3440    ///
3441    /// There the tag would only earn a roxygen2 warning and a dropped block,
3442    /// so it is a compile error pointing at `@rdname` instead.
3443    fn reject_unsupported_describe_in(&self) -> syn::Result<()> {
3444        for method in self.included_methods() {
3445            if crate::roxygen::describe_in_topic(&method.doc_tags).is_none() {
3446                continue;
3447            }
3448            let is_ctor = self.is_method_constructor(method);
3449            let is_static = method.env == ReceiverKind::None && !is_ctor;
3450            let supported = match self.class_system {
3451                ClassSystem::S3 | ClassSystem::Vctrs => !is_ctor,
3452                ClassSystem::S4 => is_ctor || is_static,
3453                ClassSystem::S7 => is_static,
3454                ClassSystem::Env | ClassSystem::R6 => false,
3455            };
3456            if supported {
3457                continue;
3458            }
3459            let kind = if is_ctor {
3460                "constructor"
3461            } else if is_static {
3462                "static method"
3463            } else {
3464                "instance method"
3465            };
3466            let system = match self.class_system {
3467                ClassSystem::S3 => "S3",
3468                ClassSystem::Vctrs => "vctrs",
3469                ClassSystem::S4 => "S4",
3470                ClassSystem::S7 => "S7",
3471                ClassSystem::Env => "Env",
3472                ClassSystem::R6 => "R6",
3473            };
3474            return Err(syn::Error::new_spanned(
3475                &method.ident,
3476                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`@describeIn` is not supported on the {1} {2} `{0}`: its R wrapper is not an R function roxygen2 can list in the destination\'s \"Functions\" section, so roxygen2 would drop the block. Use `@rdname <topic>` to document it on that page instead. `@describeIn` works on S3 instance methods, on the static methods of S3, S4, S7 and vctrs classes, and on S4 constructors.",
                method.ident, system, kind))
    })format!(
3477                    "`@describeIn` is not supported on the {system} {kind} `{}`: its R wrapper \
3478                     is not an R function roxygen2 can list in the destination's \"Functions\" \
3479                     section, so roxygen2 would drop the block. Use `@rdname <topic>` to \
3480                     document it on that page instead. `@describeIn` works on S3 instance \
3481                     methods, on the static methods of S3, S4, S7 and vctrs classes, and on \
3482                     S4 constructors.",
3483                    method.ident,
3484                ),
3485            ));
3486        }
3487        Ok(())
3488    }
3489
3490    /// Get the class name (override or type name).
3491    pub fn class_name(&self) -> String {
3492        self.class_name
3493            .clone()
3494            .unwrap_or_else(|| self.type_ident.to_string())
3495    }
3496
3497    /// The class-level settings, written like the attribute, which every impl
3498    /// block of a type must spell the same (#1776): the class system with its
3499    /// options, `class = "..."`, `internal` / `noexport`, and the `@noRd` /
3500    /// `@keywords internal` tags. They shape the members each block
3501    /// generates, so the wrapper writer refuses blocks that differ. The
3502    /// per-method defaults (`strict`, `preconditions`) may differ. A field
3503    /// fallback (`fallback = "..."`, #2150) is no setting: one block has it,
3504    /// as one has the constructor ([`class_definitions`](Self::class_definitions)).
3505    pub fn class_settings(&self) -> String {
3506        let mut options: Vec<String> = Vec::new();
3507        match self.class_system {
3508            ClassSystem::Vctrs => {
3509                let vctrs = &self.vctrs_attrs;
3510                let kind = match vctrs.kind {
3511                    VctrsKind::Vctr => "vctr",
3512                    VctrsKind::Rcrd => "rcrd",
3513                    VctrsKind::ListOf => "list_of",
3514                };
3515                options.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("kind = {0:?}", kind))
    })format!("kind = {kind:?}"));
3516                if let Some(base) = &vctrs.base {
3517                    options.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("base = {0:?}", base))
    })format!("base = {base:?}"));
3518                }
3519                if let Some(inherit) = vctrs.inherit_base_type {
3520                    options.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("inherit_base_type = {0}", inherit))
    })format!("inherit_base_type = {inherit}"));
3521                }
3522                if let Some(ptype) = &vctrs.ptype {
3523                    options.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("ptype = {0:?}", ptype))
    })format!("ptype = {ptype:?}"));
3524                }
3525                if let Some(abbr) = &vctrs.abbr {
3526                    options.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("abbr = {0:?}", abbr))
    })format!("abbr = {abbr:?}"));
3527                }
3528            }
3529            ClassSystem::R6 => {
3530                if let Some(inherit) = &self.r6_inherit {
3531                    options.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("inherit = {0:?}", inherit))
    })format!("inherit = {inherit:?}"));
3532                }
3533                for (name, value) in [
3534                    ("portable", self.r6_portable),
3535                    ("cloneable", self.r6_cloneable),
3536                    ("lock_objects", self.r6_lock_objects),
3537                    ("lock_class", self.r6_lock_class),
3538                ] {
3539                    if let Some(value) = value {
3540                        options.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} = {1}", name, value))
    })format!("{name} = {value}"));
3541                    }
3542                }
3543            }
3544            ClassSystem::S7 => {
3545                if let Some(parent) = &self.s7_parent {
3546                    options.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("parent = {0:?}", parent))
    })format!("parent = {parent:?}"));
3547                }
3548                if self.s7_abstract {
3549                    options.push("abstract".to_string());
3550                }
3551            }
3552            ClassSystem::Env | ClassSystem::S3 | ClassSystem::S4 => {}
3553        }
3554        match self.r_data_accessors {
3555            RDataAccessors::Off => {}
3556            RDataAccessors::GetSet => options.push("r_data_accessors".to_string()),
3557            RDataAccessors::GetOnly => options.push("r_data_accessors = \"get\"".to_string()),
3558            RDataAccessors::ReadOnly => {
3559                options.push("r_data_accessors = \"read_only\"".to_string());
3560            }
3561        }
3562        if self.field_lookup == FieldLookup::List {
3563            options.push("lookup = \"list\"".to_string());
3564        }
3565
3566        let system = self.class_system.to_ident().to_string();
3567        let mut settings = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [if options.is_empty() {
                    system
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{1}({0})",
                                    options.join(", "), system))
                        })
                }]))vec![if options.is_empty() {
3568            system
3569        } else {
3570            format!("{system}({})", options.join(", "))
3571        }];
3572        if let Some(class_name) = &self.class_name {
3573            settings.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("class = {0:?}", class_name))
    })format!("class = {class_name:?}"));
3574        }
3575        if self.internal {
3576            settings.push("internal".to_string());
3577        }
3578        if self.noexport {
3579            settings.push("noexport".to_string());
3580        }
3581        for tag in CLASS_SETTING_TAGS {
3582            if crate::roxygen::has_roxygen_tag(&self.doc_tags, tag) {
3583                settings.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("@{0}", tag))
    })format!("@{tag}"));
3584            }
3585        }
3586        settings.join(", ")
3587    }
3588
3589    /// What this impl block has that only one block of a type may: the
3590    /// constructor, S7 properties and the field fallback (#2150). The
3591    /// wrapper writer defines the class from the block that has them (#1776),
3592    /// so the field methods that call the fallback are that block's; the
3593    /// impl docs of every block merge into the class's roxygen block
3594    /// ([`ClassWrapper::class_docs`]).
3595    pub fn class_definitions(&self) -> Vec<String> {
3596        let mut definitions = Vec::new();
3597        if self.declared_constructor().is_some() {
3598            definitions.push("a constructor".to_string());
3599        } else if let Some(inferred) = self.inferred_constructor() {
3600            definitions.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the inferred constructor `{0}`",
                inferred.ident))
    })format!("the inferred constructor `{}`", inferred.ident));
3601        }
3602        if self.class_system == ClassSystem::S7
3603            && self.included_methods().any(|m| {
3604                let s7 = &m.method_attrs.s7;
3605                s7.getter || s7.setter || s7.validate
3606            })
3607        {
3608            definitions.push("S7 properties".to_string());
3609        }
3610        if self.field_fallback.is_some() {
3611            definitions.push("the field fallback".to_string());
3612        }
3613        definitions
3614    }
3615
3616    /// Get methods that should be included.
3617    pub fn included_methods(&self) -> impl Iterator<Item = &ParsedMethod> {
3618        self.methods.iter().filter(|m| m.should_include())
3619    }
3620
3621    /// The class constructor of this impl block, if it has one: the
3622    /// [declared](Self::declared_constructor) constructor, else the
3623    /// [inferred](Self::inferred_constructor) one. Every other receiver-less
3624    /// method is a static method.
3625    pub fn constructor(&self) -> Option<&ParsedMethod> {
3626        self.declared_constructor()
3627            .or_else(|| self.inferred_constructor())
3628    }
3629
3630    /// The constructor the block declares: the method marked
3631    /// `#[miniextendr(<system>(constructor))]` (at most one,
3632    /// [`check_constructor_markers`](Self::check_constructor_markers)), else
3633    /// a receiver-less `new` returning `Self`. For vctrs, `new` may return
3634    /// anything: the canonical vctrs constructor returns the vector payload
3635    /// (e.g. `Vec<f64>`), which `vctrs::new_vctr()` then wraps; returning
3636    /// `Self` would produce an `ExternalPtr` that `new_vctr` can't accept as
3637    /// `.data`.
3638    pub fn declared_constructor(&self) -> Option<&ParsedMethod> {
3639        self.included_methods()
3640            .find(|m| m.method_attrs.constructor)
3641            .or_else(|| {
3642                self.included_methods().find(|m| {
3643                    m.env == ReceiverKind::None
3644                        && m.ident == "new"
3645                        && (self.class_system == ClassSystem::Vctrs || m.returns_self())
3646                })
3647            })
3648    }
3649
3650    /// The methods that could be the class constructor: the receiver-less
3651    /// methods returning `Self` (bare `Self`, as [`ParsedMethod::returns_self`]
3652    /// reads it, so not `Result<Self, E>` or `Option<Self>`), other than the
3653    /// declared constructor and an S7 `convert_from` method, in source order.
3654    /// Without a declared constructor, the one candidate of a type is its
3655    /// constructor; with several, the type needs a declared one. None for
3656    /// vctrs, whose constructor returns the vector payload rather than `Self`.
3657    pub fn constructor_candidates(&self) -> impl Iterator<Item = &ParsedMethod> {
3658        let declared = self.declared_constructor();
3659        self.included_methods().filter(move |m| {
3660            self.class_system != ClassSystem::Vctrs
3661                && m.env == ReceiverKind::None
3662                && m.returns_self()
3663                && m.method_attrs.s7.convert_from.is_none()
3664                && !declared.is_some_and(|d| std::ptr::eq(d, *m))
3665        })
3666    }
3667
3668    /// The constructor this block infers: its one
3669    /// [candidate](Self::constructor_candidates), whatever its name, when it
3670    /// declares no constructor. None in the rendering for a type whose
3671    /// constructor another impl block declares
3672    /// ([`constructor_demoted`](Self::constructor_demoted)). The wrapper
3673    /// writer decides per type which rendering it writes.
3674    pub fn inferred_constructor(&self) -> Option<&ParsedMethod> {
3675        if self.constructor_demoted || self.declared_constructor().is_some() {
3676            return None;
3677        }
3678        let mut candidates = self.constructor_candidates();
3679        let first = candidates.next()?;
3680        candidates.next().is_none().then_some(first)
3681    }
3682
3683    /// Whether `m` is the class [constructor](Self::constructor).
3684    fn is_method_constructor(&self, m: &ParsedMethod) -> bool {
3685        self.constructor().is_some_and(|c| std::ptr::eq(c, m))
3686    }
3687
3688    /// The roxygen tags of the static method `m`, called as `call` (e.g.
3689    /// `Counter$from_value()`). The constructor under its own name
3690    /// ([`constructor_keeps_own_name`](Self::constructor_keeps_own_name))
3691    /// points at the class constructor `constructor` (e.g. `Counter$new()`)
3692    /// instead of repeating its docs, keeping the method's `@noRd` /
3693    /// `@keywords`, and its `@param` tags when `params` (roxygen2 merges them
3694    /// with the class constructor's).
3695    fn static_doc_tags<'a>(
3696        &self,
3697        m: &'a ParsedMethod,
3698        call: &str,
3699        constructor: &str,
3700        params: bool,
3701    ) -> std::borrow::Cow<'a, [String]> {
3702        if !self.is_method_constructor(m) {
3703            return std::borrow::Cow::Borrowed(&m.doc_tags);
3704        }
3705        let kept = |tag: &&String| {
3706            let name = tag.split_whitespace().next().unwrap_or("");
3707            name == "@noRd" || name == "@keywords" || (params && name == "@param")
3708        };
3709        let mut tags = ::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!("@description `{0}` is another name for the constructor `{1}`.",
                                call, constructor))
                    })]))vec![format!(
3710            "@description `{call}` is another name for the constructor `{constructor}`."
3711        )];
3712        tags.extend(m.doc_tags.iter().filter(kept).cloned());
3713        std::borrow::Cow::Owned(tags)
3714    }
3715
3716    /// Refuse two methods marked `#[miniextendr(<system>(constructor))]`: a
3717    /// class has one constructor.
3718    fn check_constructor_markers(&self) -> syn::Result<()> {
3719        let marker = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#[miniextendr({0}(constructor))]",
                self.class_system.to_ident()))
    })format!(
3720            "#[miniextendr({}(constructor))]",
3721            self.class_system.to_ident()
3722        );
3723        let mut marked = self
3724            .included_methods()
3725            .filter(|m| m.method_attrs.constructor);
3726        if let (Some(first), Some(second)) = (marked.next(), marked.next()) {
3727            return Err(syn::Error::new_spanned(
3728                &second.ident,
3729                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` and `{1}` are both marked `{2}`; a class has one constructor. Drop the marker from one: it becomes a static method.",
                first.ident, second.ident, marker))
    })format!(
3730                    "`{}` and `{}` are both marked `{marker}`; a class has one constructor. \
3731                     Drop the marker from one: it becomes a static method.",
3732                    first.ident, second.ident,
3733                ),
3734            ));
3735        }
3736        Ok(())
3737    }
3738
3739    /// Get public instance methods (have env, not private, not active, not an
3740    /// R6 finalizer or `deep_clone` handler).
3741    pub fn public_instance_methods(&self) -> impl Iterator<Item = &ParsedMethod> {
3742        self.methods.iter().filter(|m| {
3743            m.should_include()
3744                && m.env.is_instance()
3745                && !m.is_constructor()
3746                && !m.is_finalizer()
3747                && !m.method_attrs.r6.deep_clone
3748                && !m.is_private()
3749                && !m.is_active()
3750        })
3751    }
3752
3753    /// Get private instance methods (have env, private visibility, not active).
3754    pub fn private_instance_methods(&self) -> impl Iterator<Item = &ParsedMethod> {
3755        self.methods.iter().filter(|m| {
3756            m.should_include()
3757                && m.env.is_instance()
3758                && !m.is_constructor()
3759                && !m.is_finalizer()
3760                && m.is_private()
3761                && !m.is_active()
3762        })
3763    }
3764
3765    /// Get active binding getter methods for R6 (have env, marked active, not setter).
3766    /// Active bindings provide property-like access (obj$name instead of obj$name()).
3767    pub fn active_instance_methods(&self) -> impl Iterator<Item = &ParsedMethod> {
3768        self.methods.iter().filter(|m| {
3769            m.should_include()
3770                && m.env.is_instance()
3771                && !m.is_constructor()
3772                && !m.is_finalizer()
3773                && m.is_active()
3774                && !m.method_attrs.r6.setter // Exclude setters
3775        })
3776    }
3777
3778    /// Get active binding setter methods for R6 (have env, marked as r6_setter).
3779    pub fn active_setter_methods(&self) -> impl Iterator<Item = &ParsedMethod> {
3780        self.methods
3781            .iter()
3782            .filter(|m| m.should_include() && m.env.is_instance() && m.method_attrs.r6.setter)
3783    }
3784
3785    /// Find the setter method for a given property name.
3786    pub fn find_setter_for_prop(&self, prop_name: &str) -> Option<&ParsedMethod> {
3787        self.active_setter_methods().find(|m| {
3788            // Match by explicit prop name or by method name with "set_" prefix removed
3789            if let Some(ref explicit_prop) = m.method_attrs.r6.prop {
3790                explicit_prop == prop_name
3791            } else {
3792                // Try to match by stripping "set_" prefix from method name
3793                let method_name = crate::naming::ident_name(&m.ident);
3794                method_name.strip_prefix("set_").unwrap_or(&method_name) == prop_name
3795            }
3796        })
3797    }
3798
3799    /// Get instance methods (have env) - includes both public and private.
3800    pub fn instance_methods(&self) -> impl Iterator<Item = &ParsedMethod> {
3801        self.methods.iter().filter(|m| {
3802            m.should_include() && m.env.is_instance() && !m.is_constructor() && !m.is_finalizer()
3803        })
3804    }
3805
3806    /// Get static methods (no env, not finalizer): the receiver-less methods
3807    /// other than the constructor, and the constructor too when its R name
3808    /// isn't `new` ([`constructor_keeps_own_name`](Self::constructor_keeps_own_name)).
3809    pub fn static_methods(&self) -> impl Iterator<Item = &ParsedMethod> {
3810        self.methods.iter().filter(|m| {
3811            m.should_include()
3812                && m.env == ReceiverKind::None
3813                && (!self.is_method_constructor(m) || self.constructor_keeps_own_name(m))
3814                && !m.is_finalizer()
3815        })
3816    }
3817
3818    /// Whether the constructor `m` is also a static method under its own
3819    /// name: `Type$from_value()` next to `Type$new()`, `Type_from_value()`
3820    /// next to `Type()`, `type_from_value()` next to `new_type()`. A
3821    /// constructor named `new` has no second name, and a vctrs constructor
3822    /// returns the vector payload, which only `new_<class>()` classes.
3823    fn constructor_keeps_own_name(&self, m: &ParsedMethod) -> bool {
3824        self.class_system != ClassSystem::Vctrs && m.r_method_name() != "new"
3825    }
3826
3827    /// Get methods with `#[miniextendr(as = "...")]` attribute.
3828    ///
3829    /// These generate S3 methods for R's `as.<class>()` generics like
3830    /// `as.data.frame.MyType`, `as.list.MyType`, etc.
3831    pub fn as_coercion_methods(&self) -> impl Iterator<Item = &ParsedMethod> {
3832        self.methods
3833            .iter()
3834            .filter(|m| m.should_include() && m.method_attrs.as_coercion.is_some())
3835    }
3836
3837    /// Get the finalizer method, if any.
3838    pub fn finalizer(&self) -> Option<&ParsedMethod> {
3839        self.methods
3840            .iter()
3841            .find(|m| m.should_include() && m.is_finalizer())
3842    }
3843}
3844
3845/// Generate a C-callable wrapper function for a single method in an impl block.
3846///
3847/// Produces a `#[no_mangle] extern "C-unwind"` function named `C_{crate}_{Type}__{method}` that:
3848/// 1. Accepts SEXP arguments (including `self_sexp` for instance methods)
3849/// 2. Extracts `&self` / `&mut self` from an `ErasedExternalPtr` for instance methods
3850/// 3. Converts SEXP arguments to Rust types
3851/// 4. Calls the actual Rust method
3852/// 5. Converts the return value back to SEXP
3853///
3854/// The wrapper runs on R's main thread.
3855///
3856/// Also emits an `R_CallMethodDef` constant for R routine registration.
3857///
3858/// # Arguments
3859///
3860/// * `parsed_impl` - The parsed impl block providing type identity, cfg attrs, and options
3861/// * `method` - The parsed method to generate a wrapper for
3862pub fn generate_method_c_wrapper(parsed_impl: &ParsedImpl, method: &ParsedMethod) -> TokenStream {
3863    use crate::c_wrapper_builder::{CWrapperContext, ReturnHandling};
3864
3865    let type_ident = &parsed_impl.type_ident;
3866    let method_ident = &method.ident;
3867    let c_ident = method.c_wrapper_ident(type_ident);
3868    let self_sexp = crate::naming::self_sexp_ident();
3869    let self_ptr = syn::Ident::new("self_ptr", proc_macro2::Span::mixed_site());
3870    let self_ref = syn::Ident::new("self_ref", proc_macro2::Span::mixed_site());
3871    let self_slot = syn::Ident::new("self_slot", proc_macro2::Span::mixed_site());
3872    let external_ptr = syn::Ident::new("__self_ptr", proc_macro2::Span::mixed_site());
3873    let taken = syn::Ident::new("__mx_taken", proc_macro2::Span::mixed_site());
3874
3875    // Build rust arguments from the signature, with the `rng` wrapper's guard
3876    // back at the `&RngGuard` parameter's position (#2002)
3877    let mut rust_args: Vec<TokenStream> = method
3878        .sig
3879        .inputs
3880        .iter()
3881        .filter_map(|arg| {
3882            if let syn::FnArg::Typed(pt) = arg
3883                && let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
3884            {
3885                let ident = &pat_ident.ident;
3886                Some({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&ident, &mut _s);
    _s
}quote! { #ident })
3887            } else {
3888                None
3889            }
3890        })
3891        .collect();
3892    if let Some(index) = method.rng_guard {
3893        rust_args.insert(index, crate::type_inspect::rng_guard_arg());
3894    }
3895
3896    /// How a consuming (`self` by value) receiver is handled (#1432).
3897    #[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ValueMode {
}
#[automatically_derived]impl ::core::clone::Clone for ValueMode {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ValueMode { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for ValueMode
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ValueMode {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ValueMode { }Eq)]
3898    enum ValueMode {
3899        /// `-> Self`: move out, call, write the result back into the same slot.
3900        WriteBack,
3901        /// `-> Result<Self, E>` / `-> Option<Self>`: call on a clone, overwrite on success.
3902        Fallible,
3903        /// Any other return: move out, call, leave the slot consumed.
3904        Terminal,
3905    }
3906    let value_mode = if method.returns_self() {
3907        ValueMode::WriteBack
3908    } else if method.returns_result_self() || method.returns_option_self() {
3909        ValueMode::Fallible
3910    } else {
3911        ValueMode::Terminal
3912    };
3913
3914    // Generate self extraction for instance methods. Each receiver borrows
3915    // the value's RefCell for the whole call (shared for `&self`, exclusive
3916    // otherwise), so a callback into R that reaches the same object gets the
3917    // `miniextendr_borrow_conflict` error instead of a second reference. The
3918    // receiver is resolved before the arguments are converted and borrowed
3919    // (or moved out) after: an R error that longjmps out of an argument
3920    // conversion would skip the borrow's release and leave the object borrowed.
3921    let (pre_call, post_conversion) = if method.env.is_instance() {
3922        let owner = syn::Ident::new("__mx_owner", proc_macro2::Span::mixed_site());
3923        let cell = syn::Ident::new("__mx_cell", proc_macro2::Span::mixed_site());
3924        let guard = syn::Ident::new("__mx_guard", proc_macro2::Span::mixed_site());
3925        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! {
3926            let #owner =
3927                ::miniextendr_api::externalptr::ReceiverOwner::resolve::<#type_ident>(#self_sexp);
3928        };
3929        // The receiver's RefCell; `handle_downcast_failed` refuses a consumed
3930        // value, a pointer restored from a saved session, or another type.
3931        let cell_lookup = {
    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");
            ::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);
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote! {
3932            #resolve
3933            let #self_ptr = unsafe {
3934                ::miniextendr_api::externalptr::ErasedExternalPtr::from_sexp(#owner.get())
3935            };
3936            let #cell = match #self_ptr.downcast_cell::<#type_ident>() {
3937                ::core::option::Option::Some(cell) => cell,
3938                ::core::option::Option::None => ::miniextendr_api::externalptr::handle_downcast_failed::<#type_ident>(&#self_ptr),
3939            };
3940        };
3941        let (lookup, borrow) = match method.env {
3942            ReceiverKind::RefMut => (
3943                cell_lookup,
3944                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "mut");
    ::quote::ToTokens::to_tokens(&guard, &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, "borrow_value_mut");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&cell, &mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::ToTokens::to_tokens(&self_ref, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::__private::push_ident(&mut _s, "mut");
    ::quote::__private::push_star(&mut _s);
    ::quote::ToTokens::to_tokens(&guard, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    _s
}quote! {
3945                    let mut #guard = ::miniextendr_api::externalptr::borrow_value_mut(#cell);
3946                    let #self_ref = &mut *#guard;
3947                },
3948            ),
3949            ReceiverKind::Ref => (
3950                cell_lookup,
3951                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::ToTokens::to_tokens(&guard, &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, "borrow_value");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&cell, &mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::ToTokens::to_tokens(&self_ref, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::__private::push_star(&mut _s);
    ::quote::ToTokens::to_tokens(&guard, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    _s
}quote! {
3952                    let #guard = ::miniextendr_api::externalptr::borrow_value(#cell);
3953                    let #self_ref = &*#guard;
3954                },
3955            ),
3956            ReceiverKind::Value => match value_mode {
3957                // `self -> Result<Self, E>` / `Option<Self>`: keep the stored
3958                // value; the call runs on a clone and the slot is overwritten
3959                // only on success (`T: Clone`, see `ConsumingFallible`).
3960                ValueMode::Fallible => (
3961                    cell_lookup,
3962                    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "mut");
    ::quote::ToTokens::to_tokens(&self_slot, &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, "borrow_value_mut");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&cell, &mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote! {
3963                        let mut #self_slot = ::miniextendr_api::externalptr::borrow_value_mut(#cell);
3964                    },
3965                ),
3966                // `self -> Self` and terminal `self -> T`: move the value out,
3967                // leaving the `ConsumedSlot` marker until (and unless) the
3968                // result is written back. A call that reaches the object
3969                // meanwhile finds it consumed.
3970                ValueMode::WriteBack | ValueMode::Terminal => (
3971                    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&resolve, &mut _s);
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "mut");
    ::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);
    _s
}quote! {
3972                        #resolve
3973                        let mut #self_ptr = unsafe {
3974                            ::miniextendr_api::externalptr::ErasedExternalPtr::from_sexp(#owner.get())
3975                        };
3976                    },
3977                    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::ToTokens::to_tokens(&taken, &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, "take_for_consuming");
    ::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, "v");
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_ident(&mut _s, "v");
            ::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");
            ::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);
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote! {
3978                        let #taken = match #self_ptr.take_for_consuming::<#type_ident>() {
3979                            ::core::option::Option::Some(v) => v,
3980                            ::core::option::Option::None => ::miniextendr_api::externalptr::handle_downcast_failed::<#type_ident>(&#self_ptr),
3981                        };
3982                    },
3983                ),
3984            },
3985            // A view receiver holds the borrow itself, with the R object
3986            // the receiver resolved to (rooted by `#owner` for the call).
3987            ReceiverKind::ExternalPtrRef => (
3988                cell_lookup,
3989                {
    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::__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, "ExternalPtrRef");
            ::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_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::ToTokens::to_tokens(&owner, &mut _s);
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "owner");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::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! {
3990                    let #self_ref = unsafe {
3991                        ::miniextendr_api::ExternalPtrRef::<#type_ident>::from_raw_parts(
3992                            #owner.owner(),
3993                            #cell,
3994                        )
3995                    };
3996                },
3997            ),
3998            ReceiverKind::ExternalPtrMut => (
3999                cell_lookup,
4000                {
    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::__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, "ExternalPtrMut");
            ::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_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::ToTokens::to_tokens(&owner, &mut _s);
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "owner");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::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! {
4001                    let #self_ref = unsafe {
4002                        ::miniextendr_api::ExternalPtrMut::<#type_ident>::from_raw_parts(
4003                            #owner.owner(),
4004                            #cell,
4005                        )
4006                    };
4007                },
4008            ),
4009            // The handle receiver takes no borrow: the body reads through
4010            // `borrow()` / `borrow_mut()`, or consumes the handle.
4011            ReceiverKind::ExternalPtrValue => (
4012                {
    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(&external_ptr, &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, "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
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote! {
4013                    #resolve
4014                    let #external_ptr =
4015                        ::miniextendr_api::externalptr::wrap_receiver::<#type_ident>(#owner.get());
4016                },
4017                TokenStream::new(),
4018            ),
4019            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
4020        };
4021        (::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [lookup]))vec![lookup], ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [borrow]))vec![borrow])
4022    } else {
4023        (::alloc::vec::Vec::new()vec![], ::alloc::vec::Vec::new()vec![])
4024    };
4025
4026    // Fallible in-place builders (#1433): `&mut self -> Result<&mut Self, E>` /
4027    // `Option<&mut Self>` (and the `&self` forms). The returned borrow is
4028    // dropped and the wrapper returns the same handle on success.
4029    let fallible_self_ref = method.env.is_instance()
4030        && !#[allow(non_exhaustive_omitted_patterns)] match method.env {
    ReceiverKind::Value => true,
    _ => false,
}matches!(method.env, ReceiverKind::Value)
4031        && (method.returns_result_self_ref() || method.returns_option_self_ref());
4032
4033    // Generate call expression. A visibility marker (`Invisible<T>` /
4034    // `Visible<T>`, #1213) is a transparent newtype around the real return:
4035    // unwrap it (`.0`) before the conversion, which was analysed on the inner
4036    // type (`method.sig.output` is already peeled).
4037    let unwrap_marker = |call: TokenStream| -> TokenStream {
4038        let call = crate::type_inspect::prepare_return_value(
4039            call,
4040            method.visibility_marker,
4041            method.method_attrs.serialize,
4042        );
4043        match &method.return_wrap {
4044            Some(wrap) => wrap.prepare_value(call),
4045            None => call,
4046        }
4047    };
4048    let call_expr = match method.env {
4049        ReceiverKind::Ref | ReceiverKind::RefMut if fallible_self_ref => {
4050            let call = unwrap_marker({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&self_ref, &mut _s);
    ::quote::__private::push_dot(&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 rust_args, i) = rust_args.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let rust_args =
                        match rust_args.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&rust_args, &mut _s);
                }
            }
            _s
        });
    _s
}quote! { #self_ref.#method_ident(#(#rust_args),*) });
4051            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&call, &mut _s);
    ::quote::__private::push_dot(&mut _s);
    ::quote::__private::push_ident(&mut _s, "map");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_or(&mut _s);
            ::quote::__private::push_underscore(&mut _s);
            ::quote::__private::push_or(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            _s
        });
    _s
}quote! { #call.map(|_| ()) }
4052        }
4053        ReceiverKind::Ref | ReceiverKind::RefMut => {
4054            unwrap_marker({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&self_ref, &mut _s);
    ::quote::__private::push_dot(&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 rust_args, i) = rust_args.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let rust_args =
                        match rust_args.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&rust_args, &mut _s);
                }
            }
            _s
        });
    _s
}quote! { #self_ref.#method_ident(#(#rust_args),*) })
4055        }
4056        ReceiverKind::Value => match value_mode {
4057            ValueMode::WriteBack => {
4058                let call =
4059                    unwrap_marker({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&type_ident, &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(&taken, &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 rust_args, i) = rust_args.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let rust_args =
                        match rust_args.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&rust_args, &mut _s);
                }
            }
            _s
        });
    _s
}quote! { #type_ident::#method_ident(#taken, #(#rust_args),*) });
4060                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s, "__mx_out");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&call, &mut _s);
            ::quote::__private::push_semi(&mut _s);
            ::quote::ToTokens::to_tokens(&self_ptr, &mut _s);
            ::quote::__private::push_dot(&mut _s);
            ::quote::__private::push_ident(&mut _s,
                "restore_after_consuming");
            ::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_ident(&mut _s, "__mx_out");
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            _s
        });
    _s
}quote! {{
4061                    let __mx_out = #call;
4062                    #self_ptr.restore_after_consuming::<#type_ident>(__mx_out);
4063                }}
4064            }
4065            ValueMode::Fallible => {
4066                let call = unwrap_marker({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&type_ident, &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::__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, "clone_for_consuming");
            ::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::__private::push_star(&mut _s);
                    ::quote::ToTokens::to_tokens(&self_slot, &mut _s);
                    _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 rust_args, i) = rust_args.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let rust_args =
                        match rust_args.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&rust_args, &mut _s);
                }
            }
            _s
        });
    _s
}quote! {
4067                    #type_ident::#method_ident(
4068                        ::miniextendr_api::externalptr::clone_for_consuming::<#type_ident>(&*#self_slot),
4069                        #(#rust_args),*
4070                    )
4071                });
4072                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&call, &mut _s);
    ::quote::__private::push_dot(&mut _s);
    ::quote::__private::push_ident(&mut _s, "map");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_or(&mut _s);
            ::quote::__private::push_ident(&mut _s, "__mx_v");
            ::quote::__private::push_or(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_star(&mut _s);
                    ::quote::ToTokens::to_tokens(&self_slot, &mut _s);
                    ::quote::__private::push_eq(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "__mx_v");
                    ::quote::__private::push_semi(&mut _s);
                    _s
                });
            _s
        });
    _s
}quote! { #call.map(|__mx_v| { *#self_slot = __mx_v; }) }
4073            }
4074            ValueMode::Terminal => {
4075                unwrap_marker({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&type_ident, &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(&taken, &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 rust_args, i) = rust_args.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let rust_args =
                        match rust_args.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&rust_args, &mut _s);
                }
            }
            _s
        });
    _s
}quote! { #type_ident::#method_ident(#taken, #(#rust_args),*) })
4076            }
4077        },
4078        ReceiverKind::ExternalPtrRef | ReceiverKind::ExternalPtrMut => {
4079            unwrap_marker({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&type_ident, &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 rust_args, i) = rust_args.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let rust_args =
                        match rust_args.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&rust_args, &mut _s);
                }
            }
            _s
        });
    _s
}quote! { #type_ident::#method_ident(#self_ref, #(#rust_args),*) })
4080        }
4081        ReceiverKind::ExternalPtrValue => {
4082            unwrap_marker({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&type_ident, &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(&external_ptr, &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 rust_args, i) = rust_args.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let rust_args =
                        match rust_args.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&rust_args, &mut _s);
                }
            }
            _s
        });
    _s
}quote! { #type_ident::#method_ident(#external_ptr, #(#rust_args),*) })
4083        }
4084        ReceiverKind::None => unwrap_marker({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&type_ident, &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 rust_args, i) = rust_args.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let rust_args =
                        match rust_args.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&rust_args, &mut _s);
                }
            }
            _s
        });
    _s
}quote! { #type_ident::#method_ident(#(#rust_args),*) }),
4085    };
4086
4087    // Determine return handling strategy
4088    let return_handling = if method.env == ReceiverKind::Value && value_mode == ValueMode::WriteBack
4089    {
4090        // `self -> Self`: the call expression already wrote the result back;
4091        // hand back the same handle (in-place semantics, like `&mut Self`).
4092        ReturnHandling::SelfHandle
4093    } else if (method.env == ReceiverKind::Value && value_mode == ValueMode::Fallible)
4094        || fallible_self_ref
4095    {
4096        // Fallible in-place step: the call expression yields `Result<(), E>` /
4097        // `Option<()>`; raise on failure, same handle on success.
4098        if method.returns_result_self() || method.returns_result_self_ref() {
4099            ReturnHandling::SelfHandleResult
4100        } else {
4101            ReturnHandling::SelfHandleOption
4102        }
4103    } else if method.returns_self() {
4104        ReturnHandling::ExternalPtr
4105    } else if method.returns_self_ref() && method.env.is_instance() {
4106        // In-place builder (`&mut self -> &mut Self` / `&self -> Self`): the
4107        // method mutates/borrows the receiver and returns a borrow of it. Hand
4108        // back the same ExternalPtr handle (`self_sexp`) so chaining preserves
4109        // identity with no clone. See `ReturnHandling::SelfHandle`.
4110        ReturnHandling::SelfHandle
4111    } else if method.method_attrs.unwrap_in_r
4112        && crate::return_type_analysis::output_is_result(&method.sig.output)
4113    {
4114        ReturnHandling::IntoR
4115    } else {
4116        crate::c_wrapper_builder::detect_return_handling(
4117            &method.sig.output,
4118            method.return_wrap.as_ref(),
4119        )
4120    };
4121
4122    // Build the context using the builder
4123    let mut builder = CWrapperContext::builder(method_ident.clone(), c_ident)
4124        .r_name(method.r_method_name())
4125        .inputs(method.sig.inputs.clone())
4126        .output(method.sig.output.clone())
4127        .pre_call(pre_call)
4128        .post_conversion(post_conversion)
4129        .call_expr(call_expr)
4130        .return_handling(return_handling)
4131        .err_parts(crate::c_wrapper_builder::ErrPartsMode::from_spec(
4132            method
4133                .method_attrs
4134                .serde_error
4135                .as_ref()
4136                .map(|spec| spec.with_self_type(type_ident))
4137                .as_ref(),
4138        ))
4139        .cfg_attrs(parsed_impl.cfg_attrs.clone())
4140        .type_context(type_ident.clone())
4141        .formals(method.formals());
4142
4143    if method.env.is_instance() {
4144        builder = builder.has_self();
4145    }
4146
4147    if method.method_attrs.coerce {
4148        builder = builder.coerce_all();
4149    }
4150
4151    if method.method_attrs.check_interrupt {
4152        builder = builder.check_interrupt();
4153    }
4154
4155    if method.method_attrs.rng {
4156        builder = builder.rng();
4157    }
4158
4159    if parsed_impl.strict {
4160        builder = builder.strict();
4161    }
4162
4163    // Forward match_arg + several_ok parameter names so `RustConversionBuilder` swaps
4164    // in `match_arg_vec_from_sexp` for the Vec/slice/array/Box<[_]> conversion path.
4165    // Scalar match_arg doesn't need this — R's match.arg() validated the choice and
4166    // `TryFromSexp for EnumType` (auto-generated by `#[derive(MatchArg)]`) decodes it.
4167    // A choice type under `Missing` / `Option` layers (#1473, #1551) likewise
4168    // bypasses `TryFromSexp`: no `Option<UserEnum>` impl can exist downstream
4169    // (orphan rule).
4170    // `no_na(..)` parameters also have their converted value checked, for what
4171    // the type reads as `NA` beyond the R guard's `anyNA()`.
4172    for (rust_name, attrs) in &method.method_attrs.per_param {
4173        if attrs.convert {
4174            builder = builder.with_convert_param(rust_name.clone());
4175        }
4176        if let Some(leaf) = attrs.layered_leaf() {
4177            builder = builder.layered_choice(rust_name.clone(), leaf);
4178        } else if attrs.match_arg && attrs.several_ok {
4179            builder = builder.match_arg_several_ok(rust_name.clone());
4180        }
4181        if attrs.checks.no_na {
4182            builder = builder.no_na(rust_name.clone(), attrs.checks.no_na_message.clone());
4183        }
4184    }
4185    // `Checked<T>` / `Unchecked<T>` parameters (#1566) convert as `T` and are
4186    // wrapped back before the call.
4187    for (rust_name, markers) in &method.param_markers {
4188        builder = builder.param_markers(rust_name.clone(), markers.clone());
4189    }
4190
4191    let c_wrapper_and_def = builder.build().generate();
4192
4193    let match_arg_entries = generate_method_match_arg_entries(parsed_impl, method);
4194
4195    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&c_wrapper_and_def, &mut _s);
    ::quote::ToTokens::to_tokens(&match_arg_entries, &mut _s);
    _s
}quote! {
4196        #c_wrapper_and_def
4197        #match_arg_entries
4198    }
4199}
4200
4201/// Register enum choices, aliases, defaults and parameter documentation for
4202/// write-time placeholder substitution. R calls no choice-lookup C helper.
4203fn generate_method_match_arg_entries(
4204    parsed_impl: &ParsedImpl,
4205    method: &ParsedMethod,
4206) -> TokenStream {
4207    if !method.method_attrs.per_param.values().any(|a| a.match_arg) {
4208        return TokenStream::new();
4209    }
4210
4211    let type_ident = &parsed_impl.type_ident;
4212    let c_ident = method.c_wrapper_ident(type_ident);
4213    let c_ident_str = c_ident.to_string();
4214    let cfg_attrs = &parsed_impl.cfg_attrs;
4215
4216    let mut out = TokenStream::new();
4217
4218    // Signature order, so the emitted items don't follow the map's order.
4219    for (rust_name, attrs) in crate::miniextendr_fn::per_param_in_signature_order(
4220        &method.sig.inputs,
4221        &method.method_attrs.per_param,
4222    ) {
4223        if !attrs.match_arg {
4224            continue;
4225        }
4226        // Find the parameter type from the (already-normalized) signature.
4227        let Some(param_ty) = find_param_type(&method.sig.inputs, rust_name) else {
4228            continue;
4229        };
4230        // several_ok containers (Vec<Mode>, Box<[Mode]>, [Mode; N], &[Mode]) and the
4231        // `Option<Mode>` scalar form both wrap the enum; register the enum's
4232        // CHOICES, not the wrapper's.
4233        let several_ok = attrs.several_ok;
4234        let choices_ty = crate::match_arg_choices_ty(param_ty, several_ok).clone();
4235
4236        let key = crate::match_arg_keys::param_key(rust_name);
4237
4238        // Placeholder that the write-time substitution pass replaces with the
4239        // literal `c("a", "b", ...)` default. Shape matches the standalone-fn convention.
4240        let placeholder = crate::r_class_formatter::match_arg_placeholder(&c_ident_str, &key);
4241        let entry_ident = syn::Ident::new(
4242            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("match_arg_choices_entry_{0}",
                crate::match_arg_keys::placeholder_ident_suffix(&placeholder)))
    })format!(
4243                "match_arg_choices_entry_{}",
4244                crate::match_arg_keys::placeholder_ident_suffix(&placeholder)
4245            ),
4246            proc_macro2::Span::call_site(),
4247        );
4248        let doc_placeholder =
4249            crate::r_class_formatter::match_arg_param_doc_placeholder(&c_ident_str, &key);
4250        let doc_entry_ident = syn::Ident::new(
4251            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("match_arg_param_doc_entry_{0}",
                crate::match_arg_keys::placeholder_ident_suffix(&doc_placeholder)))
    })format!(
4252                "match_arg_param_doc_entry_{}",
4253                crate::match_arg_keys::placeholder_ident_suffix(&doc_placeholder)
4254            ),
4255            proc_macro2::Span::call_site(),
4256        );
4257
4258        let preferred_default = attrs
4259            .default
4260            .as_deref()
4261            .map(crate::match_arg_keys::extract_match_arg_default)
4262            .unwrap_or_default();
4263        let aliases_placeholder = crate::match_arg_keys::aliases_placeholder(&c_ident_str, &key);
4264        let choices_entry_tokens = crate::match_arg_keys::choices_entry_tokens(
4265            cfg_attrs,
4266            &entry_ident,
4267            &placeholder,
4268            &aliases_placeholder,
4269            &choices_ty,
4270            &preferred_default,
4271        );
4272        let param_doc_entry_tokens = crate::match_arg_keys::param_doc_entry_tokens(
4273            cfg_attrs,
4274            &doc_entry_ident,
4275            &doc_placeholder,
4276            several_ok,
4277            &attrs.choice_doc_suffix(),
4278            &choices_ty,
4279        );
4280
4281        out.extend({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&choices_entry_tokens, &mut _s);
    ::quote::ToTokens::to_tokens(&param_doc_entry_tokens, &mut _s);
    _s
}quote! {
4282            #choices_entry_tokens
4283            #param_doc_entry_tokens
4284        });
4285    }
4286
4287    out
4288}
4289
4290/// Find a parameter's Rust type from a stripped signature by identifier name.
4291fn find_param_type<'a>(
4292    inputs: &'a syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
4293    name: &str,
4294) -> Option<&'a syn::Type> {
4295    for arg in inputs {
4296        if let syn::FnArg::Typed(pt) = arg
4297            && let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
4298            && crate::naming::unraw(&pat_ident.ident) == name
4299        {
4300            return Some(pt.ty.as_ref());
4301        }
4302    }
4303    None
4304}
4305
4306/// Returns true if a vctrs constructor's return type is `Self`, `&Self`, `&mut Self`,
4307/// the named impl type, `Box<Self>`, `Result<Self, _>`, or `Result<NamedType, _>`.
4308///
4309/// These are all invalid for a vctrs constructor because the generated R wrapper
4310/// passes the return value to `vctrs::new_vctr()` / `new_rcrd()` / `new_list_of()`,
4311/// which require a plain vector payload — not an `ExternalPtr` (`EXTPTRSXP`).
4312fn vctrs_ctor_returns_self_or_type(output: &syn::ReturnType, type_ident: &syn::Ident) -> bool {
4313    let syn::ReturnType::Type(_, ty) = output else {
4314        return false;
4315    };
4316    ty_is_self_or_named(ty.as_ref(), type_ident)
4317}
4318
4319/// Recursively checks whether `ty` is `Self`, `&Self`, `&mut Self`, `Box<Self>`,
4320/// the named type, or `Result<(Self | NamedType), _>`.
4321fn ty_is_self_or_named(ty: &syn::Type, type_ident: &syn::Ident) -> bool {
4322    match ty {
4323        syn::Type::Path(p) => {
4324            let last = match p.path.segments.last() {
4325                Some(s) => s,
4326                None => return false,
4327            };
4328            // Plain `Self` or `TypeName`
4329            if last.ident == "Self" || last.ident == *type_ident {
4330                return true;
4331            }
4332            // `Result<Self, _>` or `Result<TypeName, _>`
4333            if last.ident == "Result"
4334                && let syn::PathArguments::AngleBracketed(ref args) = last.arguments
4335                && let Some(syn::GenericArgument::Type(first_ty)) = args.args.first()
4336            {
4337                return ty_is_self_or_named(first_ty, type_ident);
4338            }
4339            // `Box<Self>` or `Box<TypeName>`
4340            if last.ident == "Box"
4341                && let syn::PathArguments::AngleBracketed(ref args) = last.arguments
4342                && let Some(syn::GenericArgument::Type(inner)) = args.args.first()
4343            {
4344                return ty_is_self_or_named(inner, type_ident);
4345            }
4346            false
4347        }
4348        // `&Self` or `&mut Self`
4349        syn::Type::Reference(r) => ty_is_self_or_named(r.elem.as_ref(), type_ident),
4350        _ => false,
4351    }
4352}
4353
4354// region: Class-system R wrapper generators (sub-modules)
4355
4356/// Environment-based class wrapper generator (`obj$method()` dispatch).
4357mod env_class;
4358/// `$` / `[[` field methods of `r_data_accessors` for S3, S4 and env classes (#1848).
4359mod field_syntax;
4360/// R6 class wrapper generator (`R6Class` with `$new()`, active bindings, private methods).
4361mod r6_class;
4362/// S3 class wrapper generator (`structure()` + `generic.Class` dispatch).
4363mod s3_class;
4364/// S4 class wrapper generator (`setClass` / `setMethod` formal OOP).
4365pub(crate) mod s4_class;
4366/// S7 class wrapper generator (`new_class` / `new_generic` modern R OOP).
4367pub(crate) mod s7_class;
4368/// vctrs-compatible class wrapper generator (`new_vctr` / `new_rcrd` / `new_list_of`).
4369mod vctrs_class;
4370
4371pub(crate) use env_class::generate_env_class;
4372#[cfg(test)]
4373pub(crate) use env_class::generate_env_r_wrapper;
4374pub(crate) use r6_class::generate_r6_class;
4375#[cfg(test)]
4376pub(crate) use r6_class::generate_r6_r_wrapper;
4377pub(crate) use s3_class::generate_s3_class;
4378#[cfg(test)]
4379pub(crate) use s3_class::generate_s3_r_wrapper;
4380pub(crate) use s4_class::generate_s4_class;
4381#[cfg(test)]
4382pub(crate) use s4_class::generate_s4_r_wrapper;
4383pub(crate) use s7_class::generate_s7_class;
4384#[cfg(test)]
4385pub(crate) use s7_class::generate_s7_r_wrapper;
4386#[cfg(test)]
4387use s7_class::rust_type_to_s7_class;
4388pub(crate) use vctrs_class::generate_vctrs_class;
4389#[cfg(test)]
4390pub(crate) use vctrs_class::generate_vctrs_r_wrapper;
4391
4392/// The first line of R6's `initialize` and S7's `constructor` for a class
4393/// without a constructor: called without a `.ptr`, they raise an error
4394/// rather than build an object holding no pointer. The factories and other
4395/// classes' methods always pass the `.ptr`.
4396pub(crate) fn no_constructor_guard(class_name: &str) -> String {
4397    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if (is.null(.ptr)) stop(\"`{0}` has no constructor: its objects come from the functions that return one.\", call. = FALSE)",
                class_name))
    })format!(
4398        "if (is.null(.ptr)) stop(\"`{class_name}` has no constructor: its objects come from \
4399         the functions that return one.\", call. = FALSE)"
4400    )
4401}
4402
4403/// The line of [`ClassWrapper::head`] where the class's roxygen block takes
4404/// the [`ClassWrapper::class_doc_lines`] of every impl block of the type.
4405/// Spelled the same as `miniextendr_api::registry::CLASS_DOC_LINES_MARKER`,
4406/// which the wrapper writer replaces.
4407pub(crate) const CLASS_DOC_LINES_MARKER: &str = ".__MX_CLASS_DOC_LINES__";
4408
4409/// The line of [`ClassWrapper::head`] where the class's roxygen block takes
4410/// the [`ClassWrapper::class_docs`] of every impl block of the type, the
4411/// defining block's first. Spelled the same as
4412/// `miniextendr_api::registry::CLASS_DOCS_MARKER`.
4413pub(crate) const CLASS_DOCS_MARKER: &str = ".__MX_CLASS_DOCS__";
4414
4415/// Opens a roxygen line of a class's roxygen block that a doc tag written on
4416/// another impl block of the type replaces: a generated `@title`, `@name`,
4417/// `@rdname`, `@export`, constructor `@param` or R6 `@field`. The wrapper
4418/// writer drops the line when another block's [`ClassWrapper::class_docs`]
4419/// have the tag (for `@param` / `@field`, for the same name), and otherwise
4420/// keeps it without the prefix. Spelled the same as
4421/// `miniextendr_api::registry::CLASS_DEFAULT_PREFIX`.
4422pub(crate) const CLASS_DEFAULT_PREFIX: &str = ".__MX_CLASS_DEFAULT__";
4423
4424/// A generated member-documentation default resolved when the wrapper writer
4425/// knows the defining impl block's help topic (#2068). Unlike class defaults,
4426/// these belong to individual member blocks: an inherited author topic replaces
4427/// their page and drops generated parameter/structural prose, never author tags.
4428/// Spelled the same as `miniextendr_api::registry::CLASS_MEMBER_DEFAULT_PREFIX`.
4429pub(crate) const CLASS_MEMBER_DEFAULT_PREFIX: &str = ".__MX_CLASS_MEMBER_DEFAULT__";
4430
4431pub(crate) fn member_default(line: impl std::fmt::Display) -> String {
4432    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}",
                CLASS_MEMBER_DEFAULT_PREFIX, line))
    })format!("{CLASS_MEMBER_DEFAULT_PREFIX}{line}")
4433}
4434
4435/// A companion block follows a method's explicit page; otherwise its page is
4436/// inherited from the defining impl at wrapper-write time.
4437pub(crate) fn push_member_rdname(lines: &mut Vec<String>, tags: &[String], class: &str) {
4438    if crate::roxygen::describe_in_topic(tags).is_some()
4439        || crate::roxygen::rdname_value(tags).is_some()
4440    {
4441        crate::roxygen::push_rdname_or_default(lines, tags, class);
4442    } else {
4443        lines.push(member_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {0}", class))
    })format!("#' @rdname {class}")));
4444    }
4445}
4446
4447/// `line` as a generated default of the class's roxygen block
4448/// ([`CLASS_DEFAULT_PREFIX`]).
4449pub(crate) fn class_default(line: impl std::fmt::Display) -> String {
4450    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", CLASS_DEFAULT_PREFIX,
                line))
    })format!("{CLASS_DEFAULT_PREFIX}{line}")
4451}
4452
4453/// Opens a class's roxygen block that only carries the impl docs
4454/// ([`docs_only_class_block`]). The wrapper writer writes the block, up to its
4455/// closing `NULL`, only when the type's impl docs or member-derived class docs
4456/// say something, so a readers-only impl adds no page (#1918), or when it
4457/// keeps the class environment, whose block goes on the class's page
4458/// (#2289). Spelled the same as
4459/// `miniextendr_api::registry::CLASS_DOCS_ONLY_MARKER`.
4460pub(crate) const CLASS_DOCS_ONLY_MARKER: &str = ".__MX_CLASS_DOCS_ONLY__";
4461
4462/// The roxygen block of an S3 or vctrs class without a constructor that the
4463/// package names and builds itself (`class = "..."`, #1918), documenting no
4464/// object: it carries the impl docs.
4465///
4466/// - On the impl's `@rdname` topic, a page the package documents itself, it
4467///   adds no alias and no title, and sorts after the topic's own blocks
4468///   ([`crate::roxygen::ORDER_AFTER_TOPIC_BLOCKS`]), so their name wins.
4469/// - Otherwise its page is named for the class, aliased by it, and titled by
4470///   default (`kind`, the class system in the title) unless the impl docs
4471///   give a `@title`.
4472///
4473/// Ends with `NULL`, before which [`ClassWrapper::mark_class_doc_lines`]
4474/// goes; the writer drops the block when there is nothing to say and no
4475/// class environment to document ([`CLASS_DOCS_ONLY_MARKER`]).
4476pub(crate) fn docs_only_class_block(parsed_impl: &ParsedImpl, kind: &str) -> Vec<String> {
4477    let class_name = parsed_impl.class_name();
4478    let tags = &parsed_impl.doc_tags;
4479    let mut lines = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [CLASS_DOCS_ONLY_MARKER.to_string()]))vec![CLASS_DOCS_ONLY_MARKER.to_string()];
4480    let no_rd = crate::roxygen::has_roxygen_tag(tags, "noRd")
4481        || (parsed_impl.noexport && !parsed_impl.internal);
4482    if no_rd {
4483        if !crate::roxygen::has_roxygen_tag(tags, "noRd") {
4484            lines.push("#' @noRd".to_string());
4485        }
4486    } else {
4487        if let Some(topic) = crate::roxygen::rdname_value(tags) {
4488            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @name {0}", topic))
    })format!("#' @name {topic}"));
4489            lines.push("#' @aliases NULL".to_string());
4490            if !crate::roxygen::has_roxygen_tag(tags, "order") {
4491                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' {0}",
                crate::roxygen::ORDER_AFTER_TOPIC_BLOCKS))
    })format!("#' {}", crate::roxygen::ORDER_AFTER_TOPIC_BLOCKS));
4492            }
4493        } else {
4494            // The block's own `@title` / `@name` replace the defaults.
4495            if !crate::roxygen::has_roxygen_tag(tags, "title") {
4496                lines.push(class_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @title {0} {1} Class",
                class_name, kind))
    })format!(
4497                    "#' @title {class_name} {kind} Class"
4498                )));
4499            }
4500            if !crate::roxygen::has_roxygen_tag(tags, "name") {
4501                lines.push(class_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @name {0}", class_name))
    })format!("#' @name {class_name}")));
4502            }
4503        }
4504        if parsed_impl.internal && !crate::roxygen::has_roxygen_tag(tags, "keywords internal") {
4505            lines.push("#' @keywords internal".to_string());
4506        }
4507    }
4508    lines.push(CLASS_DOCS_MARKER.to_string());
4509    lines.push("NULL".to_string());
4510    lines
4511}
4512
4513/// Whether a type's class docs say something, beyond the page and export
4514/// tags: the wrapper writer keeps a [`CLASS_DOCS_ONLY_MARKER`] block then.
4515#[cfg(test)]
4516fn class_docs_say_something(class_docs: &[String], class_doc_lines: &[String]) -> bool {
4517    const PAGE_TAGS: &[&str] = &["rdname", "noRd", "keywords", "order", "export"];
4518    !class_doc_lines.is_empty()
4519        || class_docs.iter().any(|line| {
4520            line.strip_prefix("#' @")
4521                .and_then(|rest| rest.split_whitespace().next())
4522                .is_none_or(|tag| !PAGE_TAGS.contains(&tag))
4523        })
4524}
4525
4526/// One impl block's R wrapper, in the parts the wrapper writer merges per
4527/// Rust type (#1776): the class is defined once, from the defining block's
4528/// `head` and `tail`, and every block's `members` attach to it. See
4529/// `miniextendr_api::registry::ClassBlockEntry`.
4530#[derive(#[automatically_derived]impl ::core::fmt::Debug for ClassWrapper {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            "ClassWrapper head class_docs class_doc_lines members env tail member_names";
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.head, &self.class_docs, &self.class_doc_lines,
                        &self.members, &self.env, &self.tail, &&self.member_names];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
    }
}Debug, #[automatically_derived]impl ::core::default::Default for ClassWrapper {
    #[inline]
    fn default() -> Self {
        ClassWrapper {
            head: ::core::default::Default::default(),
            class_docs: ::core::default::Default::default(),
            class_doc_lines: ::core::default::Default::default(),
            members: ::core::default::Default::default(),
            env: ::core::default::Default::default(),
            tail: ::core::default::Default::default(),
            member_names: ::core::default::Default::default(),
        }
    }
}Default)]
4531pub struct ClassWrapper {
4532    /// The class definition: the class's roxygen block, with the
4533    /// [`CLASS_DOCS_MARKER`] line where the impl docs go and the
4534    /// [`CLASS_DOC_LINES_MARKER`] line where member-derived class docs go,
4535    /// the class object, the constructor and the class-level helpers.
4536    pub head: Vec<String>,
4537    /// The block's own doc comment as roxygen lines (with the constructor's,
4538    /// for S3 and vctrs, whose class block is the constructor's block).
4539    pub class_docs: Vec<String>,
4540    /// Roxygen lines the block's members add to the class's roxygen block.
4541    pub class_doc_lines: Vec<String>,
4542    /// The block's methods and static methods.
4543    pub members: Vec<String>,
4544    /// The class environment with its roxygen block when only a trait impl
4545    /// can land in it: an S3 class without a constructor, and a vctrs class.
4546    /// The wrapper writer keeps it only when a trait impl writes
4547    /// `Class$Trait` into it (#2264, #2289). Empty for the other systems; an
4548    /// S3 constructor's class environment is in the [`tail`](Self::tail).
4549    pub env: Vec<String>,
4550    /// What follows the members of every block, such as R6's `$lock()`.
4551    pub tail: Vec<String>,
4552    /// The names the members bind in the class's own namespaces, worded for
4553    /// the writer's message when two blocks bind the same one.
4554    pub member_names: Vec<String>,
4555}
4556
4557impl ClassWrapper {
4558    /// Put the [`CLASS_DOC_LINES_MARKER`] before the last line of `head`, the
4559    /// tag that closes the class's roxygen block, and add the lifecycle
4560    /// imports of the block's methods to the class docs.
4561    fn mark_class_doc_lines(&mut self, head: &mut Vec<String>, parsed_impl: &ParsedImpl) {
4562        let pos = head.len().saturating_sub(1);
4563        head.insert(pos, CLASS_DOC_LINES_MARKER.to_string());
4564        if let Some(import) = crate::lifecycle::collect_lifecycle_imports(
4565            parsed_impl
4566                .methods
4567                .iter()
4568                .filter_map(|m| m.method_attrs.lifecycle.as_ref()),
4569        ) {
4570            self.class_doc_lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' {0}", import))
    })format!("#' {import}"));
4571        }
4572    }
4573
4574    /// Local macro rendering for snapshots, with merge markers stripped, as
4575    /// the writer writes a type with this one impl block and no trait impl
4576    /// writing into its class environment: without the [`env`](Self::env).
4577    /// Write-time topic inheritance and the env decision are covered by the
4578    /// registry and rpkg tests.
4579    #[cfg(test)]
4580    pub fn render(&self) -> String {
4581        let mut lines = Vec::new();
4582        let keep_docs_only = class_docs_say_something(&self.class_docs, &self.class_doc_lines);
4583        let mut skipping = false;
4584        for line in &self.head {
4585            if skipping {
4586                skipping = line != "NULL";
4587                continue;
4588            }
4589            if line == CLASS_DOCS_ONLY_MARKER {
4590                skipping = !keep_docs_only;
4591            } else if line == CLASS_DOCS_MARKER {
4592                lines.extend(self.class_docs.iter().cloned());
4593            } else if line == CLASS_DOC_LINES_MARKER {
4594                lines.extend(self.class_doc_lines.iter().map(|l| strip_class_default(l)));
4595            } else {
4596                lines.push(strip_class_default(line));
4597            }
4598        }
4599        lines.extend(self.members.iter().cloned());
4600        lines.extend(self.tail.iter().cloned());
4601        lines
4602            .join("\n")
4603            .split('\n')
4604            .map(|line| {
4605                line.strip_prefix(CLASS_MEMBER_DEFAULT_PREFIX)
4606                    .unwrap_or(line)
4607            })
4608            .collect::<Vec<_>>()
4609            .join("\n")
4610    }
4611}
4612
4613/// `line` without its [`CLASS_DEFAULT_PREFIX`], as the writer keeps a
4614/// default that no other block replaces.
4615#[cfg(test)]
4616fn strip_class_default(line: &str) -> String {
4617    line.strip_prefix(CLASS_DEFAULT_PREFIX)
4618        .unwrap_or(line)
4619        .to_string()
4620}
4621
4622/// Generate R S3 method wrappers for `as.<class>()` coercion methods.
4623///
4624/// For each method with `#[miniextendr(as = "...")]`, generates an S3 method like:
4625///
4626/// ```r
4627/// #' @export
4628/// #' @method as.data.frame MyType
4629/// as.data.frame.MyType <- function(x, ...) {
4630///     .Call(C_MyType__as_data_frame, .call = sys.call(), x)
4631/// }
4632/// ```
4633///
4634/// This function is called by each class system generator to append the
4635/// `as.*` methods to the R wrapper output.
4636pub fn generate_as_coercion_methods(parsed_impl: &ParsedImpl) -> String {
4637    use crate::r_class_formatter::MethodContext;
4638
4639    let class_name = parsed_impl.class_name();
4640    let type_ident = &parsed_impl.type_ident;
4641
4642    // Check if class has @noRd - if so, skip documentation
4643    let class_doc_tags = &parsed_impl.doc_tags;
4644    let class_has_no_rd = crate::roxygen::has_roxygen_tag(class_doc_tags, "noRd");
4645    let class_has_internal = crate::roxygen::has_roxygen_tag(class_doc_tags, "keywords internal")
4646        || parsed_impl.internal;
4647    let should_export = !class_has_no_rd && !class_has_internal && !parsed_impl.noexport;
4648
4649    let mut lines = Vec::new();
4650
4651    for method in parsed_impl.as_coercion_methods() {
4652        // Get the coercion target (e.g., "data.frame", "list", "character")
4653        let coercion_target = match &method.method_attrs.as_coercion {
4654            Some(target) => target.clone(),
4655            None => continue,
4656        };
4657
4658        // Build method context for .Call generation
4659        // No choice formal and no prelude here (#1830), so a `Missing<..>`
4660        // choice parameter forwards only an omitted argument as absent, not
4661        // its choice vector (#2152).
4662        let ctx = MethodContext::new(method, type_ident)
4663            .with_impl_preconditions(parsed_impl.preconditions)
4664            .without_prelude();
4665
4666        // Normalize coercion target for R generic name.
4667        // `as.numeric()` is a thin base-R wrapper that dispatches via the internal
4668        // generic `as.double` (not `as.numeric` itself) — an `as.numeric.<Class>`
4669        // S3 method is never consulted. Register under `as.double` for both
4670        // "numeric" and "double" targets so `as.double(x)` AND `as.numeric(x)`
4671        // both dispatch to it.
4672        // Some targets use non-standard S3 generic names (e.g., tibble uses as_tibble, not as.tibble)
4673        let r_generic = match coercion_target.as_str() {
4674            "numeric" | "double" => "as.double".to_string(),
4675            "tibble" => "as_tibble".to_string(),
4676            "ts" => "as.ts".to_string(),
4677            other => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("as.{0}", other))
    })format!("as.{}", other),
4678        };
4679
4680        // S3 method name: as.data.frame.MyType
4681        let s3_method_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.{1}", r_generic, class_name))
    })format!("{}.{}", r_generic, class_name);
4682
4683        // Documentation
4684        if !class_has_no_rd {
4685            // Add documentation from the method
4686            if !method.doc_tags.is_empty() {
4687                crate::roxygen::push_roxygen_tags(&mut lines, &method.doc_tags);
4688            }
4689            // The method's own doc tags were pushed verbatim above, so only
4690            // inject the defaults a user did not supply (same rule as
4691            // `MethodDocBuilder`): a method-level `@rdname` splits the
4692            // coercion onto its own page instead of being duplicated, and a
4693            // `@describeIn` (which roxygen2 rejects next to `@name` /
4694            // `@rdname`) takes its page from the S3 method object.
4695            let describe_in = crate::roxygen::describe_in_topic(&method.doc_tags).is_some();
4696            if !describe_in && !crate::roxygen::has_roxygen_tag(&method.doc_tags, "name") {
4697                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @name {0}", s3_method_name))
    })format!("#' @name {}", s3_method_name));
4698            }
4699            if !describe_in {
4700                if crate::roxygen::has_roxygen_tag(&method.doc_tags, "rdname") {
4701                    // Own page: needs a title (see `MethodDocBuilder::build`).
4702                    if !crate::roxygen::has_roxygen_tag(&method.doc_tags, "title") {
4703                        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @title {0}", s3_method_name))
    })format!("#' @title {}", s3_method_name));
4704                    }
4705                } else {
4706                    lines.push(member_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {0}", class_name))
    })format!("#' @rdname {}", class_name)));
4707                }
4708            }
4709            crate::roxygen::push_order_after_topic_blocks(
4710                &mut lines,
4711                &method.doc_tags,
4712                &class_name,
4713            );
4714            lines.extend(crate::roxygen::method_source_tag(type_ident, &method.ident));
4715        }
4716
4717        // Export and method registration
4718        if should_export {
4719            lines.push("#' @export".to_string());
4720        }
4721        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @method {0} {1}", r_generic,
                class_name))
    })format!("#' @method {} {}", r_generic, class_name));
4722
4723        // Function signature: always takes x and ... for S3 method compatibility
4724        // Additional parameters from the method are included
4725        let r_formals = method.formals();
4726        let method_params = crate::r_wrapper_builder::build_r_formals_from_sig(
4727            &method.sig,
4728            &r_formals,
4729            &r_formals.rekey(method.param_defaults.clone()),
4730        );
4731        let formals = if method_params.is_empty() {
4732            "x, ...".to_string()
4733        } else {
4734            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("x, {0}, ...", method_params))
    })format!("x, {}, ...", method_params)
4735        };
4736
4737        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                s3_method_name, formals))
    })format!("{} <- function({}) {{", s3_method_name, formals));
4738
4739        // Build the .Call() invocation
4740        let call = ctx.instance_call("x");
4741        let strategy = crate::ReturnStrategy::for_method(method);
4742        let return_builder = crate::MethodReturnBuilder::new(call)
4743            .with_strategy(strategy)
4744            .with_invisible(method.is_invisible())
4745            .with_class_name(class_name.clone())
4746            .with_return_class_from_method(method, &type_ident.to_string());
4747        lines.extend(return_builder.build_s3_body());
4748
4749        lines.push("}".to_string());
4750        lines.push(String::new());
4751    }
4752
4753    lines.join("\n")
4754}
4755
4756/// Generate `impl RCoerce*` trait impls for methods with `#[miniextendr(as = "...")]`.
4757///
4758/// For each `as` coercion method, generates a forwarding trait impl:
4759/// ```ignore
4760/// impl ::miniextendr_api::r_coerce::RCoerceDataFrame for MyType {
4761///     fn as_data_frame(&self) -> Result<::miniextendr_api::List, ::miniextendr_api::r_coerce::RCoerceError> {
4762///         self.as_data_frame()  // inherent method preferred over trait method
4763///     }
4764/// }
4765/// ```
4766///
4767/// Skips methods with extra parameters beyond `&self` (trait methods have fixed signatures)
4768/// and skips non-standard targets (like "tibble", "data.table") that don't have corresponding traits.
4769pub fn generate_as_coercion_trait_impls(parsed_impl: &ParsedImpl) -> TokenStream {
4770    let type_ident = &parsed_impl.type_ident;
4771    let cfg_attrs = &parsed_impl.cfg_attrs;
4772
4773    let mut impls = Vec::new();
4774
4775    for method in parsed_impl.as_coercion_methods() {
4776        let coercion_target = match &method.method_attrs.as_coercion {
4777            Some(target) => target.as_str(),
4778            None => continue,
4779        };
4780
4781        // Skip methods with extra params beyond &self — trait methods have fixed &self-only signatures.
4782        // `sig.inputs` already has self stripped, so non-empty means extra params.
4783        if !method.sig.inputs.is_empty() {
4784            continue;
4785        }
4786
4787        // Skip non-instance methods (trait requires &self)
4788        if method.env != ReceiverKind::Ref {
4789            continue;
4790        }
4791
4792        // Map coercion target to (trait name, trait method name, return type tokens).
4793        // Only the 15 standard targets that have corresponding traits in r_coerce.
4794        let (trait_name, trait_method): (&str, &str) = match coercion_target {
4795            "data.frame" => ("RCoerceDataFrame", "as_data_frame"),
4796            "list" => ("RCoerceList", "as_list"),
4797            "character" => ("RCoerceCharacter", "as_character"),
4798            "numeric" | "double" => ("RCoerceNumeric", "as_numeric"),
4799            "integer" => ("RCoerceInteger", "as_integer"),
4800            "logical" => ("RCoerceLogical", "as_logical"),
4801            "matrix" => ("RCoerceMatrix", "as_matrix"),
4802            "vector" => ("RCoerceVector", "as_vector"),
4803            "factor" => ("RCoerceFactor", "as_factor"),
4804            "Date" => ("RCoerceDate", "as_date"),
4805            "POSIXct" => ("RCoercePOSIXct", "as_posixct"),
4806            "complex" => ("RCoerceComplex", "as_complex"),
4807            "raw" => ("RCoerceRaw", "as_raw"),
4808            "environment" => ("RCoerceEnvironment", "as_environment"),
4809            "function" => ("RCoerceFunction", "as_function"),
4810            _ => continue, // Non-standard targets (tibble, data.table, etc.)
4811        };
4812
4813        let trait_ident = syn::Ident::new(trait_name, proc_macro2::Span::call_site());
4814        let trait_method_ident = syn::Ident::new(trait_method, proc_macro2::Span::call_site());
4815        let user_method_ident = &method.ident;
4816
4817        // Return type: data.frame and list return Result<List, RCoerceError>,
4818        // all others return Result<SEXP, RCoerceError>
4819        let return_type = match coercion_target {
4820            "data.frame" | "list" => {
    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, "result");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Result");
    ::quote::__private::push_lt(&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, "List");
    ::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, "r_coerce");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "RCoerceError");
    ::quote::__private::push_gt(&mut _s);
    _s
}quote! {
4821                ::core::result::Result<::miniextendr_api::List, ::miniextendr_api::r_coerce::RCoerceError>
4822            },
4823            _ => {
    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, "result");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Result");
    ::quote::__private::push_lt(&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);
    ::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, "r_coerce");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "RCoerceError");
    ::quote::__private::push_gt(&mut _s);
    _s
}quote! {
4824                ::core::result::Result<::miniextendr_api::SEXP, ::miniextendr_api::r_coerce::RCoerceError>
4825            },
4826        };
4827
4828        impls.push({
    let mut _s = ::quote::__private::TokenStream::new();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut cfg_attrs, i) = cfg_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let cfg_attrs =
                match cfg_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&cfg_attrs, &mut _s);
        }
    }
    ::quote::__private::push_ident(&mut _s, "impl");
    ::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, "r_coerce");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::ToTokens::to_tokens(&trait_ident, &mut _s);
    ::quote::__private::push_ident(&mut _s, "for");
    ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "fn");
            ::quote::ToTokens::to_tokens(&trait_method_ident, &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::__private::push_ident(&mut _s, "self");
                    _s
                });
            ::quote::__private::push_rarrow(&mut _s);
            ::quote::ToTokens::to_tokens(&return_type, &mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "self");
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::ToTokens::to_tokens(&user_method_ident, &mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    _s
                });
            _s
        });
    _s
}quote! {
4829            #(#cfg_attrs)*
4830            impl ::miniextendr_api::r_coerce::#trait_ident for #type_ident {
4831                fn #trait_method_ident(&self) -> #return_type {
4832                    self.#user_method_ident()
4833                }
4834            }
4835        });
4836    }
4837
4838    {
    let mut _s = ::quote::__private::TokenStream::new();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut impls, i) = impls.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let impls =
                match impls.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&impls, &mut _s);
        }
    }
    _s
}quote! { #(#impls)* }
4839}
4840
4841/// Detect S7 fast-path shortcut name collisions within an inherent impl block.
4842///
4843/// The S7 generator (`s7_class`) emits a standalone `<ClassName>_<method>`
4844/// shortcut function for each non-fallback, non-`no_shortcut` instance method,
4845/// and a `<ClassName>_<r_method_name>` function for each static method. These
4846/// share one R namespace, so two definitions with the same name silently
4847/// clobber each other (last write wins). This typically arises from an
4848/// `r_name` override that aliases an instance shortcut onto a static method
4849/// (or vice versa).
4850///
4851/// Returns an error pointing at the offending method, advising the user to
4852/// rename (via `r_name`) or opt the instance method out with
4853/// `#[miniextendr(s7(no_shortcut))]`. Non-S7 class systems are a no-op.
4854///
4855/// Note: collisions with `#[derive(ExternalPtr)]` sidecar accessors
4856/// (`<ClassName>_get_<field>` / `_set_<field>`) are *not* detected here — the
4857/// sidecar field names live in the derive's distributed-slice registry and are
4858/// not visible to this macro invocation. See #991 for the write-time check.
4859fn check_s7_shortcut_collisions(parsed: &ParsedImpl) -> syn::Result<()> {
4860    if parsed.class_system != ClassSystem::S7 {
4861        return Ok(());
4862    }
4863    let class_name = parsed.class_name();
4864
4865    // Map emitted standalone-function name -> the method ident span that produced
4866    // it, so a second producer of the same name can be reported against itself.
4867    let mut seen: std::collections::HashMap<String, proc_macro2::Span> =
4868        std::collections::HashMap::new();
4869
4870    // Static methods always emit `<ClassName>_<r_method_name>`.
4871    for m in parsed.static_methods() {
4872        let name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}_{1}", class_name,
                m.r_method_name()))
    })format!("{}_{}", class_name, m.r_method_name());
4873        seen.entry(name).or_insert_with(|| m.ident.span());
4874    }
4875
4876    // Instance methods (excluding fallback / no_shortcut / property accessors)
4877    // emit the `<ClassName>_<r_method_name>` shortcut, unless that name is not
4878    // syntactic R (an operator `r_name`), in which case none is emitted.
4879    for m in parsed.instance_methods() {
4880        if m.method_attrs.s7.fallback
4881            || m.method_attrs.s7.no_shortcut
4882            || m.method_attrs.s7.getter
4883            || m.method_attrs.s7.setter
4884            || m.method_attrs.s7.validate
4885        {
4886            continue;
4887        }
4888        let Some(name) = s7_class::s7_shortcut_name(&class_name, &m.r_method_name()) else {
4889            continue;
4890        };
4891        if seen.contains_key(&name) {
4892            return Err(syn::Error::new(
4893                m.ident.span(),
4894                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("S7 fast-path shortcut `{0}` collides with another generated function of the same name on `{1}`. Rename one (e.g. `#[miniextendr(s7(r_name = \"...\"))]`) or opt this method out of the shortcut with `#[miniextendr(s7(no_shortcut))]`.",
                name, class_name))
    })format!(
4895                    "S7 fast-path shortcut `{name}` collides with another generated function \
4896                     of the same name on `{class_name}`. Rename one (e.g. \
4897                     `#[miniextendr(s7(r_name = \"...\"))]`) or opt this method out of the \
4898                     shortcut with `#[miniextendr(s7(no_shortcut))]`."
4899                ),
4900            ));
4901        }
4902        seen.insert(name, m.ident.span());
4903    }
4904
4905    Ok(())
4906}
4907
4908/// Env constructors, instance methods and static methods all occupy the same
4909/// class environment. Check the emitted names before one overwrites another.
4910fn check_env_member_collisions(parsed: &ParsedImpl) -> syn::Result<()> {
4911    if parsed.class_system != ClassSystem::Env {
4912        return Ok(());
4913    }
4914    let mut seen = std::collections::HashMap::new();
4915    if let Some(constructor) = parsed.constructor() {
4916        seen.insert("new".to_owned(), constructor);
4917    }
4918    for method in parsed.instance_methods().chain(parsed.static_methods()) {
4919        let name = method.r_method_name();
4920        if let Some(previous) = seen.insert(name.clone(), method) {
4921            return Err(syn::Error::new_spanned(
4922                &method.ident,
4923                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Env member `{0}${3}` is defined by both `{1}` and `{2}`. Constructors always occupy `new`; instance and static methods share the class environment. Rename a colliding method with `#[miniextendr(r_name = \"...\")]`.",
                parsed.class_name(), previous.ident, method.ident, name))
    })format!(
4924                    "Env member `{}${name}` is defined by both `{}` and `{}`. \
4925                     Constructors always occupy `new`; instance and static methods \
4926                     share the class environment. Rename a colliding method with \
4927                     `#[miniextendr(r_name = \"...\")]`.",
4928                    parsed.class_name(),
4929                    previous.ident,
4930                    method.ident,
4931                ),
4932            ));
4933        }
4934    }
4935    Ok(())
4936}
4937
4938/// R6 always has an `initialize` member, including classes without a Rust
4939/// constructor. R6 requires public, private and active names to be distinct;
4940/// reject collisions before the generated class fails during package loading.
4941fn check_r6_initialize_collision(parsed: &ParsedImpl) -> syn::Result<()> {
4942    if parsed.class_system != ClassSystem::R6 {
4943        return Ok(());
4944    }
4945    for method in parsed
4946        .public_instance_methods()
4947        .chain(parsed.private_instance_methods())
4948        .chain(parsed.active_instance_methods())
4949    {
4950        let name = if method.is_active() {
4951            method
4952                .method_attrs
4953                .r6
4954                .prop
4955                .clone()
4956                .unwrap_or_else(|| method.r_method_name())
4957        } else {
4958            method.r_method_name()
4959        };
4960        if name == "initialize" {
4961            return Err(syn::Error::new_spanned(
4962                &method.ident,
4963                "R6 member `initialize` conflicts with the generated constructor. \
4964                 Rename the method or use `#[miniextendr(r_name = \"...\")]`; \
4965                 for an active binding, choose a different `r6(prop = \"...\")`.",
4966            ));
4967        }
4968    }
4969    Ok(())
4970}
4971
4972/// The bindings of an `R6::R6Class()` generator object (R6 2.6). The R6
4973/// generator assigns static methods onto that object (`Class$name <- function`),
4974/// so a static method under one of these names silently replaces R6's own:
4975/// `new` stops creating objects, `set` and `lock` are the generated `$set()` /
4976/// `$lock()` calls, and `$new()` reads the data fields.
4977const R6_GENERATOR_BINDINGS: &[&str] = &[
4978    "active",
4979    "class",
4980    "classname",
4981    "clone_method",
4982    "cloneable",
4983    "debug",
4984    "debug_names",
4985    "get_inherit",
4986    "has_private",
4987    "inherit",
4988    "is_locked",
4989    "lock",
4990    "lock_class",
4991    "lock_objects",
4992    "new",
4993    "parent_env",
4994    "portable",
4995    "private_fields",
4996    "private_methods",
4997    "public_fields",
4998    "public_methods",
4999    "self",
5000    "set",
5001    "undebug",
5002    "unlock",
5003];
5004
5005/// Reject an R6 static method whose R name is one of the generator object's
5006/// own bindings ([`R6_GENERATOR_BINDINGS`]), which the static would replace
5007/// without a warning when the package loads.
5008fn check_r6_static_collisions(parsed: &ParsedImpl) -> syn::Result<()> {
5009    if parsed.class_system != ClassSystem::R6 {
5010        return Ok(());
5011    }
5012    for method in parsed.static_methods() {
5013        let name = method.r_method_name();
5014        if R6_GENERATOR_BINDINGS.contains(&name.as_str()) {
5015            return Err(syn::Error::new_spanned(
5016                &method.ident,
5017                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("R6 static method `{0}${1}` would replace the R6 generator\'s own `{1}`: static methods are assigned onto the generator object. Rename it with `#[miniextendr(r_name = \"...\")]`.",
                parsed.class_name(), name))
    })format!(
5018                    "R6 static method `{class}${name}` would replace the R6 generator's own \
5019                     `{name}`: static methods are assigned onto the generator object. Rename \
5020                     it with `#[miniextendr(r_name = \"...\")]`.",
5021                    class = parsed.class_name(),
5022                ),
5023            ));
5024        }
5025    }
5026    Ok(())
5027}
5028
5029/// Two instance methods of one S4 impl block that dispatch through the same
5030/// generic emit two `setMethod("<generic>", "<Class>", ...)` calls with the
5031/// same signature, and the second silently replaces the first. The default
5032/// generic follows the R method name (`s4_<r_name>`), so `r_name = "x"` next to
5033/// a method `x` is one way to get there; two equal `s4(generic = "...")`
5034/// overrides are another.
5035fn check_s4_generic_collisions(parsed: &ParsedImpl) -> syn::Result<()> {
5036    if parsed.class_system != ClassSystem::S4 {
5037        return Ok(());
5038    }
5039    let mut seen = std::collections::HashMap::new();
5040    for method in parsed.instance_methods() {
5041        let generic = s4_class::s4_generic_name(method);
5042        if let Some(previous) = seen.insert(generic.clone(), method) {
5043            return Err(syn::Error::new_spanned(
5044                &method.ident,
5045                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("S4 generic `{3}` gets a method for `{0}` from both `{1}` and `{2}`; the second `setMethod()` would replace the first. Rename one with `#[miniextendr(r_name = \"...\")]` or give it another `s4(generic = \"...\")`.",
                parsed.class_name(), previous.ident, method.ident, generic))
    })format!(
5046                    "S4 generic `{generic}` gets a method for `{}` from both `{}` and `{}`; \
5047                     the second `setMethod()` would replace the first. Rename one with \
5048                     `#[miniextendr(r_name = \"...\")]` or give it another \
5049                     `s4(generic = \"...\")`.",
5050                    parsed.class_name(),
5051                    previous.ident,
5052                    method.ident,
5053                ),
5054            ));
5055        }
5056    }
5057    Ok(())
5058}
5059
5060/// Check the R formals of every generated method
5061/// ([`check_r_formals`](crate::r_wrapper_builder::check_r_formals)), reserving
5062/// the names each class system's wrapper binds itself:
5063///
5064/// - the receiver of an instance method: `x` for S3 and S4,
5065///   the first dispatch argument (`x` unless `s7(dispatch)` or an operator
5066///   says otherwise) for S7; shortcuts use the collision-free `.mx_self`;
5067/// - `self` and `private`, which R6 binds inside `initialize` and every method
5068///   of the class: the wrapper reads the pointer from `private$.ptr` and
5069///   returns `self` from a chaining method.
5070///
5071/// Static methods and the other constructors are plain functions and reserve
5072/// nothing; S7 property accessors have fixed formals, so a `formal(...)` on
5073/// one is refused (#1842); vctrs impls take no instance methods (MXL120).
5074fn check_method_formals(parsed: &ParsedImpl) -> syn::Result<()> {
5075    let receiver = |name: &str, method: &str| {
5076        (
5077            name.to_string(),
5078            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("is the receiver of the generated {0}",
                method))
    })format!("is the receiver of the generated {method}"),
5079        )
5080    };
5081    for m in parsed.included_methods() {
5082        let is_ctor = parsed.is_method_constructor(m);
5083        let instance = m.env.is_instance() && !is_ctor && !m.is_finalizer();
5084        if (m.method_attrs.receiver.is_some() || m.method_attrs.no_dispatch_dots) && !instance {
5085            return Err(syn::Error::new_spanned(
5086                &m.ident,
5087                "`receiver` and `no_dots` apply only to instance methods",
5088            ));
5089        }
5090        let generic_receiver = m.method_attrs.receiver.as_deref().unwrap_or("x");
5091        let s7 = &m.method_attrs.s7;
5092        let formals = m.formals();
5093        if parsed.class_system == ClassSystem::S7
5094            && (s7.getter || s7.setter || s7.validate)
5095            && let Some(lit) = m
5096                .method_attrs
5097                .per_param
5098                .values()
5099                .find_map(|a| a.formal.as_ref())
5100        {
5101            return Err(syn::Error::new(
5102                lit.span(),
5103                "`formal(...)` on an S7 property getter, setter or validator: S7 calls it with \
5104                 fixed arguments (`self`, `value`), so a declared formal would name nothing",
5105            ));
5106        }
5107        let reserved = match parsed.class_system {
5108            ClassSystem::R6 if instance || is_ctor => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [("self".to_string(),
                    "is R6's `self` binding inside the class, the object the generated \
                     method works on".to_string()),
                ("private".to_string(),
                    "is R6's `private` binding inside the class, where the generated method \
                     reads the object's pointer".to_string())]))vec![
5109                (
5110                    "self".to_string(),
5111                    "is R6's `self` binding inside the class, the object the generated \
5112                     method works on"
5113                        .to_string(),
5114                ),
5115                (
5116                    "private".to_string(),
5117                    "is R6's `private` binding inside the class, where the generated method \
5118                     reads the object's pointer"
5119                        .to_string(),
5120                ),
5121            ],
5122            ClassSystem::S3 if instance => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [receiver(generic_receiver, "S3 method")]))vec![receiver(generic_receiver, "S3 method")],
5123            ClassSystem::S4 if instance => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [receiver(generic_receiver, "S4 method")]))vec![receiver(generic_receiver, "S4 method")],
5124            ClassSystem::S7 if instance && !(s7.getter || s7.setter || s7.validate) => {
5125                let generic = m
5126                    .method_attrs
5127                    .generic
5128                    .clone()
5129                    .unwrap_or_else(|| m.r_method_name());
5130                let dispatch =
5131                    s7_class::s7_dispatch_args(m, &s7_class::s7_generic_target(&generic));
5132                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [receiver(&dispatch[0], "S7 method")]))vec![receiver(&dispatch[0], "S7 method")]
5133            }
5134            _ => Vec::new(),
5135        };
5136        crate::r_wrapper_builder::check_r_formals(&m.sig.inputs, &formals, &reserved)?;
5137    }
5138    Ok(())
5139}
5140
5141/// Check that every S3 instance method for a replacement generic
5142/// (`s3(generic = "[[<-")`, or an `r_name` ending in `<-`) takes the new value
5143/// last, as `value`
5144/// ([`check_replacement_value_param`](crate::miniextendr_fn::check_replacement_value_param),
5145/// #1853). The generator puts the dispatch `...` before that formal
5146/// ([`s3_method_formals`](crate::r_class_formatter::MethodContext::s3_method_formals)).
5147/// Other class systems register their methods themselves, and static methods
5148/// are plain functions.
5149fn check_s3_replacement_methods(parsed: &ParsedImpl) -> syn::Result<()> {
5150    if !#[allow(non_exhaustive_omitted_patterns)] match parsed.class_system {
    ClassSystem::S3 | ClassSystem::Vctrs => true,
    _ => false,
}matches!(parsed.class_system, ClassSystem::S3 | ClassSystem::Vctrs) {
5151        return Ok(());
5152    }
5153    for m in parsed.instance_methods() {
5154        let generic = m
5155            .method_attrs
5156            .generic
5157            .clone()
5158            .unwrap_or_else(|| m.r_method_name());
5159        crate::miniextendr_fn::check_replacement_value_param(
5160            &generic,
5161            &m.sig.inputs,
5162            &m.formals(),
5163            m.ident.span(),
5164        )?;
5165    }
5166    Ok(())
5167}
5168
5169/// Refuse a `dots = empty | forward(..) | data` (#2157) that describes a
5170/// `...` the method's wrapper doesn't have
5171/// ([`DotsPolicy::check_signature`](crate::dots_policy::DotsPolicy::check_signature)):
5172/// `forward` and `data` need the method's own `...` parameter; `empty` the
5173/// wrapper's `...` formal, which is that parameter or the dispatch `...` a
5174/// method of a generic gets ([`has_dispatch_dots`]).
5175fn check_dots_policies(parsed: &ParsedImpl) -> syn::Result<()> {
5176    for m in &parsed.methods {
5177        if let Some(policy) = &m.method_attrs.dots_policy {
5178            policy.check_signature(
5179                m.has_dots,
5180                m.has_dots || has_dispatch_dots(parsed.class_system, m),
5181            )?;
5182        }
5183    }
5184    Ok(())
5185}
5186
5187/// Whether the class system gives `m`'s R wrapper a `...` formal the Rust
5188/// method doesn't take: the dispatch `...` of an S3, S4 or S7 instance method
5189/// (unless `no_dispatch_dots` / `s7(no_dots)`), and of a vctrs protocol
5190/// method. Env and R6 methods and every other static method have only the
5191/// formals of the Rust signature.
5192fn has_dispatch_dots(class_system: ClassSystem, m: &ParsedMethod) -> bool {
5193    match class_system {
5194        ClassSystem::Vctrs => m.method_attrs.vctrs_protocol.is_some(),
5195        _ if !m.env.is_instance() => false,
5196        ClassSystem::S3 | ClassSystem::S4 => !m.method_attrs.no_dispatch_dots,
5197        ClassSystem::S7 => !m.method_attrs.s7.no_dots,
5198        ClassSystem::Env | ClassSystem::R6 => false,
5199    }
5200}
5201
5202/// Validate the S7 dispatch arguments of every S7 instance method: an explicit
5203/// `s7(dispatch = "...")`, and the pair S7 fixes for an `Ops` / `%*%`
5204/// operator generic (`e1, e2` / `x, y`).
5205///
5206/// S7 registers a method only when its formals start with the generic's
5207/// dispatch arguments, in order and without defaults, and it rejects the
5208/// wrong number of classes in the signature; any violation stops the package
5209/// from loading. The generator names the receiver after the first dispatch
5210/// argument and takes the others from the method's leading parameters, so the
5211/// rules are checked here, where the error can name the fix. `!` is rejected
5212/// outright because S7 does not dispatch it. Non-S7 class systems, static
5213/// methods and property accessors are a no-op.
5214fn check_s7_dispatch(parsed: &ParsedImpl) -> syn::Result<()> {
5215    if parsed.class_system != ClassSystem::S7 {
5216        return Ok(());
5217    }
5218    for m in parsed.instance_methods() {
5219        if m.method_attrs.s7.getter || m.method_attrs.s7.setter || m.method_attrs.s7.validate {
5220            continue;
5221        }
5222        let ctx = crate::r_class_formatter::MethodContext::new(m, &parsed.type_ident);
5223        check_s7_method_dispatch(m, &ctx.params)
5224            .map_err(|message| syn::Error::new(m.ident.span(), message))?;
5225    }
5226    Ok(())
5227}
5228
5229/// [`check_s7_dispatch`] for one method; `params` is its R formals string
5230/// (normalized names, with defaults).
5231fn check_s7_method_dispatch(m: &ParsedMethod, params: &str) -> Result<(), String> {
5232    use s7_class::{S7GenericTarget, s7_dispatch_args, s7_generic_target};
5233
5234    let rust_name = crate::naming::ident_name(&m.ident);
5235    let generic = m
5236        .method_attrs
5237        .generic
5238        .clone()
5239        .unwrap_or_else(|| m.r_method_name());
5240    let target = s7_generic_target(&generic);
5241    let op = target.name();
5242    if op == "!" {
5243        return Err(
5244            "S7 methods cannot be generated for the `!` operator: S7 does not dispatch \
5245                    `!` (its Ops handling covers the binary operators only). Keep this method \
5246                    under an ordinary name and call it directly."
5247                .to_string(),
5248        );
5249    }
5250
5251    let dispatch = s7_dispatch_args(m, &target);
5252    let spec = m
5253        .method_attrs
5254        .s7
5255        .dispatch
5256        .clone()
5257        .unwrap_or_else(|| dispatch.join(", "));
5258    let formals = crate::roxygen::split_r_formals(params);
5259    let names: Vec<&str> = formals
5260        .iter()
5261        .map(|f| crate::roxygen::formal_name(f))
5262        .collect();
5263    let listed = if names.is_empty() {
5264        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` has no parameters besides the receiver",
                rust_name))
    })format!("`{rust_name}` has no parameters besides the receiver")
5265    } else {
5266        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the R parameters of `{1}` are {0}",
                names.iter().map(|n|
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("`{0}`", n))
                                    })).collect::<Vec<_>>().join(", "), rust_name))
    })format!(
5267            "the R parameters of `{rust_name}` are {}",
5268            names
5269                .iter()
5270                .map(|n| format!("`{n}`"))
5271                .collect::<Vec<_>>()
5272                .join(", ")
5273        )
5274    };
5275
5276    let mut seen = std::collections::HashSet::new();
5277    for d in &dispatch {
5278        // `...` / `..1` pass R's syntactic-name rule but are not arguments.
5279        if !crate::naming::is_syntactic_r_name(d) || d.starts_with("..") {
5280            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`s7(dispatch = \"{0}\")` on `{1}`: `{2}` is not a syntactic R argument name (S7 dispatch arguments are plain names, and `...` cannot be one)",
                spec, rust_name, d))
    })format!(
5281                "`s7(dispatch = \"{spec}\")` on `{rust_name}`: `{d}` is not a syntactic R \
5282                 argument name (S7 dispatch arguments are plain names, and `...` cannot be one)"
5283            ));
5284        }
5285        if !seen.insert(d.as_str()) {
5286            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`s7(dispatch = \"{0}\")` on `{1}` names `{2}` twice",
                spec, rust_name, d))
    })format!(
5287                "`s7(dispatch = \"{spec}\")` on `{rust_name}` names `{d}` twice"
5288            ));
5289        }
5290    }
5291
5292    let is_base_operator = #[allow(non_exhaustive_omitted_patterns)] match target {
    S7GenericTarget::BaseOperator(_) => true,
    _ => false,
}matches!(target, S7GenericTarget::BaseOperator(_));
5293    if let Some(pair) = s7_class::s7_operator_dispatch_args(op).filter(|_| is_base_operator) {
5294        let [left, right] = pair;
5295        if dispatch != pair {
5296            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("S7 dispatches `{0}` on `{1}` and `{2}`, so `s7(dispatch = \"{3}\")` cannot be used on `{4}`: drop it (the pair is the default for `{0}`)",
                op, left, right, spec, rust_name))
    })format!(
5297                "S7 dispatches `{op}` on `{left}` and `{right}`, so `s7(dispatch = \"{spec}\")` \
5298                 cannot be used on `{rust_name}`: drop it (the pair is the default for `{op}`)"
5299            ));
5300        }
5301        if m.method_attrs.s7.fallback {
5302            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`s7(fallback)` cannot be combined with the `{0}` operator on `{1}`: it would register the method for every pair of operands, not for this class",
                op, rust_name))
    })format!(
5303                "`s7(fallback)` cannot be combined with the `{op}` operator on `{rust_name}`: \
5304                 it would register the method for every pair of operands, not for this class"
5305            ));
5306        }
5307        let operands: Vec<&str> = names.iter().copied().filter(|n| *n != "...").collect();
5308        if operands.len() != 1 {
5309            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` implements the `{1}` operator, so it takes exactly one parameter besides the receiver: the right operand, named `{2}` (S7 calls the method as `{3} {1} {2}`); {4}",
                rust_name, op, right, left, listed))
    })format!(
5310                "`{rust_name}` implements the `{op}` operator, so it takes exactly one parameter \
5311                 besides the receiver: the right operand, named `{right}` (S7 calls the method \
5312                 as `{left} {op} {right}`); {listed}"
5313            ));
5314        }
5315        if operands[0] != right {
5316            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("S7 dispatches `{1}` on `{2}` and `{3}`: the receiver becomes `{2}` and the right operand of `{4}` must be named `{3}`. Rename the parameter `{0}` to `{3}`.",
                operands[0], op, left, right, rust_name))
    })format!(
5317                "S7 dispatches `{op}` on `{left}` and `{right}`: the receiver becomes `{left}` and \
5318                 the right operand of `{rust_name}` must be named `{right}`. Rename the parameter \
5319                 `{}` to `{right}`.",
5320                operands[0]
5321            ));
5322        }
5323    }
5324    if is_base_operator && s7_class::s7_operator_dispatch_args(op).is_none() && dispatch.len() > 1 {
5325        return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("S7 dispatches `{0}` through the base primitive on its first argument only, so `s7(dispatch = \"{1}\")` cannot be used on `{2}`: drop it",
                op, spec, rust_name))
    })format!(
5326            "S7 dispatches `{op}` through the base primitive on its first argument only, so \
5327             `s7(dispatch = \"{spec}\")` cannot be used on `{rust_name}`: drop it"
5328        ));
5329    }
5330
5331    // A parameter named like the receiver (`dispatch[0]`) is rejected earlier,
5332    // by `check_method_formals`.
5333    for (i, d) in dispatch.iter().enumerate().skip(1) {
5334        let Some(&found) = names.get(i - 1) else {
5335            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`s7(dispatch = \"{0}\")` on `{1}`: dispatch argument `{2}` must be parameter {3} of the method (S7 needs a method\'s formals to start with the generic\'s dispatch arguments, the first naming the receiver), but {4}",
                spec, rust_name, d, i, listed))
    })format!(
5336                "`s7(dispatch = \"{spec}\")` on `{rust_name}`: dispatch argument `{d}` must be \
5337                 parameter {i} of the method (S7 needs a method's formals to start with the \
5338                 generic's dispatch arguments, the first naming the receiver), but {listed}"
5339            ));
5340        };
5341        if found != d {
5342            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`s7(dispatch = \"{0}\")` on `{1}`: dispatch argument `{2}` must be parameter {3} of the method, found `{4}` (S7 needs a method\'s formals to start with the generic\'s dispatch arguments, in order, the first naming the receiver); {5}",
                spec, rust_name, d, i, found, listed))
    })format!(
5343                "`s7(dispatch = \"{spec}\")` on `{rust_name}`: dispatch argument `{d}` must be \
5344                 parameter {i} of the method, found `{found}` (S7 needs a method's formals to \
5345                 start with the generic's dispatch arguments, in order, the first naming the \
5346                 receiver); {listed}"
5347            ));
5348        }
5349        if formals[i - 1].contains('=') {
5350            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`s7(dispatch = \"{1}\")` on `{2}`: dispatch argument `{3}` has a default value (`{0}`), which S7 does not allow on dispatch arguments",
                formals[i - 1].trim(), spec, rust_name, d))
    })format!(
5351                "`s7(dispatch = \"{spec}\")` on `{rust_name}`: dispatch argument `{d}` has a \
5352                 default value (`{}`), which S7 does not allow on dispatch arguments",
5353                formals[i - 1].trim()
5354            ));
5355        }
5356    }
5357    if m.method_attrs.s7.no_dots
5358        && #[allow(non_exhaustive_omitted_patterns)] match target {
    S7GenericTarget::Local(_) => true,
    _ => false,
}matches!(target, S7GenericTarget::Local(_))
5359        && let Some(extra) = names.get(dispatch.len() - 1)
5360    {
5361        return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`s7(no_dots)` on `{0}` makes a generic without `...`, and S7 then requires every method\'s formals to equal its dispatch arguments, but `{1}` is not one. Add it to `s7(dispatch = \"...\")` or drop `no_dots`.",
                rust_name, extra))
    })format!(
5362            "`s7(no_dots)` on `{rust_name}` makes a generic without `...`, and S7 then requires \
5363             every method's formals to equal its dispatch arguments, but `{extra}` is not one. \
5364             Add it to `s7(dispatch = \"...\")` or drop `no_dots`."
5365        ));
5366    }
5367    Ok(())
5368}
5369
5370/// Top-level entry point for expanding `#[miniextendr]` on impl blocks.
5371///
5372/// Dispatches between two cases:
5373/// 1. **Inherent impls** (`impl Type { ... }`): Parses [`ImplAttrs`] and [`ParsedImpl`],
5374///    then generates C wrappers, R wrapper code, `R_CallMethodDef` arrays, and
5375///    `as.<class>()` trait impls for the chosen class system.
5376/// 2. **Trait impls** (`impl Trait for Type { ... }`): Generates trait ABI vtables,
5377///    cross-package shims, and R wrappers via
5378///    [`expand_miniextendr_impl_trait`](crate::miniextendr_impl_trait::expand_miniextendr_impl_trait).
5379///
5380/// # Arguments
5381///
5382/// * `attr` - The token stream inside `#[miniextendr(...)]` (class system, options)
5383/// * `item` - The full `impl` block token stream
5384///
5385/// # Returns
5386///
5387/// A token stream containing the original impl block (with miniextendr attrs stripped),
5388/// C wrapper functions, an R wrapper string constant, a `R_CallMethodDef` array constant,
5389/// and any forwarding trait impls for `as.<class>()` coercion.
5390pub fn expand_impl(
5391    attr: proc_macro::TokenStream,
5392    item: proc_macro::TokenStream,
5393) -> proc_macro::TokenStream {
5394    let item_impl = match syn::parse::<syn::ItemImpl>(item.clone()) {
5395        Ok(i) => i,
5396        Err(e) => return e.into_compile_error().into(),
5397    };
5398
5399    // Check if this is a trait impl (impl Trait for Type)
5400    if item_impl.trait_.is_some() {
5401        // Delegate to trait ABI vtable generator
5402        return crate::miniextendr_impl_trait::expand_miniextendr_impl_trait(attr, item);
5403    }
5404
5405    // Otherwise, this is an inherent impl - parse class system attrs
5406    let attrs = match syn::parse::<ImplAttrs>(attr) {
5407        Ok(a) => a,
5408        Err(e) => return e.into_compile_error().into(),
5409    };
5410
5411    let mut parsed = match ParsedImpl::parse(attrs, item_impl) {
5412        Ok(p) => p,
5413        Err(e) => return e.into_compile_error().into(),
5414    };
5415
5416    if let Err(e) = check_class_members(&parsed) {
5417        return e.into_compile_error().into();
5418    }
5419    // A block that infers its constructor is written in one of two
5420    // renderings, decided per type by the wrapper writer: with that
5421    // constructor, or (when another block declares one) with it as a static
5422    // method. Both must hold.
5423    let infers_constructor = parsed.inferred_constructor().is_some();
5424    let demoted_class = if infers_constructor {
5425        parsed.constructor_demoted = true;
5426        let demoted = parsed
5427            .reject_unsupported_describe_in()
5428            .and_then(|()| check_class_members(&parsed))
5429            .map(|()| (generate_class_wrapper(&parsed), parsed.class_definitions()));
5430        parsed.constructor_demoted = false;
5431        match demoted {
5432            Ok(class) => Some(class),
5433            Err(e) => return e.into_compile_error().into(),
5434        }
5435    } else {
5436        None
5437    };
5438
5439    let type_ident = &parsed.type_ident;
5440    let cfg_attrs = &parsed.cfg_attrs;
5441
5442    // Generate C wrappers for all included methods
5443    let c_wrappers: Vec<TokenStream> = parsed
5444        .included_methods()
5445        .map(|m| generate_method_c_wrapper(&parsed, m))
5446        .collect();
5447    // The `.Call` entries of the field fallback (#2150), which this block's
5448    // field methods call; only the block that defines the class has one.
5449    let fallback_entries = field_syntax::fallback_c_entries(&parsed);
5450
5451    // The R wrapper, in the parts the wrapper writer merges per type (#1776).
5452    let class = generate_class_wrapper(&parsed);
5453
5454    let original_impl = &parsed.original_impl;
5455
5456    // Generate forwarding trait impls for as.<class>() coercion methods
5457    let trait_impls = generate_as_coercion_trait_impls(&parsed);
5458
5459    // Every part is qualified against the formals pooled over the whole block
5460    // (the constructor included).
5461    let formals = crate::r_shadowing::formal_names(
5462        parsed
5463            .included_methods()
5464            .map(|m| (&m.sig.inputs, m.formals())),
5465    );
5466    let r_part = |lines: &[String]| crate::r_wrapper_raw_literal(&lines.join("\n"), &formals);
5467    let class_parts = |class: &ClassWrapper, defines: &[String]| {
5468        let head = r_part(&class.head);
5469        let class_docs = r_part(&class.class_docs);
5470        let class_doc_lines = r_part(&class.class_doc_lines);
5471        let members = r_part(&class.members);
5472        let env = r_part(&class.env);
5473        let tail = r_part(&class.tail);
5474        let member_names = &class.member_names;
5475        {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "defines");
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            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 defines, i) = defines.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let defines =
                        match defines.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&defines, &mut _s);
                }
            }
            _s
        });
    ::quote::__private::push_comma(&mut _s);
    ::quote::__private::push_ident(&mut _s, "head");
    ::quote::__private::push_colon(&mut _s);
    ::quote::ToTokens::to_tokens(&head, &mut _s);
    ::quote::__private::push_comma(&mut _s);
    ::quote::__private::push_ident(&mut _s, "class_docs");
    ::quote::__private::push_colon(&mut _s);
    ::quote::ToTokens::to_tokens(&class_docs, &mut _s);
    ::quote::__private::push_comma(&mut _s);
    ::quote::__private::push_ident(&mut _s, "class_doc_lines");
    ::quote::__private::push_colon(&mut _s);
    ::quote::ToTokens::to_tokens(&class_doc_lines, &mut _s);
    ::quote::__private::push_comma(&mut _s);
    ::quote::__private::push_ident(&mut _s, "members");
    ::quote::__private::push_colon(&mut _s);
    ::quote::ToTokens::to_tokens(&members, &mut _s);
    ::quote::__private::push_comma(&mut _s);
    ::quote::__private::push_ident(&mut _s, "member_names");
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            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 member_names, i) = member_names.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let member_names =
                        match member_names.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&member_names, &mut _s);
                }
            }
            _s
        });
    ::quote::__private::push_comma(&mut _s);
    ::quote::__private::push_ident(&mut _s, "env");
    ::quote::__private::push_colon(&mut _s);
    ::quote::ToTokens::to_tokens(&env, &mut _s);
    ::quote::__private::push_comma(&mut _s);
    ::quote::__private::push_ident(&mut _s, "tail");
    ::quote::__private::push_colon(&mut _s);
    ::quote::ToTokens::to_tokens(&tail, &mut _s);
    ::quote::__private::push_comma(&mut _s);
    _s
}quote! {
5476            defines: &[#(#defines),*],
5477            head: #head,
5478            class_docs: #class_docs,
5479            class_doc_lines: #class_doc_lines,
5480            members: #members,
5481            member_names: &[#(#member_names),*],
5482            env: #env,
5483            tail: #tail,
5484        }
5485    };
5486
5487    let source_loc_doc = crate::source_location_doc(type_ident.span());
5488    let source_start = type_ident.span().start();
5489    let source_line_lit = syn::LitInt::new(&source_start.line.to_string(), type_ident.span());
5490    let source_col_lit =
5491        syn::LitInt::new(&(source_start.column + 1).to_string(), type_ident.span());
5492
5493    let param_warnings = &parsed.param_warnings;
5494
5495    // r_class_name is the R-visible name (may differ from type_ident when
5496    // `class = "Override"` was set on the impl block).
5497    let r_class_name_str = parsed.class_name();
5498    let class_system_str = parsed.class_system.to_ident().to_string();
5499    // `$` / `[[` field syntax (`s3/s4/env(r_data_accessors)`): the wrapper
5500    // writer then keeps the type's standalone sidecar accessors internal
5501    // (#1900). R6 bindings and S7 properties leave them exported.
5502    let field_syntax = parsed.r_data_accessors.enabled()
5503        && #[allow(non_exhaustive_omitted_patterns)] match parsed.class_system {
    ClassSystem::S3 | ClassSystem::S4 | ClassSystem::Env => true,
    _ => false,
}matches!(
5504            parsed.class_system,
5505            ClassSystem::S3 | ClassSystem::S4 | ClassSystem::Env
5506        );
5507    // The read-only form takes the standalone setters away too (#2268).
5508    let read_only_fields = field_syntax && parsed.r_data_accessors == RDataAccessors::ReadOnly;
5509    let settings = parsed.class_settings();
5510    let parts = class_parts(&class, &parsed.class_definitions());
5511    let constructor = parsed
5512        .constructor()
5513        .map(|m| crate::naming::ident_name(&m.ident))
5514        .unwrap_or_default();
5515    let candidates: Vec<String> = parsed
5516        .constructor_candidates()
5517        .map(|m| crate::naming::ident_name(&m.ident))
5518        .collect();
5519    let block_entry = |constructor: &str, inferred: bool, demoted, parts| {
5520        {
    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, "ClassBlockEntry");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "rust_type");
            ::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(&type_ident, &mut _s);
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            ::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(&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_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "r_class_name");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&r_class_name_str, &mut _s);
            ::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, "source_column");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&source_col_lit, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "settings");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&settings, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "constructor");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&constructor, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "constructor_inferred");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&inferred, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "constructor_candidates");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    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 candidates, i) = candidates.quote_into_iter();
                        let has_iter = has_iter | i;
                        <_ as
                                ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                        while true {
                            let candidates =
                                match candidates.next() {
                                    Some(_x) => ::quote::__private::RepInterp(_x),
                                    None => break,
                                };
                            if !_first { ::quote::__private::push_comma(&mut _s); }
                            _first = false;
                            ::quote::ToTokens::to_tokens(&candidates, &mut _s);
                        }
                    }
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "demoted");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&demoted, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&parts, &mut _s);
            _s
        });
    _s
}quote! {
5521            ::miniextendr_api::registry::ClassBlockEntry {
5522                rust_type: ::core::stringify!(#type_ident),
5523                type_path: || ::core::any::type_name::<#type_ident>(),
5524                r_class_name: #r_class_name_str,
5525                source_file: ::core::file!(),
5526                source_line: #source_line_lit,
5527                source_column: #source_col_lit,
5528                settings: #settings,
5529                constructor: #constructor,
5530                constructor_inferred: #inferred,
5531                constructor_candidates: &[#(#candidates),*],
5532                demoted: #demoted,
5533                #parts
5534            }
5535        }
5536    };
5537    // A block that infers its constructor also registers the rendering in
5538    // which that method is a static method (`demoted`).
5539    let (demoted_static, demoted_ref) = match &demoted_class {
5540        Some((demoted, definitions)) => {
5541            let entry = block_entry(
5542                "",
5543                false,
5544                {
    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!(::core::option::Option::None),
5545                class_parts(demoted, definitions),
5546            );
5547            (
5548                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "static");
    ::quote::__private::push_ident(&mut _s, "DEMOTED");
    ::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, "ClassBlockEntry");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&entry, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    _s
}quote! {
5549                    static DEMOTED: ::miniextendr_api::registry::ClassBlockEntry = #entry;
5550                },
5551                {
    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_and(&mut _s);
            ::quote::__private::push_ident(&mut _s, "DEMOTED");
            _s
        });
    _s
}quote!(::core::option::Option::Some(&DEMOTED)),
5552            )
5553        }
5554        None => (::quote::__private::TokenStream::new()quote!(), {
    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!(::core::option::Option::None)),
5555    };
5556    let class_block = block_entry(&constructor, infers_constructor, demoted_ref, parts);
5557    let constructor_check = constructor_check(&parsed);
5558
5559    // The registrations sit in an anonymous `const _` so that any number of
5560    // impl blocks of one type can register theirs; the wrapper writer merges
5561    // them per type (#1776).
5562    let expanded = {
    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_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::ToTokens::to_tokens(&original_impl, &mut _s);
    ::quote::ToTokens::to_tokens(&param_warnings, &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::ToTokens::to_tokens(&fallback_entries, &mut _s);
    ::quote::ToTokens::to_tokens(&trait_impls, &mut _s);
    ::quote::ToTokens::to_tokens(&constructor_check, &mut _s);
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut cfg_attrs, i) = cfg_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let cfg_attrs =
                match cfg_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&cfg_attrs, &mut _s);
        }
    }
    ::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::ToTokens::to_tokens(&demoted_static, &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, "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_CLASS_BLOCKS");
                                    _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, "CLASS_BLOCK");
            ::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, "ClassBlockEntry");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&class_block, &mut _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, "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_CLASS_NAMES");
                                    _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, "CLASS_NAME");
            ::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, "ClassNameEntry");
            ::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, "ClassNameEntry");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "rust_type");
                    ::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(&type_ident, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "r_class_name");
                    ::quote::__private::push_colon(&mut _s);
                    ::quote::ToTokens::to_tokens(&r_class_name_str, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "class_system");
                    ::quote::__private::push_colon(&mut _s);
                    ::quote::ToTokens::to_tokens(&class_system_str, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "field_syntax");
                    ::quote::__private::push_colon(&mut _s);
                    ::quote::ToTokens::to_tokens(&field_syntax, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "read_only_fields");
                    ::quote::__private::push_colon(&mut _s);
                    ::quote::ToTokens::to_tokens(&read_only_fields, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote! {
5563        #[doc = #source_loc_doc]
5564        #[doc = ::core::concat!("Generated from source file `", ::core::file!(), "`.")]
5565        #original_impl
5566
5567        // Warnings for @param tags on impl blocks
5568        #param_warnings
5569
5570        // C wrappers and call method defs
5571        #(#c_wrappers)*
5572        #fallback_entries
5573
5574        // Forwarding trait impls for as.<class>() coercion methods
5575        #trait_impls
5576
5577        #constructor_check
5578
5579        #(#cfg_attrs)*
5580        const _: () = {
5581            #demoted_static
5582
5583            // The impl block's share of the R class, merged with the type's
5584            // other impl blocks by the wrapper writer.
5585            #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_CLASS_BLOCKS), linkme(crate = ::miniextendr_api::linkme))]
5586            static CLASS_BLOCK: ::miniextendr_api::registry::ClassBlockEntry = #class_block;
5587
5588            // Class name registration for cross-reference placeholder resolution.
5589            // Maps the Rust type name to the R-visible class name at link time.
5590            #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_CLASS_NAMES), linkme(crate = ::miniextendr_api::linkme))]
5591            static CLASS_NAME: ::miniextendr_api::registry::ClassNameEntry =
5592                ::miniextendr_api::registry::ClassNameEntry {
5593                    rust_type: ::core::stringify!(#type_ident),
5594                    r_class_name: #r_class_name_str,
5595                    class_system: #class_system_str,
5596                    field_syntax: #field_syntax,
5597                    read_only_fields: #read_only_fields,
5598                };
5599        };
5600    };
5601
5602    expanded.into()
5603}
5604
5605/// The checks of the members a block generates, which `expand_impl` runs on
5606/// each rendering of the block.
5607fn check_class_members(parsed: &ParsedImpl) -> syn::Result<()> {
5608    // Every R formal must parse, be distinct, and leave the names the class
5609    // system's wrapper binds itself (receiver, R6 `self` / `private`) alone.
5610    check_method_formals(parsed)?;
5611    check_env_member_collisions(parsed)?;
5612    check_r6_initialize_collision(parsed)?;
5613    check_r6_static_collisions(parsed)?;
5614    check_s4_generic_collisions(parsed)?;
5615    // A replacement method (`s3(generic = "[[<-")`) takes `value` last.
5616    check_s3_replacement_methods(parsed)?;
5617    // `dots = empty | forward(..) | data` needs a `...` to describe (#2157).
5618    check_dots_policies(parsed)?;
5619    // Detect S7 fast-path shortcut name collisions (#986). The shortcut
5620    // `<ClassName>_<method>` shares a namespace with the standalone functions
5621    // emitted for static methods — an `r_name` override (or a static method
5622    // literally named like an instance method) can make two definitions clash,
5623    // with the last one silently winning. Fail loudly at compile time instead.
5624    check_s7_shortcut_collisions(parsed)?;
5625    // S7 only registers a method whose formals start with the generic's
5626    // dispatch arguments (`s7(dispatch)`, the `e1, e2` of an Ops operator);
5627    // anything else would stop the package from loading.
5628    check_s7_dispatch(parsed)
5629}
5630
5631/// The block's R wrapper, in the parts the wrapper writer merges per type
5632/// (#1776), with the `as.<class>()` coercion methods (any class system).
5633fn generate_class_wrapper(parsed: &ParsedImpl) -> ClassWrapper {
5634    let mut class = match parsed.class_system {
5635        ClassSystem::Env => generate_env_class(parsed),
5636        ClassSystem::R6 => generate_r6_class(parsed),
5637        ClassSystem::S3 => generate_s3_class(parsed),
5638        ClassSystem::S7 => generate_s7_class(parsed),
5639        ClassSystem::S4 => generate_s4_class(parsed),
5640        ClassSystem::Vctrs => generate_vctrs_class(parsed),
5641    };
5642    let as_coercion_wrappers = generate_as_coercion_methods(parsed);
5643    if !as_coercion_wrappers.is_empty() {
5644        class.members.push(String::new());
5645        class.members.push(as_coercion_wrappers);
5646    }
5647    class
5648}
5649
5650/// The compile-time half of the constructor decision. A block that declares
5651/// the constructor implements the hidden
5652/// `miniextendr_api::registry::ClassConstructor` for its type, under a
5653/// type private to the block. A block with several constructor candidates
5654/// and none declared requires that impl, once per candidate and spanned at
5655/// it, so the type compiles only when another of its impl blocks declares
5656/// the constructor; the error names each candidate. Two candidates in two
5657/// blocks are the wrapper writer's to refuse.
5658fn constructor_check(parsed: &ParsedImpl) -> TokenStream {
5659    let cfg_attrs = &parsed.cfg_attrs;
5660    let (impl_generics, _, where_clause) = parsed.original_impl.generics.split_for_impl();
5661    let self_ty = &parsed.original_impl.self_ty;
5662    if parsed.declared_constructor().is_some() {
5663        return {
    let mut _s = ::quote::__private::TokenStream::new();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut cfg_attrs, i) = cfg_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let cfg_attrs =
                match cfg_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&cfg_attrs, &mut _s);
        }
    }
    ::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_ident(&mut _s, "struct");
            ::quote::__private::push_ident(&mut _s, "__MxConstructorBlock");
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "impl");
            ::quote::ToTokens::to_tokens(&impl_generics, &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, "ClassConstructor");
            ::quote::__private::push_lt(&mut _s);
            ::quote::__private::push_ident(&mut _s, "__MxConstructorBlock");
            ::quote::__private::push_gt(&mut _s);
            ::quote::__private::push_ident(&mut _s, "for");
            ::quote::ToTokens::to_tokens(&self_ty, &mut _s);
            ::quote::ToTokens::to_tokens(&where_clause, &mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                ::quote::__private::TokenStream::new());
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote! {
5664            #(#cfg_attrs)*
5665            const _: () = {
5666                // Named so that no user type spelled in `#self_ty` is shadowed.
5667                struct __MxConstructorBlock;
5668                impl #impl_generics
5669                    ::miniextendr_api::registry::ClassConstructor<__MxConstructorBlock>
5670                    for #self_ty #where_clause {}
5671            };
5672        };
5673    }
5674    if parsed.constructor_candidates().nth(1).is_none() {
5675        return TokenStream::new();
5676    }
5677    // The type spanned at each candidate, so the error points there.
5678    let requirements = parsed.constructor_candidates().map(|m| {
5679        let mut ty = parsed.type_ident.clone();
5680        ty.set_span(m.ident.span());
5681        {
    let mut _s = ::quote::__private::TokenStream::new();
    let _span: ::quote::__private::Span =
        ::quote::__private::get_span(m.ident.span()).__into_span();
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "miniextendr_api");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "registry");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span,
        "require_class_constructor");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_lt_spanned(&mut _s, _span);
    ::quote::ToTokens::to_tokens(&ty, &mut _s);
    ::quote::__private::push_comma_spanned(&mut _s, _span);
    ::quote::__private::push_underscore_spanned(&mut _s, _span);
    ::quote::__private::push_gt_spanned(&mut _s, _span);
    ::quote::__private::push_group_spanned(&mut _s, _span,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let _: ::quote::__private::Span =
                ::quote::__private::get_span(_span).__into_span();
            ::quote::__private::TokenStream::new()
        });
    ::quote::__private::push_semi_spanned(&mut _s, _span);
    _s
}quote::quote_spanned! {m.ident.span()=>
5682            ::miniextendr_api::registry::require_class_constructor::<#ty, _>();
5683        }
5684    });
5685    {
    let mut _s = ::quote::__private::TokenStream::new();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut cfg_attrs, i) = cfg_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let cfg_attrs =
                match cfg_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&cfg_attrs, &mut _s);
        }
    }
    ::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, "allow");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "dead_code");
                            _s
                        });
                    _s
                });
            ::quote::__private::push_ident(&mut _s, "fn");
            ::quote::__private::push_ident(&mut _s, "constructor_check");
            ::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();
                    {
                        use ::quote::__private::ext::*;
                        let has_iter = ::quote::__private::HasIterator::<false>;
                        #[allow(unused_mut)]
                        let (mut requirements, i) = requirements.quote_into_iter();
                        let has_iter = has_iter | i;
                        <_ as
                                ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                        while true {
                            let requirements =
                                match requirements.next() {
                                    Some(_x) => ::quote::__private::RepInterp(_x),
                                    None => break,
                                };
                            ::quote::ToTokens::to_tokens(&requirements, &mut _s);
                        }
                    }
                    _s
                });
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote! {
5686        #(#cfg_attrs)*
5687        const _: () = {
5688            #[allow(dead_code)]
5689            fn constructor_check() {
5690                #(#requirements)*
5691            }
5692        };
5693    }
5694}
5695
5696#[cfg(test)]
5697mod tests;
5698// endregion