Skip to main content

miniextendr_macros/
externalptr_derive.rs

1//! # `#[derive(ExternalPtr)]` - ExternalPtr Support
2//!
3//! This module implements the `#[derive(ExternalPtr)]` macro which generates
4//! a `TypedExternal` impl for use with `ExternalPtr<T>`.
5//!
6//! Trait ABI wrapper infrastructure is automatically generated when you use
7//! `#[miniextendr]` on `impl Trait for Type` blocks.
8//!
9//! ## Sidecar codegen vs `#[miniextendr]` fns
10//!
11//! `#[derive(ExternalPtr)]` with `#[r_data]` fields emits a pair of C/R
12//! wrappers per sidecar field (`<Type>_get_<field>` /
13//! `<Type>_set_<field>`). **These wrappers do NOT go through
14//! `c_wrapper_builder::CWrapperContext`** — they are hand-rolled in this
15//! module so they can present the simplest signature R expects from a slot
16//! accessor:
17//!
18//! | Aspect | `#[miniextendr]` fn / method (`c_wrapper_builder`) | Sidecar accessor (here) |
19//! |---|---|---|
20//! | First C param | `__miniextendr_call: SEXP` | none |
21//! | Last C param | — | `require_live: SEXP`, the restored-pointer flag (#1891) |
22//! | C `numArgs` | 1 + user args | `2` (getter) / `3` (setter) |
23//! | R `.Call` | `.Call(C_…, .call = sys.call(), …)` | `.Call(C_…, x, FALSE)` / `.Call(C_…, x, value, FALSE)`; the field methods pass `TRUE` |
24//! | Error transport | tagged-condition SEXP via `with_r_unwind_protect(…, Some(call))` | tagged-condition SEXP via `with_r_unwind_protect(…, None)`; the R guard's `sys.call()` supplies attribution |
25//!
26//! **A sidecar R wrapper passes no `.call` argument.** The C function doesn't
27//! have a slot for it: R would throw "Incorrect number of arguments" at
28//! runtime (#344, #348).
29//!
30//! **The `require_live` flag** is how the generated `$` / `[[` / `$<-` /
31//! `[[<-` field methods refuse a pointer restored from a saved session while
32//! the standalone accessors, the R6 active bindings and the S7 properties
33//! keep reading its `Sidecar` values (#1891): one accessor per field, no
34//! extra `.Call()`. Only a `Sidecar` slot's accessors read the flag
35//! (`externalptr::sidecar_require_live`); the other kinds need the live Rust
36//! value whatever it says.
37//!
38//! ## Usage
39//!
40//! ### Basic (no traits)
41//!
42//! ```ignore
43//! #[derive(ExternalPtr)]
44//! struct MyData {
45//!     value: i32,
46//! }
47//! // Generates: impl TypedExternal for MyData { ... }
48//! ```
49//!
50//! ### With R Sidecar Slots and Class System
51//!
52//! The `#[r_data]` attribute marks fields that get R accessors. Every public
53//! slot gets the standalone `Type_get_field(x)` / `Type_set_field(x, value)`,
54//! which take the pointer or any object carrying it in `.ptr` (a list, an
55//! environment, an R6 / S4 / S7 handle). `#[externalptr(...)]` names the class
56//! system; the impl's `r_data_accessors` option also wires the slots into the
57//! class. Under the S3, S4 and env field syntax, `$` / `[[` are the class's R
58//! API and the standalone accessors are internal: no `@export`, no "Type
59//! Sidecar Accessors" page (#1900), and under its read-only form
60//! (`r_data_accessors = "read_only"`, #2268) there are no standalone setters.
61//! The derive emits the three renderings in a `SidecarAccessorsEntry`; the
62//! wrapper writer picks one by the class's `ClassNameEntry::field_syntax` and
63//! `read_only_fields`, since the impl block is a separate expansion. For the
64//! same reason each setter registers with its type in `MX_SIDECAR_SETTERS`,
65//! and `registry::call_defs` leaves a read-only type's setters out of the
66//! routines R registers (#2292).
67//! Otherwise they are exported on the type's page.
68//!
69//! | Class System | Attribute | R Accessors |
70//! |--------------|-----------|-------------|
71//! | Environment | `#[externalptr(env)]` (default) + `#[miniextendr(env(r_data_accessors))]` | `obj$field` / `obj[["field"]]` next to the methods, `obj$field <- value` |
72//! | R6 | `#[externalptr(r6)]` + `#[miniextendr(r6(r_data_accessors))]` | Active bindings, `obj$field` / `obj$field <- value` |
73//! | S3 | `#[externalptr(s3)]` + `#[miniextendr(s3(r_data_accessors))]` | `$` / `[[` / `$<-` / `[[<-` methods |
74//! | S4 | `#[externalptr(s4)]` + `#[miniextendr(s4(r_data_accessors))]` | `$` / `$<-` methods |
75//! | S7 | `#[externalptr(s7)]` + `#[miniextendr(s7(r_data_accessors))]` | Properties, `obj@field` / `obj@field <- value` |
76//!
77//! For S3, S4 and env, `r_data_accessors = "get"` generates the getters only,
78//! and `r_data_accessors = "read_only"` the getters and a `$<-` / `[[<-`
79//! that refuses every field with `miniextendr_read_only_field` (#2268).
80//! The `$` / `[[` methods share the helpers [`generate_field_syntax_helpers`]
81//! prepares for every type with R accessors (#1848). The wrapper writer includes
82//! them only when an impl enables S3, S4 or env field syntax.
83//!
84//! Standalone setters and R6 active-binding setters return the receiver invisibly
85//! by default. `#[r_data(setter = "visible")]` exposes that return value;
86//! `setter = "invisible"` explicitly requests the default. These options also
87//! control S7 property setters, whose unmarked return remains visible.
88//! R assignment itself stays invisible regardless of the setter's choice.
89//!
90//! Four field tiers are supported:
91//!
92//! 1. **Rooted values** (`Sidecar<T>`) - kept in the external pointer's
93//!    protection list, which roots them and serializes them with the
94//!    pointer. The derive generates typed accessors as associated functions
95//!    of the struct, with the field's visibility, taking a view or the
96//!    `ExternalPtr` handle (the struct holds nothing that points back at its
97//!    pointer): `#[r_data(ref)]` a getter
98//!    `fn f(ptr: &impl SidecarOwner<Self>) -> T`, `#[r_data(mut)]` a setter
99//!    `fn set_f(ptr: &mut impl SidecarOwnerMut<Self>, value: T)`,
100//!    `#[r_data(ref, mut)]` or a bare `#[r_data]` both. A method that needs
101//!    the values takes a view as its receiver (`self: ExternalPtrRef<'_, Self>`
102//!    / `mut self: ExternalPtrMut<'_, Self>`) and calls `Self::f(&self)`; see
103//!    `miniextendr_api::externalptr::Sidecar`. A bare `SEXP` field is
104//!    refused: the struct can't root it.
105//! 2. **Scalars** (`i32`, `f64`, `bool`, `u8`) - struct fields, returned as a
106//!    length-1 vector and written with `Rf_as*`
107//! 3. **Conversion types** (anything else) - struct fields, converted with the
108//!    `IntoR`/`TryFromSexp` traits on every read (unless `cache`, below) and
109//!    write
110//! 4. **Computed fields** (`#[r_data(get = "Self::f")] pub f: Computed`,
111//!    #1883) - no value in the struct; the getter calls the named
112//!    `fn(&Self) -> impl IntoR` on the live Rust value; a `Result` from it
113//!    is an error boundary, `Result<T, ()>` reading `NULL` (#2269). There
114//!    is no R setter, as for a read-only field (below). Only `pub`.
115//!
116//! `#[r_data(read_only)]` makes a public field of tier 1 to 3 read-only from
117//! R (#2268): no `Type_set_f()` and no setter C function; under the get/set
118//! field syntax an assignment raises `miniextendr_read_only_field`; the R6
119//! active binding refuses a value with the same class (no call: R6 calls the
120//! binding with `value`, not the assignment); the S7 property has no setter,
121//! so S7 refuses the write with its own error. A computed field is refused
122//! the same way (#1888). The Rust accessors of a `Sidecar<T>` field stay:
123//! `read_only` goes with `ref` / `mut`, and refuses the selector, a private
124//! or computed field and `setter = ...`.
125//!
126//! `#[r_data(cache)]` on a public tier 3 field keeps the R value its getter
127//! converts (#2271): the first read stores it
128//! (`externalptr::sidecar_r_cached`, under the field's index among the
129//! type's cached fields) and every later read returns that same object,
130//! until the value is next borrowed exclusively (a `&mut self` method, a
131//! `&mut T` argument, an R setter, `ExternalPtr::borrow_mut`, ...), which
132//! drops every kept value of the object. The derive emits
133//! `TypedExternal::CACHED_FIELD_COUNT`, the constant those borrows check. A
134//! failed conversion is not kept. It goes with `read_only`, `null_if_none`,
135//! `name`, `setter` and `prop_doc`, and refuses the selector, a tier 1, 2 or
136//! 4 field and a private one.
137//!
138//! `#[r_data(name = "keys")]` gives a field its R name (#1891): the field
139//! list, the `$` / `[[` labels, the R6 binding / S7 property and the
140//! standalone `Type_get_keys()` / `Type_set_keys()` use it; the C symbols and
141//! the Rust accessors keep the Rust identifier. The name must be a syntactic
142//! R name, unique in the type, and not `.ptr`. A `Sidecar` field's R name is
143//! also the save format (#2215): a save names the field's slot after it
144//! (`SIDECAR_NAMES`), and a reload finds the slot by it. So
145//! renaming the Rust field keeps earlier saves readable (give it the old
146//! ident as its `name` if it had none), while renaming the R name orphans
147//! the slot in every earlier save.
148//!
149//! Scalar, conversion and computed values come from the Rust struct, behind
150//! the pointer's address, which `saveRDS` does not write. The R accessors of
151//! a `Sidecar` field read and write the protection list by slot index (a
152//! restored pointer's by the field's R name, #2187): the
153//! setter validates the value with `TryFromSexp::<T>` and stores the value R
154//! gave, and the standalone accessors keep working on a pointer `readRDS()`
155//! brought back without an address (checked by the type ID in `prot[0]`).
156//!
157//! ### A saved and restored object
158//!
159//! `saveRDS()` / `serialize()` keep the pointer's `prot` list (the `Sidecar`
160//! values and the user slot) but not the Rust value. On the restored pointer
161//! the standalone `Sidecar` accessors, the R6 active bindings and the S7
162//! properties work; the generated `$` / `[[` / `$<-` / `[[<-` field methods
163//! refuse it whatever the field (they pass the accessors' `require_live`
164//! flag, #1891), and the accessor of a struct or computed field, like every
165//! method, raises the classed error `miniextendr_restored_no_value` ("restored
166//! from a saved session and has no Rust value; re-create it"). A pointer
167//! another version of the crate saved is refused by every accessor with
168//! `miniextendr_restored_other_version`, which names both versions.
169//! `#[externalptr(restored(class = ["pkg_saved", "pkg_error"], message =
170//! "..."))]` puts the package's classes in front of those (which stay) and
171//! replaces the message, on every restored refusal of the type. Its
172//! `refuse = "every_read"` (#1901) extends the field methods' refusal to the
173//! reads that never call an accessor: `names()` and an unknown `$` / `[[`
174//! name check the pointer first through one more C function
175//! (`.rdata_live_<Type>`, `externalptr::sidecar_r_live`), and `.DollarNames()`
176//! offers only the field names for a restored pointer without its value
177//! (#2218). `restored(no_handle = "...")` words the refusal of a list or
178//! environment of the class that carries no pointer, saying why (#2218);
179//! without it the restored message serves both. R's `y <- x`
180//! shares the one Rust value and the one `prot` list: a write through `y` is
181//! visible through `x`.
182//!
183//! `#[externalptr(field_error(class = ["pkg_error_field", "pkg_error"]))]`
184//! (#1899) puts the package's classes in front of the field readers' own
185//! errors: a position that picks no field (`subscriptOutOfBoundsError`
186//! stays behind them, and `0` / a negative position raise it too), a pointer
187//! of another type, and a receiver of the class that carries no pointer
188//! (`miniextendr_no_handle`, which also gets the `restored(class)` classes).
189//! They reach R as `.rdata_error_class_<Type>` and Rust as
190//! `TypedExternal::FIELD_ERROR_CLASS`. `field_error(no_field_hint = "...")`
191//! (#2112) adds the package's sentence after the field list of the
192//! `miniextendr_no_field` error, each `%s` in it the name asked for.
193//! The classes also lead `miniextendr_read_only_field`, under the field
194//! syntax and on an R6 binding, and `field_error(read_only_hint = "...")`
195//! (#2268) adds the package's sentence after its message, each `%s` in it
196//! the field's R name.
197//!
198//! ```ignore
199//! #[derive(ExternalPtr)]
200//! #[externalptr(r6)]
201//! pub struct MyType {
202//!     pub x: i32,
203//!
204//!     #[r_data]
205//!     r: RSidecar,  // Selector - enables R accessors for this type
206//!
207//!     #[r_data(ref, mut)]
208//!     pub keys: Sidecar<Vec<i32>>,  // In the protection list; `MyType::keys(&ptr)` / `MyType::set_keys(&mut ptr, v)`
209//!
210//!     #[r_data]
211//!     pub count: i32,  // Scalar struct field
212//!
213//!     #[r_data]
214//!     pub name: String,  // Conversion: uses IntoR/TryFromSexp
215//! }
216//!
217//! #[miniextendr(r6(r_data_accessors))]
218//! impl MyType {
219//!     pub fn new(n: i32) -> Self {
220//!         MyType { x: 0, r: RSidecar, keys: Sidecar::new((1..=n).collect()), count: n, name: String::new() }
221//!     }
222//!     pub fn key_count(self: ExternalPtrRef<'_, Self>) -> usize {
223//!         Self::keys(&self).len()
224//!     }
225//! }
226//! // Generates: active bindings `keys`, `count`, `name` in the R6Class
227//! ```
228//!
229//! ### Trait ABI wiring
230//!
231//! ```ignore
232//! #[derive(ExternalPtr)]
233//! struct MyCounter {
234//!     value: i32,
235//! }
236//!
237//! #[miniextendr]
238//! impl Counter for MyCounter { /* ... */ }
239//! ```
240//!
241//! ## Generated Types
242//!
243//! The runtime's generic `ErasedObject<MyCounter>` owns the value and its
244//! `mx_erased` header; no per-type wrapper struct or drop function is emitted.
245//!
246//! ### Base Vtable
247//!
248//! ```ignore
249//! static __MX_BASE_VTABLE_MyCounter: mx_base_vtable = mx_base_vtable {
250//!     drop: ErasedObject::<MyCounter>::drop_raw,
251//!     concrete_tag: __MX_TAG_MyCounter,
252//!     query: ErasedObject::<MyCounter>::query,
253//!     data_offset: ErasedObject::<MyCounter>::DATA_OFFSET,
254//! };
255//! ```
256//!
257//! Trait implementations register their vtables with the dispatch registry.
258//! The shared `registry::universal_query` looks them up by concrete type tag
259//! and trait tag; the derive emits no per-type query function.
260
261use proc_macro2::{Span, TokenStream};
262use syn::{DeriveInput, Field, Ident, Visibility};
263
264use crate::miniextendr_impl::ClassSystem;
265
266/// The package's condition classes and messages for a pointer of the type
267/// restored from a saved session, `#[externalptr(restored(class = "..." |
268/// ["...", "..."], message = "...", no_handle = "...", refuse =
269/// "every_read"))]` (#1891, #1901, #2218). Each is optional; the derive emits
270/// `TypedExternal::RESTORED_ERROR_CLASS` / `RESTORED_ERROR_MESSAGE` /
271/// `NO_HANDLE_MESSAGE` for the ones given.
272#[derive(#[automatically_derived]impl ::core::fmt::Debug for RestoredOptions {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "RestoredOptions class message no_handle every_read", &self.class,
            &self.message, &self.no_handle, &&self.every_read)
    }
}Debug, #[automatically_derived]impl ::core::default::Default for RestoredOptions {
    #[inline]
    fn default() -> Self {
        RestoredOptions {
            class: ::core::default::Default::default(),
            message: ::core::default::Default::default(),
            no_handle: ::core::default::Default::default(),
            every_read: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]impl ::core::clone::Clone for RestoredOptions {
    #[inline]
    fn clone(&self) -> Self {
        RestoredOptions {
            class: ::core::clone::Clone::clone(&self.class),
            message: ::core::clone::Clone::clone(&self.message),
            no_handle: ::core::clone::Clone::clone(&self.no_handle),
            every_read: ::core::clone::Clone::clone(&self.every_read),
        }
    }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    RestoredOptions {
}
#[automatically_derived]impl ::core::cmp::PartialEq for RestoredOptions {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.every_read == other.every_read && self.class == other.class &&
                self.message == other.message &&
            self.no_handle == other.no_handle
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for RestoredOptions {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Vec<String>>;
        let _: ::core::cmp::AssertParamIsEq<Option<String>>;
        let _: ::core::cmp::AssertParamIsEq<Option<String>>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq)]
273struct RestoredOptions {
274    /// The classes, in order, put in front of the `miniextendr_restored*`
275    /// classes.
276    class: Vec<String>,
277    /// The message, replacing miniextendr's in both restored cases.
278    message: Option<String>,
279    /// `no_handle = "..."`: the message for a list or environment of the
280    /// class that carries no pointer, saying why (#2218).
281    no_handle: Option<String>,
282    /// `refuse = "every_read"`: the field methods refuse a restored pointer
283    /// on the reads that never reach a field accessor too (`names()`, a name
284    /// that is not a field), and `.DollarNames()` offers only the field names
285    /// for it (#1901, #2218). The derive emits the liveness check they call.
286    every_read: bool,
287}
288
289/// What `#[externalptr(...)]` says about the type.
290struct ExternalPtrAttrs {
291    class_system: ClassSystem,
292    restored: RestoredOptions,
293    /// `field_error(class = ..., message = ..., no_field_hint = ...,
294    /// read_only_hint = ...)`: the field methods' own errors (#1899, #1920,
295    /// #2112, #2268).
296    field_error: FieldErrorOptions,
297}
298
299/// `#[externalptr(field_error(class = ..., message = ..., no_field_hint = ...,
300/// read_only_hint = ...))]`.
301#[derive(#[automatically_derived]impl ::core::default::Default for FieldErrorOptions {
    #[inline]
    fn default() -> Self {
        FieldErrorOptions {
            class: ::core::default::Default::default(),
            message: ::core::default::Default::default(),
            no_field_hint: ::core::default::Default::default(),
            read_only_hint: ::core::default::Default::default(),
        }
    }
}Default)]
302struct FieldErrorOptions {
303    /// The classes put in front of the errors the R field readers raise
304    /// themselves (#1899), `TypedExternal::FIELD_ERROR_CLASS`.
305    class: Vec<String>,
306    /// The package's message for a receiver of the class whose pointer is no
307    /// `T` or that carries none (#1920), `TypedExternal::FIELD_ERROR_MESSAGE`.
308    message: Option<String>,
309    /// A sentence the `miniextendr_no_field` error adds after its field list,
310    /// each `%s` replaced by the name asked for (#2112).
311    no_field_hint: Option<String>,
312    /// A sentence the `miniextendr_read_only_field` error adds after its
313    /// message, each `%s` replaced by the field's R name (#2268).
314    read_only_hint: Option<String>,
315}
316
317/// Parse `#[externalptr(...)]` attributes: the class system, the restored
318/// refusal's classes, message and scope, and the field readers' classes.
319///
320/// Supported forms:
321/// - `#[externalptr(env)]` - Environment style (default)
322/// - `#[externalptr(r6)]` - R6 class
323/// - `#[externalptr(s3)]` - S3 class
324/// - `#[externalptr(s4)]` - S4 class
325/// - `#[externalptr(s7)]` - S7 class
326/// - `#[externalptr(vctrs)]` - vctrs class
327/// - `#[externalptr(restored(class = "pkg_saved", message = "...", no_handle = "...", refuse = "every_read"))]`,
328///   with `class = ["pkg_saved", "pkg_error"]` for several classes; next to
329///   the class system (`#[externalptr(s3, restored(...))]`) or on its own.
330/// - `#[externalptr(field_error(class = ["pkg_error_config", "pkg_error"], message = "...", no_field_hint = "...", read_only_hint = "..."))]`
331fn parse_externalptr_attrs(input: &DeriveInput) -> syn::Result<ExternalPtrAttrs> {
332    let mut class_system = ClassSystem::Env; // Default
333    let mut restored: Option<RestoredOptions> = None;
334    let mut field_error: Option<FieldErrorOptions> = None;
335
336    for attr in &input.attrs {
337        if attr.path().is_ident("externalptr") {
338            attr.parse_nested_meta(|meta| {
339                let ident_str = meta
340                    .path
341                    .get_ident()
342                    .map(|i| i.to_string())
343                    .unwrap_or_default();
344
345                match ident_str.as_str() {
346                    "env" => class_system = ClassSystem::Env,
347                    "r6" => class_system = ClassSystem::R6,
348                    "s3" => class_system = ClassSystem::S3,
349                    "s4" => class_system = ClassSystem::S4,
350                    "s7" => class_system = ClassSystem::S7,
351                    "vctrs" => class_system = ClassSystem::Vctrs,
352                    "restored" => {
353                        if restored.is_some() {
354                            return Err(meta.error("`restored(...)` is given twice"));
355                        }
356                        restored = Some(parse_restored_options(&meta)?);
357                    }
358                    "field_error" => {
359                        if field_error.is_some() {
360                            return Err(meta.error("`field_error(...)` is given twice"));
361                        }
362                        field_error = Some(parse_field_error_options(&meta)?);
363                    }
364                    _ => {
365                        return Err(syn::Error::new_spanned(
366                            &meta.path,
367                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown `externalptr` option \'{0}\'; expected a class system (env, r6, s3, s4, s7, vctrs), `restored(class = ..., message = ..., refuse = ...)` or `field_error(class = ..., message = ...)`",
                ident_str))
    })format!(
368                                "unknown `externalptr` option '{}'; expected a class system (env, r6, s3, s4, s7, vctrs), `restored(class = ..., message = ..., refuse = ...)` or `field_error(class = ..., message = ...)`",
369                                ident_str
370                            ),
371                        ));
372                    }
373                }
374                Ok(())
375            })?;
376        }
377    }
378
379    Ok(ExternalPtrAttrs {
380        class_system,
381        restored: restored.unwrap_or_default(),
382        field_error: field_error.unwrap_or_default(),
383    })
384}
385
386/// The value of a `class = "..."` or `class = ["...", ...]` argument: the
387/// condition classes in order, non-empty, none of them empty.
388fn parse_class_list(inner: &syn::meta::ParseNestedMeta) -> syn::Result<Vec<String>> {
389    let value = inner.value()?;
390    let classes: Vec<syn::LitStr> = if value.peek(syn::token::Bracket) {
391        let content;
392        match ::syn::__private::parse_brackets(&value) {
    ::syn::__private::Ok(brackets) => {
        content = brackets.content;
        _ = content;
        brackets.token
    }
    ::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
};syn::bracketed!(content in value);
393        content
394            .parse_terminated(<syn::LitStr as syn::parse::Parse>::parse, ::syn::token::Commasyn::Token![,])?
395            .into_iter()
396            .collect()
397    } else {
398        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [value.parse()?]))vec![value.parse()?]
399    };
400    if classes.is_empty() {
401        return Err(inner.error("`class` needs at least one condition class"));
402    }
403    for class in &classes {
404        if class.value().is_empty() {
405            return Err(syn::Error::new_spanned(
406                class,
407                "a condition class can't be empty",
408            ));
409        }
410    }
411    Ok(classes.iter().map(syn::LitStr::value).collect())
412}
413
414/// The arguments of `restored(...)`: `class = "..."` or `class = ["...", ...]`
415/// (non-empty, in order), `message = "..."`, `no_handle = "..."` (each
416/// non-empty) and `refuse = "every_read"`, each at most once. syn refuses
417/// empty parentheses, so at least one is given.
418fn parse_restored_options(meta: &syn::meta::ParseNestedMeta) -> syn::Result<RestoredOptions> {
419    let mut options = RestoredOptions::default();
420    let mut class_given = false;
421    let mut refuse_given = false;
422    // A non-empty string option, given once.
423    let text = |inner: &syn::meta::ParseNestedMeta, given: bool, option: &str| {
424        if given {
425            return Err(inner.error(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is given twice", option))
    })format!("`{option}` is given twice")));
426        }
427        let value: syn::LitStr = inner.value()?.parse()?;
428        if value.value().is_empty() {
429            return Err(syn::Error::new_spanned(
430                value,
431                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` can\'t be empty", option))
    })format!("`{option}` can't be empty"),
432            ));
433        }
434        Ok(value)
435    };
436    meta.parse_nested_meta(|inner| {
437        if inner.path.is_ident("class") {
438            if std::mem::replace(&mut class_given, true) {
439                return Err(inner.error("`class` is given twice"));
440            }
441            options.class = parse_class_list(&inner)?;
442            Ok(())
443        } else if inner.path.is_ident("message") {
444            options.message = Some(text(&inner, options.message.is_some(), "message")?.value());
445            Ok(())
446        } else if inner.path.is_ident("no_handle") {
447            options.no_handle =
448                Some(text(&inner, options.no_handle.is_some(), "no_handle")?.value());
449            Ok(())
450        } else if inner.path.is_ident("refuse") {
451            if std::mem::replace(&mut refuse_given, true) {
452                return Err(inner.error("`refuse` is given twice"));
453            }
454            let refuse: syn::LitStr = inner.value()?.parse()?;
455            if refuse.value() != "every_read" {
456                return Err(syn::Error::new_spanned(
457                    refuse,
458                    "`refuse` takes \"every_read\": the field methods then refuse a restored pointer \
459                     on `names()` and on a name that is not a field too",
460                ));
461            }
462            options.every_read = true;
463            Ok(())
464        } else {
465            Err(inner.error(
466                "unknown `restored` option; expected `class = \"...\"` (or `class = [\"...\", ...]`), `message = \"...\"`, `no_handle = \"...\"` and `refuse = \"every_read\"`",
467            ))
468        }
469    })?;
470    Ok(options)
471}
472
473/// The arguments of `field_error(...)`: `class = "..."` or `class = ["...",
474/// ...]`, `message = "..."`, `no_field_hint = "..."` and `read_only_hint =
475/// "..."`, each once.
476fn parse_field_error_options(meta: &syn::meta::ParseNestedMeta) -> syn::Result<FieldErrorOptions> {
477    let mut class: Option<Vec<String>> = None;
478    let mut options = FieldErrorOptions::default();
479    // A non-empty string option, given once.
480    let text = |inner: &syn::meta::ParseNestedMeta, slot: &mut Option<String>, option: &str| {
481        if slot.is_some() {
482            return Err(inner.error(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is given twice", option))
    })format!("`{option}` is given twice")));
483        }
484        let value: syn::LitStr = inner.value()?.parse()?;
485        if value.value().is_empty() {
486            return Err(syn::Error::new_spanned(
487                value,
488                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is empty", option))
    })format!("`{option}` is empty"),
489            ));
490        }
491        *slot = Some(value.value());
492        Ok(())
493    };
494    meta.parse_nested_meta(|inner| {
495        if inner.path.is_ident("class") {
496            if class.is_some() {
497                return Err(inner.error("`class` is given twice"));
498            }
499            class = Some(parse_class_list(&inner)?);
500            Ok(())
501        } else if inner.path.is_ident("message") {
502            text(&inner, &mut options.message, "message")
503        } else if inner.path.is_ident("no_field_hint") {
504            text(&inner, &mut options.no_field_hint, "no_field_hint")
505        } else if inner.path.is_ident("read_only_hint") {
506            text(&inner, &mut options.read_only_hint, "read_only_hint")
507        } else {
508            Err(inner.error(
509                "unknown `field_error` option; expected `class = \"...\"` (or `class = [\"...\", ...]`), `message = \"...\"`, `no_field_hint = \"...\"` and `read_only_hint = \"...\"`",
510            ))
511        }
512    })?;
513    options.class = class.unwrap_or_default();
514    Ok(options)
515}
516
517/// Check if a field has the `#[r_data]` attribute.
518fn has_r_data_attr(field: &Field) -> bool {
519    field.attrs.iter().any(|a| a.path().is_ident("r_data"))
520}
521
522/// The last path segment that names the rooted sidecar field type,
523/// `miniextendr_api::externalptr::Sidecar<T>`. Its final name is #1857; the
524/// derive spells it here only.
525const SIDECAR_TYPE_NAME: &str = "Sidecar";
526
527/// The `T` of a `Sidecar<T>` field type, `None` for any other type.
528fn sidecar_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
529    let syn::Type::Path(type_path) = ty else {
530        return None;
531    };
532    let seg = type_path.path.segments.last()?;
533    if seg.ident != SIDECAR_TYPE_NAME {
534        return None;
535    }
536    let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
537        return None;
538    };
539    let mut types = args.args.iter().filter_map(|arg| match arg {
540        syn::GenericArgument::Type(ty) => Some(ty),
541        _ => None,
542    });
543    let inner = types.next()?;
544    types.next().is_none().then_some(inner)
545}
546
547/// The last path segment that names the marker type of a computed field,
548/// `miniextendr_api::externalptr::Computed` (#1883).
549const COMPUTED_TYPE_NAME: &str = "Computed";
550
551/// Whether a field type is `Computed`, the marker of a read-only field
552/// computed from the Rust value by the function `#[r_data(get = "...")]`
553/// names.
554fn is_computed_type(ty: &syn::Type) -> bool {
555    #[allow(non_exhaustive_omitted_patterns)] match ty {
    syn::Type::Path(type_path) if
        type_path.path.segments.last().is_some_and(|seg|
                seg.ident == COMPUTED_TYPE_NAME) => true,
    _ => false,
}matches!(ty, syn::Type::Path(type_path)
556        if type_path.path.segments.last().is_some_and(|seg| seg.ident == COMPUTED_TYPE_NAME))
557}
558
559/// Options for a sidecar field's generated documentation, setters and Rust
560/// accessors.
561#[derive(#[automatically_derived]impl ::core::default::Default for RDataOptions {
    #[inline]
    fn default() -> Self {
        RDataOptions {
            prop_doc: ::core::default::Default::default(),
            setter_invisible: ::core::default::Default::default(),
            access_ref: ::core::default::Default::default(),
            access_mut: ::core::default::Default::default(),
            name: ::core::default::Default::default(),
            get: ::core::default::Default::default(),
            read_only: ::core::default::Default::default(),
            null_if_none: ::core::default::Default::default(),
            cache: ::core::default::Default::default(),
        }
    }
}Default)]
562struct RDataOptions {
563    prop_doc: Option<String>,
564    setter_invisible: Option<bool>,
565    /// `ref`: generate the Rust getter of a `Sidecar<T>` field.
566    access_ref: Option<Span>,
567    /// `mut`: generate the Rust setter of a `Sidecar<T>` field.
568    access_mut: Option<Span>,
569    /// `name = "..."`: the field's R name, in place of the Rust identifier
570    /// (#1891).
571    name: Option<syn::LitStr>,
572    /// `get = "path"`: the getter of a `Computed` field, a
573    /// `fn(&Self) -> impl IntoR` (#1883).
574    get: Option<syn::LitStr>,
575    /// `read_only`: R reads the field and can't write it (#2268): no R
576    /// setter, and the field methods refuse a write. The Rust accessors
577    /// (`ref` / `mut`) stay.
578    read_only: Option<Span>,
579    /// `null_if_none`: an `Option<T>` struct field's getter reads `NULL` for
580    /// `None`, in place of `Option<T>`'s own conversion (`NA` for a scalar,
581    /// #2270). The setter is unchanged.
582    null_if_none: Option<Span>,
583    /// `cache`: a converted struct field's getter keeps the R value its first
584    /// read makes until the value is next borrowed exclusively (#2271).
585    cache: Option<Span>,
586}
587
588/// Which Rust accessors a `Sidecar<T>` field gets: `#[r_data(ref)]` the
589/// getter, `#[r_data(mut)]` the setter, `#[r_data(ref, mut)]` or a bare
590/// `#[r_data]` both.
591#[derive(#[automatically_derived]impl ::core::fmt::Debug for SidecarAccess {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "SidecarAccess get set", &self.get, &&self.set)
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for SidecarAccess {
}
#[automatically_derived]impl ::core::clone::Clone for SidecarAccess {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for SidecarAccess { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    SidecarAccess {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SidecarAccess {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.get == other.get && self.set == other.set
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for SidecarAccess {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq, #[automatically_derived]impl ::core::default::Default for SidecarAccess {
    #[inline]
    fn default() -> Self {
        SidecarAccess {
            get: ::core::default::Default::default(),
            set: ::core::default::Default::default(),
        }
    }
}Default)]
592struct SidecarAccess {
593    get: bool,
594    set: bool,
595}
596
597/// One item of `#[r_data(...)]`: `ref`, `mut` (both keywords, so
598/// `parse_nested_meta` cannot read them), a flag (`read_only`,
599/// `null_if_none`, `cache`) or `key = "value"`.
600enum RDataArg {
601    Ref(Span),
602    Mut(Span),
603    Flag(Ident),
604    KeyValue { key: Ident, value: syn::LitStr },
605}
606
607impl syn::parse::Parse for RDataArg {
608    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
609        let lookahead = input.lookahead1();
610        if lookahead.peek(::syn::token::Refsyn::Token![ref]) {
611            let token: ::syn::token::Refsyn::Token![ref] = input.parse()?;
612            Ok(Self::Ref(token.span))
613        } else if lookahead.peek(::syn::token::Mutsyn::Token![mut]) {
614            let token: ::syn::token::Mutsyn::Token![mut] = input.parse()?;
615            Ok(Self::Mut(token.span))
616        } else if lookahead.peek(Ident) {
617            let key: Ident = input.parse()?;
618            if !input.peek(::syn::token::Eqsyn::Token![=]) {
619                return Ok(Self::Flag(key));
620            }
621            let _eq: ::syn::token::Eqsyn::Token![=] = input.parse()?;
622            let value: syn::LitStr = input.parse()?;
623            Ok(Self::KeyValue { key, value })
624        } else {
625            Err(lookahead.error())
626        }
627    }
628}
629
630/// Parse field-level `#[r_data(ref, mut, prop_doc = "...", setter = "visible")]`
631/// options.
632fn parse_r_data_options(field: &Field) -> syn::Result<RDataOptions> {
633    let mut options = RDataOptions::default();
634    for attr in &field.attrs {
635        if !attr.path().is_ident("r_data") || #[allow(non_exhaustive_omitted_patterns)] match attr.meta {
    syn::Meta::Path(_) => true,
    _ => false,
}matches!(attr.meta, syn::Meta::Path(_)) {
636            continue;
637        }
638        let args = attr.parse_args_with(
639            syn::punctuated::Punctuated::<RDataArg, ::syn::token::Commasyn::Token![,]>::parse_terminated,
640        )?;
641        for arg in args {
642            match arg {
643                RDataArg::Ref(span) => {
644                    if options.access_ref.replace(span).is_some() {
645                        return Err(syn::Error::new(span, "duplicate `ref` option"));
646                    }
647                }
648                RDataArg::Mut(span) => {
649                    if options.access_mut.replace(span).is_some() {
650                        return Err(syn::Error::new(span, "duplicate `mut` option"));
651                    }
652                }
653                RDataArg::KeyValue { key, value } if key == "prop_doc" => {
654                    options.prop_doc = Some(value.value());
655                }
656                RDataArg::KeyValue { key, value } if key == "setter" => {
657                    if options.setter_invisible.is_some() {
658                        return Err(syn::Error::new_spanned(key, "duplicate `setter` option"));
659                    }
660                    options.setter_invisible = Some(match value.value().as_str() {
661                        "visible" => false,
662                        "invisible" => true,
663                        _ => {
664                            return Err(syn::Error::new_spanned(
665                                value,
666                                "setter must be \"visible\" or \"invisible\"",
667                            ));
668                        }
669                    });
670                }
671                RDataArg::KeyValue { key, value } if key == "name" => {
672                    if options.name.is_some() {
673                        return Err(syn::Error::new_spanned(key, "duplicate `name` option"));
674                    }
675                    options.name = Some(value);
676                }
677                RDataArg::KeyValue { key, value } if key == "get" => {
678                    if options.get.is_some() {
679                        return Err(syn::Error::new_spanned(key, "duplicate `get` option"));
680                    }
681                    options.get = Some(value);
682                }
683                RDataArg::Flag(key) if key == "read_only" => {
684                    if options.read_only.replace(key.span()).is_some() {
685                        return Err(syn::Error::new_spanned(key, "duplicate `read_only` option"));
686                    }
687                }
688                RDataArg::KeyValue { key, .. } if key == "read_only" => {
689                    return Err(syn::Error::new_spanned(
690                        &key,
691                        "`read_only` takes no value: `#[r_data(read_only)]`",
692                    ));
693                }
694                RDataArg::Flag(key) if key == "null_if_none" => {
695                    if options.null_if_none.replace(key.span()).is_some() {
696                        return Err(syn::Error::new_spanned(
697                            key,
698                            "duplicate `null_if_none` option",
699                        ));
700                    }
701                }
702                RDataArg::KeyValue { key, .. } if key == "null_if_none" => {
703                    return Err(syn::Error::new_spanned(
704                        &key,
705                        "`null_if_none` takes no value: `#[r_data(null_if_none)]`",
706                    ));
707                }
708                RDataArg::Flag(key) if key == "cache" => {
709                    if options.cache.replace(key.span()).is_some() {
710                        return Err(syn::Error::new_spanned(key, "duplicate `cache` option"));
711                    }
712                }
713                RDataArg::KeyValue { key, .. } if key == "cache" => {
714                    return Err(syn::Error::new_spanned(
715                        &key,
716                        "`cache` takes no value: `#[r_data(cache)]`",
717                    ));
718                }
719                RDataArg::Flag(key) | RDataArg::KeyValue { key, .. } => {
720                    return Err(syn::Error::new_spanned(
721                        &key,
722                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unknown key `{0}`; supported: `ref`, `mut`, `read_only`, `null_if_none`, `cache`, `name`, `get`, `prop_doc`, `setter`",
                key))
    })format!(
723                            "unknown key `{key}`; supported: `ref`, `mut`, `read_only`, `null_if_none`, \
724                             `cache`, `name`, `get`, `prop_doc`, `setter`"
725                        ),
726                    ));
727                }
728            }
729        }
730    }
731    if let Some(span) = options.read_only {
732        // `read_only` takes R's setter away: a field R reaches has one to take.
733        let refusal = if is_rsidecar_type(field) {
734            Some("the RSidecar selector, which has no R accessors".to_string())
735        } else if is_computed_type(&field.ty) {
736            Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a `{0}` field, which is read-only already: it has no setter",
                COMPUTED_TYPE_NAME))
    })format!(
737                "a `{COMPUTED_TYPE_NAME}` field, which is read-only already: it has no setter"
738            ))
739        } else if !is_pub(field) || field.ident.is_none() {
740            Some(
741                "a field that is not `pub`: only `pub` `#[r_data]` fields reach R, and \
742                 `read_only` applies to R only"
743                    .to_string(),
744            )
745        } else if options.setter_invisible.is_some() {
746            Some(
747                "a field with `setter = ...`: a read-only field has no R setter whose return \
748                 to choose"
749                    .to_string(),
750            )
751        } else {
752            None
753        };
754        if let Some(refusal) = refusal {
755            return Err(syn::Error::new(
756                span,
757                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`read_only` makes a public `#[r_data]` field read-only from R (no R setter, and the field methods refuse a write); it doesn\'t apply to {0}",
                refusal))
    })format!(
758                    "`read_only` makes a public `#[r_data]` field read-only from R (no R setter, \
759                     and the field methods refuse a write); it doesn't apply to {refusal}"
760                ),
761            ));
762        }
763    }
764    if let Some(span) = options.null_if_none {
765        // `null_if_none` changes how the getter converts an `Option<T>`
766        // struct field; no other kind converts one.
767        let refusal = if is_rsidecar_type(field) {
768            Some("the RSidecar selector, which has no R accessors".to_string())
769        } else if is_computed_type(&field.ty) {
770            Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a `{0}` field: its `get` function returns `Nullable<T>` to read `NULL` for `None`",
                COMPUTED_TYPE_NAME))
    })format!(
771                "a `{COMPUTED_TYPE_NAME}` field: its `get` function returns `Nullable<T>` to read \
772                 `NULL` for `None`"
773            ))
774        } else if sidecar_inner_type(&field.ty).is_some() {
775            Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a `{0}<T>` field, which keeps the R value it was given: declare it `{0}<Nullable<T>>` to keep `NULL` for `None`",
                SIDECAR_TYPE_NAME))
    })format!(
776                "a `{SIDECAR_TYPE_NAME}<T>` field, which keeps the R value it was given: declare it \
777                 `{SIDECAR_TYPE_NAME}<Nullable<T>>` to keep `NULL` for `None`"
778            ))
779        } else if !is_pub(field) || field.ident.is_none() {
780            Some("a field that is not `pub`: only `pub` `#[r_data]` fields reach R".to_string())
781        } else if crate::type_inspect::nullable_inner_type(&field.ty).is_some() {
782            Some("a `Nullable<T>` field, which reads `NULL` for `None` already".to_string())
783        } else if !crate::type_inspect::is_option_type(&field.ty) {
784            Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a `{0}` field: only an `Option<T>` field has a `None`",
                crate::type_inspect::type_display(&field.ty)))
    })format!(
785                "a `{}` field: only an `Option<T>` field has a `None`",
786                crate::type_inspect::type_display(&field.ty)
787            ))
788        } else {
789            None
790        };
791        if let Some(refusal) = refusal {
792            return Err(syn::Error::new(
793                span,
794                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`null_if_none` makes a public `Option<T>` `#[r_data]` field read `NULL` for `None` (in place of `NA` for a scalar); it doesn\'t apply to {0}",
                refusal))
    })format!(
795                    "`null_if_none` makes a public `Option<T>` `#[r_data]` field read `NULL` for \
796                     `None` (in place of `NA` for a scalar); it doesn't apply to {refusal}"
797                ),
798            ));
799        }
800    }
801    if let Some(span) = options.cache {
802        // `cache` keeps what a struct field's getter converts; the other
803        // kinds convert nothing on a read, or read more than the struct. A
804        // scalar field is refused with its kind (`parse_sidecar_info`).
805        let refusal = if is_rsidecar_type(field) {
806            Some("the RSidecar selector, which has no R accessors".to_string())
807        } else if is_computed_type(&field.ty) {
808            Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a `{0}` field, which runs its `get` function on every read: the function may read more than the struct, so no borrow of the struct says when its value changes",
                COMPUTED_TYPE_NAME))
    })format!(
809                "a `{COMPUTED_TYPE_NAME}` field, which runs its `get` function on every read: the \
810                 function may read more than the struct, so no borrow of the struct says when its \
811                 value changes"
812            ))
813        } else if sidecar_inner_type(&field.ty).is_some() {
814            Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a `{0}<T>` field, whose getter returns the R value the pointer keeps, converting nothing",
                SIDECAR_TYPE_NAME))
    })format!(
815                "a `{SIDECAR_TYPE_NAME}<T>` field, whose getter returns the R value the pointer keeps, \
816                 converting nothing"
817            ))
818        } else if !is_pub(field) || field.ident.is_none() {
819            Some("a field that is not `pub`: only `pub` `#[r_data]` fields reach R".to_string())
820        } else {
821            None
822        };
823        if let Some(refusal) = refusal {
824            return Err(cache_refusal(span, &refusal));
825        }
826    }
827    if options.setter_invisible.is_some()
828        && (is_rsidecar_type(field)
829            || is_computed_type(&field.ty)
830            || !is_pub(field)
831            || field.ident.is_none())
832    {
833        return Err(syn::Error::new_spanned(
834            field,
835            "`setter` requires a public named sidecar slot with a setter, not the RSidecar \
836             selector or a `Computed` field",
837        ));
838    }
839    if let Some(span) = options.access_ref.or(options.access_mut)
840        && sidecar_inner_type(&field.ty).is_none()
841    {
842        return Err(syn::Error::new(
843            span,
844            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`ref` and `mut` in `#[r_data(...)]` apply to `{1}<T>` fields only; a plain `#[r_data]` field stays a struct field with its R accessors{0}",
                if is_computed_type(&field.ty) {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(", and a `{0}` field is read through its `get` function",
                                    COMPUTED_TYPE_NAME))
                        })
                } else { String::new() }, SIDECAR_TYPE_NAME))
    })format!(
845                "`ref` and `mut` in `#[r_data(...)]` apply to `{SIDECAR_TYPE_NAME}<T>` fields only; \
846                 a plain `#[r_data]` field stays a struct field with its R accessors{}",
847                if is_computed_type(&field.ty) {
848                    format!(
849                        ", and a `{COMPUTED_TYPE_NAME}` field is read through its `get` function"
850                    )
851                } else {
852                    String::new()
853                }
854            ),
855        ));
856    }
857    if let Some(name) = &options.name {
858        if is_rsidecar_type(field) {
859            return Err(syn::Error::new_spanned(
860                name,
861                "`name` applies to a sidecar slot, not the RSidecar selector, which has no R name",
862            ));
863        }
864        let value = name.value();
865        if value.is_empty() {
866            return Err(syn::Error::new_spanned(
867                name,
868                "an R field name can't be empty",
869            ));
870        }
871        if value == ".ptr" {
872            return Err(syn::Error::new_spanned(
873                name,
874                "`.ptr` is the element that carries the pointer in a list or environment receiver, \
875                 so it can't be an R field name",
876            ));
877        }
878        if !crate::naming::is_syntactic_r_name(&value) {
879            return Err(syn::Error::new_spanned(
880                name,
881                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is not a syntactic R name; an R field name has letters, digits, `.` and `_` only, starts with a letter or a `.` not followed by a digit, and is not a reserved word",
                value))
    })format!(
882                    "`{value}` is not a syntactic R name; an R field name has letters, digits, `.` and `_` \
883                     only, starts with a letter or a `.` not followed by a digit, and is not a reserved word"
884                ),
885            ));
886        }
887    }
888    match (&options.get, is_computed_type(&field.ty)) {
889        (Some(get), false) => {
890            return Err(syn::Error::new_spanned(
891                get,
892                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`get` applies to a `{0}` field only: declare the field as `pub <name>: {0}`, and `get` names the function that computes its value",
                COMPUTED_TYPE_NAME))
    })format!(
893                    "`get` applies to a `{COMPUTED_TYPE_NAME}` field only: declare the field as \
894                     `pub <name>: {COMPUTED_TYPE_NAME}`, and `get` names the function that computes its value"
895                ),
896            ));
897        }
898        (None, true) => {
899            return Err(syn::Error::new_spanned(
900                &field.ty,
901                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a `{0}` field needs `#[r_data(get = \"Self::f\")]`, the function `fn(&Self) -> impl IntoR` that computes its value",
                COMPUTED_TYPE_NAME))
    })format!(
902                    "a `{COMPUTED_TYPE_NAME}` field needs `#[r_data(get = \"Self::f\")]`, the function \
903                     `fn(&Self) -> impl IntoR` that computes its value"
904                ),
905            ));
906        }
907        _ => {}
908    }
909    Ok(options)
910}
911
912/// The refusal of `#[r_data(cache)]` on a field it doesn't apply to, at the
913/// option: `refusal` says what the field is.
914fn cache_refusal(span: Span, refusal: &str) -> syn::Error {
915    syn::Error::new(
916        span,
917        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`cache` keeps the R value a public `#[r_data]` struct field\'s getter converts, until the object is next borrowed exclusively; it doesn\'t apply to {0}",
                refusal))
    })format!(
918            "`cache` keeps the R value a public `#[r_data]` struct field's getter converts, until \
919             the object is next borrowed exclusively; it doesn't apply to {refusal}"
920        ),
921    )
922}
923
924/// Check if a field type is `RSidecar`.
925///
926/// Returns `true` if the last path segment of the field's type is `RSidecar`,
927/// which acts as the selector marker enabling R sidecar accessor generation.
928pub(crate) fn is_rsidecar_type(field: &Field) -> bool {
929    if let syn::Type::Path(type_path) = &field.ty {
930        type_path
931            .path
932            .segments
933            .last()
934            .map(|seg| seg.ident == "RSidecar")
935            .unwrap_or(false)
936    } else {
937        false
938    }
939}
940
941/// Check if a field is public.
942fn is_pub(field: &Field) -> bool {
943    #[allow(non_exhaustive_omitted_patterns)] match field.vis {
    Visibility::Public(_) => true,
    _ => false,
}matches!(field.vis, Visibility::Public(_))
944}
945
946/// The kind of sidecar slot, determining how getter/setter FFI functions are generated.
947///
948/// Each kind maps to a different codegen strategy for reading and writing the
949/// slot through R's `.Call` interface:
950/// - `Sidecar`: a value in the external pointer's protection list, validated
951///   with `TryFromSexp::<T>` on write and stored as R gave it.
952/// - Scalars: a struct field, read into R with `Rf_Scalar*`, written with `Rf_as*`.
953/// - Conversion: a struct field, converted with the `IntoR`/`TryFromSexp` traits.
954/// - Computed: no field; a getter function of the Rust value, no setter.
955#[derive(#[automatically_derived]impl ::core::fmt::Debug for SlotKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Sidecar(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Sidecar", &__self_0),
            Self::Computed(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Computed", &__self_0),
            Self::ScalarInt =>
                ::core::fmt::Formatter::write_str(f, "ScalarInt"),
            Self::ScalarReal =>
                ::core::fmt::Formatter::write_str(f, "ScalarReal"),
            Self::ScalarLogical =>
                ::core::fmt::Formatter::write_str(f, "ScalarLogical"),
            Self::ScalarRaw =>
                ::core::fmt::Formatter::write_str(f, "ScalarRaw"),
            Self::Conversion =>
                ::core::fmt::Formatter::write_str(f, "Conversion"),
        }
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for SlotKind {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Sidecar(__self_0) =>
                SlotKind::Sidecar(::core::clone::Clone::clone(__self_0)),
            Self::Computed(__self_0) =>
                SlotKind::Computed(::core::clone::Clone::clone(__self_0)),
            Self::ScalarInt => SlotKind::ScalarInt,
            Self::ScalarReal => SlotKind::ScalarReal,
            Self::ScalarLogical => SlotKind::ScalarLogical,
            Self::ScalarRaw => SlotKind::ScalarRaw,
            Self::Conversion => SlotKind::Conversion,
        }
    }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for SlotKind
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SlotKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Sidecar(__self_0), Self::Sidecar(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Computed(__self_0), Self::Computed(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for SlotKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<usize>;
        let _: ::core::cmp::AssertParamIsEq<syn::Path>;
    }
}Eq)]
956pub(crate) enum SlotKind {
957    /// `Sidecar<T>` field: the value at this position among the type's
958    /// `Sidecar` fields, kept in the external pointer's protection list
959    /// (getter returns it, setter validates `value` as a `T` and stores it
960    /// there).
961    Sidecar(usize),
962    /// `Computed` marker field: the getter calls this function, a
963    /// `fn(&Self) -> impl IntoR` (a leading `Self` already replaced by the
964    /// struct's name), on the live Rust value; there is no setter (#1883).
965    Computed(syn::Path),
966    /// Scalar struct field `i32` (or `i16`/`i8`), returned as a length-1 integer.
967    ScalarInt,
968    /// Scalar struct field `f64` (or `f32`), returned as a length-1 double.
969    ScalarReal,
970    /// Scalar struct field `bool` (or `Rbool`), returned as a length-1 logical.
971    ScalarLogical,
972    /// Scalar struct field `u8`, returned as a length-1 raw.
973    ScalarRaw,
974    /// Conversion type -- uses `IntoR`/`TryFromSexp` traits for arbitrary Rust types.
975    Conversion,
976}
977
978/// Information about a single `#[r_data]`-annotated sidecar slot field.
979///
980/// Collected during struct field parsing and used to generate FFI getter/setter
981/// functions and R wrapper code for each public slot.
982pub(crate) struct SidecarSlot {
983    /// Rust identifier of the field (e.g., `count`, `name`). The C symbols,
984    /// the `R_CallMethodDef` statics and the Rust accessors are named by it.
985    pub(crate) name: Ident,
986    /// The field's R name: `#[r_data(name = "...")]`, else the Rust
987    /// identifier (#1891). Every R-facing string uses it: `.rdata_fields_T`,
988    /// the `$` switch labels, the R6 binding / S7 property, the standalone
989    /// `T_get_<name>()` / `T_set_<name>()` and the setter's message. A
990    /// `Sidecar` field's save slot is named by it too (`SIDECAR_NAMES`, the
991    /// name the accessors and `__mx_visit_sidecars` pass, #2215).
992    pub(crate) r_name: String,
993    /// Rust type of the field, used in conversion-based getter/setter codegen.
994    ty: syn::Type,
995    /// The field's visibility, which its generated Rust accessors take.
996    vis: Visibility,
997    /// Whether the field is `pub`. Only public fields get R accessor functions.
998    is_public: bool,
999    /// Determines the codegen strategy for reading/writing this slot.
1000    pub(crate) kind: SlotKind,
1001    /// The Rust accessors of a `Sidecar<T>` field (`#[r_data(ref | mut)]`);
1002    /// unused by the other kinds.
1003    access: SidecarAccess,
1004    /// Optional documentation string for the S7 `@prop` tag.
1005    /// Sourced from `#[r_data(prop_doc = "...")]`. `None` means no doc was supplied;
1006    /// a default fallback string is used at emit time.
1007    prop_doc: Option<String>,
1008    /// Explicit setter visibility; each generated setter keeps its default when absent.
1009    setter_invisible: Option<bool>,
1010    /// `#[r_data(read_only)]` (#2268): R reads the field and can't write
1011    /// it. The Rust accessors of a `Sidecar<T>` field are unaffected.
1012    read_only: bool,
1013    /// `#[r_data(null_if_none)]` (#2270): the getter of this `Option<T>`
1014    /// `Conversion` field reads `NULL` for `None`.
1015    null_if_none: bool,
1016    /// `#[r_data(cache)]` (#2271): the position of this `Conversion` field
1017    /// among the type's cached fields, under which its getter keeps the R
1018    /// value its first read makes (`externalptr::sidecar_r_cached`).
1019    cache: Option<usize>,
1020}
1021
1022impl SidecarSlot {
1023    /// Whether R can write the field: a setter C function, `CallDef` and
1024    /// `Type_set_<f>()`, a writing arm in `.rdata_set_<Type>`, a writing R6
1025    /// binding and an S7 property setter. A `Computed` field (#1883) and an
1026    /// `#[r_data(read_only)]` one (#2268) have none.
1027    fn has_r_setter(&self) -> bool {
1028        !self.read_only && !#[allow(non_exhaustive_omitted_patterns)] match self.kind {
    SlotKind::Computed(_) => true,
    _ => false,
}matches!(self.kind, SlotKind::Computed(_))
1029    }
1030
1031    /// What the refusal of a write to a field without an R setter says of
1032    /// it, after "`f` of `Class`".
1033    fn read_only_reason(&self) -> &'static str {
1034        if #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    SlotKind::Computed(_) => true,
    _ => false,
}matches!(self.kind, SlotKind::Computed(_)) {
1035            COMPUTED_REASON
1036        } else {
1037            READ_ONLY_REASON
1038        }
1039    }
1040}
1041
1042/// The refusal of a write to a `Computed` field, after "`f` of `Class`".
1043const COMPUTED_REASON: &str = "is computed from the Rust value and can't be assigned";
1044
1045/// The refusal of a write to a read-only field, after "`f` of `Class`".
1046const READ_ONLY_REASON: &str = "is read-only";
1047
1048/// Aggregated sidecar information extracted from struct field analysis.
1049///
1050/// Contains everything needed to generate sidecar accessor code: the
1051/// selector presence, the list of typed slots, and the target class system.
1052pub(crate) struct SidecarInfo {
1053    /// Whether the struct contains an `RSidecar`-typed field marked with `#[r_data]`.
1054    /// At most one selector is allowed per struct.
1055    has_selector: bool,
1056    /// The `#[r_data]` slot fields (excluding the RSidecar selector itself),
1057    /// each carrying its index, kind, and visibility.
1058    pub(crate) slots: Vec<SidecarSlot>,
1059    /// The R class system chosen via `#[externalptr(...)]`, controlling the
1060    /// style of generated R wrapper code.
1061    class_system: ClassSystem,
1062}
1063
1064/// The getter path of a `Computed` field, `#[r_data(get = "Self::f")]`,
1065/// parsed from the literal; a leading `Self` becomes the struct's name, since
1066/// the getter is called from a free function the derive emits outside any
1067/// impl.
1068fn computed_getter_path(get: &syn::LitStr, struct_name: &Ident) -> syn::Result<syn::Path> {
1069    let mut path: syn::Path = get.parse().map_err(|err| {
1070        syn::Error::new_spanned(
1071            get,
1072            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`get` must be a path to the getter function, e.g. `Self::f`: {0}",
                err))
    })format!("`get` must be a path to the getter function, e.g. `Self::f`: {err}"),
1073        )
1074    })?;
1075    crate::util::resolve_self(&mut path, struct_name);
1076    Ok(path)
1077}
1078
1079/// R views stored in ordinary Rust fields have no GC owner. Inspect only
1080/// known views and containers: aliases and user-defined wrappers are opaque to
1081/// a derive, and a generic argument alone need not be stored (PhantomData).
1082fn contains_unrooted_r_view(ty: &syn::Type) -> bool {
1083    if crate::type_inspect::is_rooted_reference(ty) {
1084        return true;
1085    }
1086    match ty {
1087        syn::Type::Array(t) => contains_unrooted_r_view(&t.elem),
1088        syn::Type::Slice(t) => contains_unrooted_r_view(&t.elem),
1089        syn::Type::Tuple(t) => t.elems.iter().any(contains_unrooted_r_view),
1090        syn::Type::Reference(t) => contains_unrooted_r_view(&t.elem),
1091        syn::Type::Paren(t) => contains_unrooted_r_view(&t.elem),
1092        syn::Type::Group(t) => contains_unrooted_r_view(&t.elem),
1093        syn::Type::Path(t) if t.qself.is_none() => {
1094            let Some(segment) = t.path.segments.last() else {
1095                return false;
1096            };
1097            match segment.ident.to_string().as_str() {
1098                "SEXP" | "List" | "ListMut" | "NamedList" | "DataFrame" | "StrVec" | "RCow"
1099                | "RArray" | "RVector" | "RMatrix" | "RArray3D" | "Factor" | "FactorMut" => true,
1100                "Option" | "Nullable" | "Result" | "Vec" | "VecDeque" | "LinkedList"
1101                | "BinaryHeap" | "HashSet" | "BTreeSet" | "HashMap" | "BTreeMap" | "Box" | "Rc"
1102                | "Arc" | "Cow" | "Cell" | "RefCell" | "Mutex" | "RwLock" | "OnceCell"
1103                | "OnceLock" => {
1104                    let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
1105                        return false;
1106                    };
1107                    args.args.iter().any(|arg| {
1108                        #[allow(non_exhaustive_omitted_patterns)] match arg {
    syn::GenericArgument::Type(ty) if contains_unrooted_r_view(ty) => true,
    _ => false,
}matches!(arg, syn::GenericArgument::Type(ty) if contains_unrooted_r_view(ty))
1109                    })
1110                }
1111                _ => false,
1112            }
1113        }
1114        _ => false,
1115    }
1116}
1117
1118/// Determine the [`SlotKind`] for a field type by inspecting its last path segment.
1119///
1120/// Recognizes `Sidecar<T>`, which takes position `sidecars` (the number of
1121/// `Sidecar` fields before it), `Computed` with its `get` function, scalar
1122/// numerics (`i32`, `i16`, `i8`, `f64`, `f32`), booleans (`bool`, `Rbool`),
1123/// and raw bytes (`u8`). An R view, including one in a standard container,
1124/// is an error: the struct can't root it.
1125/// Everything else falls through to [`SlotKind::Conversion`].
1126fn slot_kind_for_type(
1127    ty: &syn::Type,
1128    sidecars: usize,
1129    get: Option<&syn::LitStr>,
1130    struct_name: &Ident,
1131) -> syn::Result<SlotKind> {
1132    if sidecar_inner_type(ty).is_some() {
1133        return Ok(SlotKind::Sidecar(sidecars));
1134    }
1135    if is_computed_type(ty) {
1136        // `parse_r_data_options` refused a `Computed` field without `get`.
1137        let get = get.expect("a Computed field has a `get` option");
1138        return Ok(SlotKind::Computed(computed_getter_path(get, struct_name)?));
1139    }
1140    if contains_unrooted_r_view(ty) {
1141        let field_type = crate::type_inspect::type_display(ty);
1142        return Err(syn::Error::new_spanned(
1143            ty,
1144            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a `{0}` sidecar field is not rooted: the GC frees its value once R drops its own references. Declare the field as `{1}<{0}>`, which keeps the value in the external pointer\'s protection list",
                field_type, SIDECAR_TYPE_NAME))
    })format!(
1145                "a `{field_type}` sidecar field is not rooted: the GC frees its value once R drops \
1146                 its own references. Declare the field as `{SIDECAR_TYPE_NAME}<{field_type}>`, which \
1147                 keeps the value in the external pointer's protection list"
1148            ),
1149        ));
1150    }
1151    if let syn::Type::Path(type_path) = ty
1152        && let Some(seg) = type_path.path.segments.last()
1153    {
1154        let ident = &seg.ident;
1155        if ident == SIDECAR_TYPE_NAME {
1156            return Err(syn::Error::new_spanned(
1157                ty,
1158                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` takes one type argument: `{0}<T>`",
                SIDECAR_TYPE_NAME))
    })format!("`{SIDECAR_TYPE_NAME}` takes one type argument: `{SIDECAR_TYPE_NAME}<T>`"),
1159            ));
1160        }
1161        if ident == "i32" || ident == "i16" || ident == "i8" {
1162            return Ok(SlotKind::ScalarInt);
1163        }
1164        if ident == "f64" || ident == "f32" {
1165            return Ok(SlotKind::ScalarReal);
1166        }
1167        if ident == "bool" || ident == "Rbool" {
1168            return Ok(SlotKind::ScalarLogical);
1169        }
1170        if ident == "u8" {
1171            return Ok(SlotKind::ScalarRaw);
1172        }
1173    }
1174    // Everything else uses conversion
1175    Ok(SlotKind::Conversion)
1176}
1177
1178/// Parse struct fields for sidecar information.
1179///
1180/// Iterates over all fields, identifying `#[r_data]` markers. Fields with
1181/// `RSidecar` type are tracked as selector markers (at most one allowed);
1182/// all other `#[r_data]` fields become [`SidecarSlot`] entries with their
1183/// slot kind inferred from the field type.
1184///
1185/// Returns `Err` if more than one `RSidecar` field is found.
1186pub(crate) fn parse_sidecar_info(
1187    input: &DeriveInput,
1188    class_system: ClassSystem,
1189) -> syn::Result<SidecarInfo> {
1190    let fields = match &input.data {
1191        syn::Data::Struct(data) => &data.fields,
1192        _ => {
1193            return Ok(SidecarInfo {
1194                has_selector: false,
1195                slots: ::alloc::vec::Vec::new()vec![],
1196                class_system,
1197            });
1198        }
1199    };
1200
1201    let mut selector_fields: Vec<&Field> = ::alloc::vec::Vec::new()vec![];
1202    let mut slots = ::alloc::vec::Vec::new()vec![];
1203    let mut sidecars = 0usize;
1204    let mut cached = 0usize;
1205
1206    for field in fields.iter() {
1207        if !has_r_data_attr(field) {
1208            if sidecar_inner_type(&field.ty).is_some() {
1209                return Err(syn::Error::new_spanned(
1210                    &field.ty,
1211                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a `{0}<T>` field needs `#[r_data]`, `#[r_data(ref)]`, `#[r_data(mut)]` or `#[r_data(ref, mut)]`: the derive attaches only the fields it knows to the external pointer",
                SIDECAR_TYPE_NAME))
    })format!(
1212                        "a `{SIDECAR_TYPE_NAME}<T>` field needs `#[r_data]`, `#[r_data(ref)]`, \
1213                         `#[r_data(mut)]` or `#[r_data(ref, mut)]`: the derive attaches only the \
1214                         fields it knows to the external pointer"
1215                    ),
1216                ));
1217            }
1218            continue;
1219        }
1220
1221        let options = parse_r_data_options(field)?;
1222        if is_rsidecar_type(field) {
1223            // RSidecar is the selector marker, not a slot
1224            selector_fields.push(field);
1225        } else if let Some(ref ident) = field.ident {
1226            // Any other type with #[r_data] becomes a slot
1227            let kind = slot_kind_for_type(&field.ty, sidecars, options.get.as_ref(), &input.ident)?;
1228            if #[allow(non_exhaustive_omitted_patterns)] match kind {
    SlotKind::Computed(_) => true,
    _ => false,
}matches!(kind, SlotKind::Computed(_)) {
1229                // Only a `pub` `#[r_data]` field reaches R, and a computed
1230                // field exists for R only.
1231                if !is_pub(field) {
1232                    return Err(syn::Error::new_spanned(
1233                        field,
1234                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a `{0}` field must be `pub`: it exists only as an R field, and only `pub` `#[r_data]` fields reach R",
                COMPUTED_TYPE_NAME))
    })format!(
1235                            "a `{COMPUTED_TYPE_NAME}` field must be `pub`: it exists only as an R field, \
1236                             and only `pub` `#[r_data]` fields reach R"
1237                        ),
1238                    ));
1239                }
1240            }
1241            let access = if #[allow(non_exhaustive_omitted_patterns)] match kind {
    SlotKind::Sidecar(_) => true,
    _ => false,
}matches!(kind, SlotKind::Sidecar(_)) {
1242                sidecars += 1;
1243                let (get, set) = (options.access_ref.is_some(), options.access_mut.is_some());
1244                // A bare `#[r_data]` on a `Sidecar` field means `ref, mut`.
1245                SidecarAccess {
1246                    get: get || !set,
1247                    set: set || !get,
1248                }
1249            } else {
1250                SidecarAccess::default()
1251            };
1252            // `parse_r_data_options` refused `cache` on every kind but a
1253            // scalar and a conversion field; a scalar reads in constant time.
1254            let cache = match (options.cache, &kind) {
1255                (None, _) => None,
1256                (Some(_), SlotKind::Conversion) => {
1257                    cached += 1;
1258                    Some(cached - 1)
1259                }
1260                (Some(span), _) => {
1261                    return Err(cache_refusal(
1262                        span,
1263                        &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a scalar `{0}` field, whose getter makes a length-1 vector, as fast as returning a kept one",
                crate::type_inspect::type_display(&field.ty)))
    })format!(
1264                            "a scalar `{}` field, whose getter makes a length-1 vector, as fast as \
1265                             returning a kept one",
1266                            crate::type_inspect::type_display(&field.ty)
1267                        ),
1268                    ));
1269                }
1270            };
1271            let r_name = options
1272                .name
1273                .as_ref()
1274                .map_or_else(|| crate::naming::ident_name(ident), syn::LitStr::value);
1275            slots.push(SidecarSlot {
1276                name: ident.clone(),
1277                r_name,
1278                ty: field.ty.clone(),
1279                vis: field.vis.clone(),
1280                is_public: is_pub(field),
1281                kind,
1282                access,
1283                prop_doc: options.prop_doc,
1284                setter_invisible: options.setter_invisible,
1285                read_only: options.read_only.is_some(),
1286                null_if_none: options.null_if_none.is_some(),
1287                cache,
1288            });
1289        }
1290    }
1291
1292    // Check for multiple selectors
1293    if selector_fields.len() > 1 {
1294        return Err(syn::Error::new_spanned(
1295            selector_fields[1],
1296            "only one RSidecar field is allowed per struct",
1297        ));
1298    }
1299
1300    // Two slots can't share an R name: a renamed field can't take another
1301    // field's name (the `$` switch and the standalone accessors would clash).
1302    for (i, slot) in slots.iter().enumerate() {
1303        if let Some(earlier) = slots[..i].iter().find(|other| other.r_name == slot.r_name) {
1304            return Err(syn::Error::new(
1305                slot.name.span(),
1306                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the R field name `{0}` is already taken by the field `{1}`; every `#[r_data]` field of a type needs its own R name (`#[r_data(name = \"...\")]` renames one)",
                slot.r_name, earlier.name))
    })format!(
1307                    "the R field name `{}` is already taken by the field `{}`; every `#[r_data]` field \
1308                     of a type needs its own R name (`#[r_data(name = \"...\")]` renames one)",
1309                    slot.r_name, earlier.name
1310                ),
1311            ));
1312        }
1313    }
1314
1315    Ok(SidecarInfo {
1316        has_selector: !selector_fields.is_empty(),
1317        slots,
1318        class_system,
1319    })
1320}
1321
1322/// Whether a slot's C accessors read the `require_live` flag: only a
1323/// `Sidecar` slot can serve a restored pointer, so only its accessors decide
1324/// by the flag; the other kinds need the live Rust value whatever it says.
1325fn uses_require_live(slot: &SidecarSlot) -> bool {
1326    #[allow(non_exhaustive_omitted_patterns)] match slot.kind {
    SlotKind::Sidecar(_) => true,
    _ => false,
}matches!(slot.kind, SlotKind::Sidecar(_))
1327}
1328
1329/// The `require_live` parameter of a slot's C accessors: named for the body
1330/// to read when the slot uses it, underscored otherwise.
1331fn require_live_param(slot: &SidecarSlot) -> Ident {
1332    if uses_require_live(slot) {
1333        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("require_live"))
            }), ::quote::__private::Option::None)quote::format_ident!("require_live")
1334    } else {
1335        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("_require_live"))
            }), ::quote::__private::Option::None)quote::format_ident!("_require_live")
1336    }
1337}
1338
1339/// Generate the token stream for a sidecar getter function body.
1340///
1341/// Reads the slot and returns it as an R SEXP. The strategy depends on the
1342/// slot kind:
1343/// - `Sidecar`: returns the value from the external pointer's protection list,
1344///   after flushing a live struct's pending value for the field. It needs no
1345///   live address, so without `require_live` it also reads a pointer that
1346///   `readRDS` brought back; with it (the field methods of
1347///   `r_data_accessors`, #1891) a restored pointer is refused.
1348/// - Scalar kinds: reads the struct field (accessed via the external pointer
1349///   address) and wraps it with `Rf_Scalar*`.
1350/// - `Conversion`: clones the struct field and converts it with `IntoR`;
1351///   under `#[r_data(null_if_none)]` the `Option<T>` converts as a
1352///   `Nullable<T>`, so `None` reads `NULL` (#2270). Under
1353///   `#[r_data(cache)]` the converted value is kept and returned by the
1354///   reads that follow until the value is borrowed exclusively
1355///   (`externalptr::sidecar_r_cached`, #2271).
1356/// - `Computed`: calls the `get` function on the live struct and converts
1357///   its value with `IntoR`; a `Result` is an error boundary (#2269).
1358///
1359/// A failed `IntoR` conversion raises the classed `result_err` condition
1360/// (`c_wrapper_builder::return_conversion`, #2272).
1361///
1362/// The body runs inside `with_r_unwind_protect` (see the emission site in
1363/// [`generate_sidecar_accessors`]). The receiver is the pointer or an object
1364/// carrying it in `.ptr`, as for an instance method; an argument carrying no
1365/// pointer, a null pointer address, or a wrong stored type panics with the
1366/// same `expected ExternalPtr<T>` message the main class-method path uses.
1367/// The panic is transported as a tagged condition and re-raised by the R
1368/// wrapper.
1369fn generate_getter_body(struct_name: &syn::Ident, slot: &SidecarSlot) -> TokenStream {
1370    let field_name = &slot.name;
1371
1372    // Helper: the live struct behind the pointer, borrowed shared for the
1373    // getter. `sidecar_r_struct` panics (caught by the surrounding
1374    // with_r_unwind_protect and raised as an R error) on a non-pointer, a
1375    // wrong type, or a pointer without an address (a restored object: the
1376    // classed errors) instead of silently returning R_NilValue, and while a
1377    // running method holds the struct mutably (`miniextendr_borrow_conflict`).
1378    let extract_ref = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__mx_data");
    ::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, "sidecar_r_struct");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_lt(&mut _s);
    ::quote::ToTokens::to_tokens(&struct_name, &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, "x");
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "data");
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::ToTokens::to_tokens(&struct_name, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::__private::push_ident(&mut _s, "__mx_data");
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
1379        let __mx_data = ::miniextendr_api::externalptr::sidecar_r_struct::<#struct_name>(x);
1380        let data: &#struct_name = &__mx_data;
1381    };
1382
1383    match &slot.kind {
1384        SlotKind::Sidecar(index) => {
1385            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::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, "sidecar_r_get");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_lt(&mut _s);
            ::quote::ToTokens::to_tokens(&struct_name, &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, "x");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&index, &mut _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, "externalptr");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "sidecar_require_live");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "require_live");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            _s
        });
    _s
}quote::quote! {
1386                unsafe {
1387                    ::miniextendr_api::externalptr::sidecar_r_get::<#struct_name>(
1388                        x,
1389                        #index,
1390                        ::miniextendr_api::externalptr::sidecar_require_live(require_live),
1391                    )
1392                }
1393            }
1394        }
1395        SlotKind::Computed(getter) => {
1396            // The getter's own conditions (`rust_error!(class = ...)`) are
1397            // panics the surrounding guard catches, so they reach R with
1398            // their classes. Naming the marker field is its only Rust use:
1399            // it keeps `dead_code` quiet and checks the field's type.
1400            //
1401            // A `Result` from the getter is an error boundary, as a
1402            // function's is (#2269). The derive sees only the getter's path,
1403            // so the autoref probe on `ComputedProbe` sorts its value:
1404            // `Result<T, ()>`'s `Err` reads `NULL`, another `Err` is the
1405            // `result_err` condition with the `Err` arm probe of functions
1406            // (`e` is the name `ErrPartsMode::expr` reads), anything else and
1407            // an `Ok` convert. The read and the conversion are spanned at the
1408            // `get` string, where a type without `IntoR` is reported.
1409            let span = syn::spanned::Spanned::span(getter);
1410            let read = {
    let mut _s = ::quote::__private::TokenStream::new();
    let _span: ::quote::__private::Span =
        ::quote::__private::get_span(span).__into_span();
    ::quote::__private::push_group_spanned(&mut _s, _span,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            let _span: ::quote::__private::Span =
                ::quote::__private::get_span(_span).__into_span();
            ::quote::__private::push_and_and_spanned(&mut _s, _span);
            ::quote::__private::push_and_spanned(&mut _s, _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,
                "externalptr");
            ::quote::__private::push_colon2_spanned(&mut _s, _span);
            ::quote::__private::push_ident_spanned(&mut _s, _span,
                "ComputedProbe");
            ::quote::__private::push_colon2_spanned(&mut _s, _span);
            ::quote::__private::push_ident_spanned(&mut _s, _span, "of");
            ::quote::__private::push_group_spanned(&mut _s, _span,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    let _span: ::quote::__private::Span =
                        ::quote::__private::get_span(_span).__into_span();
                    ::quote::__private::push_and_spanned(&mut _s, _span);
                    ::quote::__private::push_ident_spanned(&mut _s, _span,
                        "__mx_value");
                    _s
                });
            _s
        });
    ::quote::__private::push_dot_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span,
        "__mx_computed_read");
    ::quote::__private::push_group_spanned(&mut _s, _span,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            let _span: ::quote::__private::Span =
                ::quote::__private::get_span(_span).__into_span();
            ::quote::__private::push_ident_spanned(&mut _s, _span,
                "__mx_value");
            _s
        });
    _s
}quote::quote_spanned! {span=>
1411                (&&&::miniextendr_api::externalptr::ComputedProbe::of(&__mx_value))
1412                    .__mx_computed_read(__mx_value)
1413            };
1414            let none = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "None");
    _s
}quote::quote!(::core::option::Option::None);
1415            let value = crate::c_wrapper_builder::return_conversion_at(
1416                &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "__mx_ok");
    _s
}quote::quote!(__mx_ok),
1417                &none,
1418                span,
1419            );
1420            let err_parts = crate::c_wrapper_builder::ErrPartsMode::from_spec(None).expr();
1421            {
    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, "unused_imports");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "use");
    ::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_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "ComputedReadNull");
            ::quote::__private::push_ident(&mut _s, "as");
            ::quote::__private::push_underscore(&mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "ComputedReadResult");
            ::quote::__private::push_ident(&mut _s, "as");
            ::quote::__private::push_underscore(&mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "ComputedReadValue");
            ::quote::__private::push_ident(&mut _s, "as");
            ::quote::__private::push_underscore(&mut _s);
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&extract_ref, &mut _s);
            ::quote::__private::push_ident(&mut _s, "let");
            ::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, "Computed");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_ident(&mut _s, "data");
            ::quote::__private::push_dot(&mut _s);
            ::quote::ToTokens::to_tokens(&field_name, &mut _s);
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s, "__mx_value");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&getter, &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, "data");
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "match");
            ::quote::ToTokens::to_tokens(&read, &mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "externalptr");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "ComputedRead");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "Value");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "__mx_ok");
                            _s
                        });
                    ::quote::__private::push_fat_arrow(&mut _s);
                    ::quote::ToTokens::to_tokens(&value, &mut _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, "externalptr");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "ComputedRead");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "Null");
                    ::quote::__private::push_fat_arrow(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "SEXP");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "nil");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                ::quote::__private::TokenStream::new());
                            _s
                        });
                    ::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, "ComputedRead");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "Err");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "e");
                            _s
                        });
                    ::quote::__private::push_fat_arrow(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "error_value");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s,
                                "result_err_condition_value");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::ToTokens::to_tokens(&err_parts, &mut _s);
                                    ::quote::__private::push_comma(&mut _s);
                                    ::quote::ToTokens::to_tokens(&none, &mut _s);
                                    ::quote::__private::push_comma(&mut _s);
                                    _s
                                });
                            _s
                        });
                    _s
                });
            _s
        });
    _s
}quote::quote! {
1422                #[allow(unused_imports)]
1423                use ::miniextendr_api::externalptr::{
1424                    ComputedReadNull as _, ComputedReadResult as _, ComputedReadValue as _,
1425                };
1426                unsafe {
1427                    #extract_ref
1428                    let ::miniextendr_api::externalptr::Computed = data.#field_name;
1429                    let __mx_value = #getter(data);
1430                    match #read {
1431                        ::miniextendr_api::externalptr::ComputedRead::Value(__mx_ok) => #value,
1432                        ::miniextendr_api::externalptr::ComputedRead::Null => {
1433                            ::miniextendr_api::SEXP::nil()
1434                        }
1435                        ::miniextendr_api::externalptr::ComputedRead::Err(e) => {
1436                            ::miniextendr_api::error_value::result_err_condition_value(
1437                                #err_parts, #none,
1438                            )
1439                        }
1440                    }
1441                }
1442            }
1443        }
1444        SlotKind::ScalarInt => {
1445            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "use");
    ::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_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&extract_ref, &mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "scalar_integer");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "data");
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::ToTokens::to_tokens(&field_name, &mut _s);
                    _s
                });
            _s
        });
    _s
}quote::quote! {
1446                use ::miniextendr_api::SEXP;
1447                unsafe {
1448                    #extract_ref
1449                    SEXP::scalar_integer(data.#field_name)
1450                }
1451            }
1452        }
1453        SlotKind::ScalarReal => {
1454            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "use");
    ::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_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&extract_ref, &mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "scalar_real");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "data");
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::ToTokens::to_tokens(&field_name, &mut _s);
                    _s
                });
            _s
        });
    _s
}quote::quote! {
1455                use ::miniextendr_api::SEXP;
1456                unsafe {
1457                    #extract_ref
1458                    SEXP::scalar_real(data.#field_name)
1459                }
1460            }
1461        }
1462        SlotKind::ScalarLogical => {
1463            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "use");
    ::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_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&extract_ref, &mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "scalar_logical");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "data");
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::ToTokens::to_tokens(&field_name, &mut _s);
                    _s
                });
            _s
        });
    _s
}quote::quote! {
1464                use ::miniextendr_api::SEXP;
1465                unsafe {
1466                    #extract_ref
1467                    SEXP::scalar_logical(data.#field_name)
1468                }
1469            }
1470        }
1471        SlotKind::ScalarRaw => {
1472            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "use");
    ::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_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&extract_ref, &mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "scalar_raw");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "data");
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::ToTokens::to_tokens(&field_name, &mut _s);
                    _s
                });
            _s
        });
    _s
}quote::quote! {
1473                use ::miniextendr_api::SEXP;
1474                unsafe {
1475                    #extract_ref
1476                    SEXP::scalar_raw(data.#field_name)
1477                }
1478            }
1479        }
1480        SlotKind::Conversion => {
1481            // Use IntoR trait for conversion (e.g., String -> character). The
1482            // getter reads the field through a shared borrow, so converting it
1483            // needs a clone; spanned at the field type, so a type without
1484            // `Clone` is reported at the field.
1485            let ty = &slot.ty;
1486            let span = syn::spanned::Spanned::span(ty);
1487            let clone = {
    let mut _s = ::quote::__private::TokenStream::new();
    let _span: ::quote::__private::Span =
        ::quote::__private::get_span(span).__into_span();
    ::quote::__private::push_lt_spanned(&mut _s, _span);
    ::quote::ToTokens::to_tokens(&ty, &mut _s);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "as");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "core");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "clone");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "Clone");
    ::quote::__private::push_gt_spanned(&mut _s, _span);
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "clone");
    _s
}quote::quote_spanned! {span=> <#ty as ::core::clone::Clone>::clone };
1488            let value = crate::c_wrapper_builder::return_conversion(
1489                &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "val");
    _s
}quote::quote!(val),
1490                &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "None");
    _s
}quote::quote!(::core::option::Option::None),
1491            );
1492            // `null_if_none` (#2270): the `Option<T>` converts as a
1493            // `Nullable<T>`, whose `None` is `NULL` whatever `T` is.
1494            let nullable = slot
1495                .null_if_none
1496                .then(|| {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "val");
    ::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, "Nullable");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "val");
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! { let val = ::miniextendr_api::Nullable(val); });
1497            match slot.cache {
1498                None => {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&extract_ref, &mut _s);
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s, "val");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&ty, &mut _s);
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&clone, &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, "data");
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::ToTokens::to_tokens(&field_name, &mut _s);
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::ToTokens::to_tokens(&nullable, &mut _s);
            ::quote::ToTokens::to_tokens(&value, &mut _s);
            _s
        });
    _s
}quote::quote! {
1499                    unsafe {
1500                        #extract_ref
1501                        let val: #ty = #clone(&data.#field_name);
1502                        #nullable
1503                        #value
1504                    }
1505                },
1506                // `cache` (#2271): the converted value is kept for the next
1507                // reads, until the value is borrowed exclusively; a failed
1508                // conversion's condition is returned and not kept.
1509                Some(index) => {
1510                    let value = crate::c_wrapper_builder::return_conversion_result(
1511                        &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "val");
    _s
}quote::quote!(val),
1512                        &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "None");
    _s
}quote::quote!(::core::option::Option::None),
1513                    );
1514                    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::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, "sidecar_r_cached");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_lt(&mut _s);
            ::quote::ToTokens::to_tokens(&struct_name, &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, "x");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&index, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_or(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "data");
                    ::quote::__private::push_colon(&mut _s);
                    ::quote::__private::push_and(&mut _s);
                    ::quote::ToTokens::to_tokens(&struct_name, &mut _s);
                    ::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_ident(&mut _s, "let");
                            ::quote::__private::push_ident(&mut _s, "val");
                            ::quote::__private::push_colon(&mut _s);
                            ::quote::ToTokens::to_tokens(&ty, &mut _s);
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::ToTokens::to_tokens(&clone, &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, "data");
                                    ::quote::__private::push_dot(&mut _s);
                                    ::quote::ToTokens::to_tokens(&field_name, &mut _s);
                                    _s
                                });
                            ::quote::__private::push_semi(&mut _s);
                            ::quote::ToTokens::to_tokens(&nullable, &mut _s);
                            ::quote::ToTokens::to_tokens(&value, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            _s
        });
    _s
}quote::quote! {
1515                        unsafe {
1516                            ::miniextendr_api::externalptr::sidecar_r_cached::<#struct_name>(
1517                                x,
1518                                #index,
1519                                |data: &#struct_name| {
1520                                    let val: #ty = #clone(&data.#field_name);
1521                                    #nullable
1522                                    #value
1523                                },
1524                            )
1525                        }
1526                    }
1527                }
1528            }
1529        }
1530    }
1531}
1532
1533/// Generate the token stream for a sidecar setter function body.
1534///
1535/// Stores the incoming R SEXP `value` in the slot. The strategy depends on the
1536/// slot kind:
1537/// - `Sidecar`: validates `value` with `TryFromSexp::<T>` (a failure raises
1538///   the conversion error) and stores it in the external pointer's protection
1539///   list, which roots it; a live struct's pending value for the field is
1540///   dropped.
1541/// - Scalar kinds: writes the struct field, using `Rf_as*` or coercion for
1542///   single-element extraction;
1543///   an input that doesn't reduce to a single non-NA scalar raises a
1544///   conversion error instead of silently storing an NA/`false` sentinel.
1545/// - `Conversion`: uses `TryFromSexp::try_from_sexp`; a failed conversion
1546///   raises a conversion error instead of silently dropping the write.
1547///
1548/// Returns the external pointer `x` (for R's invisible return convention).
1549/// The body runs inside `with_r_unwind_protect` (see the emission site in
1550/// [`generate_sidecar_accessors`]); a bad receiver panics with the main-path
1551/// `expected ExternalPtr<T>` message and conversion failures return a tagged
1552/// condition SEXP with kind `conversion` — both are re-raised by the R
1553/// wrapper. Sidecar accessors have no `__miniextendr_call` slot (#344/#348),
1554/// so the tagged conditions carry null call attribution.
1555///
1556/// A `Computed` slot has no setter: the result is empty, and the caller
1557/// emits none.
1558fn generate_setter_body(struct_name: &syn::Ident, slot: &SidecarSlot) -> TokenStream {
1559    let field_name = &slot.name;
1560
1561    // Helper: the live struct behind the pointer, borrowed exclusively for
1562    // the setter. Failure modes panic like the getter's
1563    // (`sidecar_r_struct_mut`) instead of silently no-op'ing, and a running
1564    // method holding the struct makes it raise `miniextendr_borrow_conflict`.
1565    let extract_mut = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "mut");
    ::quote::__private::push_ident(&mut _s, "__mx_data");
    ::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, "sidecar_r_struct_mut");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_lt(&mut _s);
    ::quote::ToTokens::to_tokens(&struct_name, &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, "x");
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "data");
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::__private::push_ident(&mut _s, "mut");
    ::quote::ToTokens::to_tokens(&struct_name, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::__private::push_ident(&mut _s, "mut");
    ::quote::__private::push_ident(&mut _s, "__mx_data");
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
1566        let mut __mx_data =
1567            ::miniextendr_api::externalptr::sidecar_r_struct_mut::<#struct_name>(x);
1568        let data: &mut #struct_name = &mut __mx_data;
1569    };
1570
1571    // Conversion-failure condition, the argument error of #1594 on the
1572    // setter's `value` formal: `'<field>' must be <expected>: <reason>` with
1573    // the field's R-facing expectation. The message names the field, which is
1574    // what an R6 active binding (`obj$count <- x`) or an S7 property
1575    // (`obj@count <- x`) user assigned to: their condition call is the
1576    // binding's anonymous function. `e$param == "value"` (the formal), the
1577    // field's Rust type is `e$rust_type`, and the crate's
1578    // `conversion_error_class` applies. A `Conversion` slot's expectation comes
1579    // from the same type table as an argument's, else from the error at run
1580    // time, else `invalid '<field>' argument`
1581    // (`rust_conversion_builder::conversion_value_tokens`); a scalar
1582    // slot reads its value with `Rf_as*`, which has no error value, so the
1583    // reason is worded from the rejected value (`from_r::scalar_rejection_reason`).
1584    let crate_class = crate::crate_config::conversion_error_class();
1585    // A `Sidecar<T>` slot converts and reports its `T`.
1586    let value_ty = sidecar_inner_type(&slot.ty).unwrap_or(&slot.ty);
1587    let rust_type = crate::type_inspect::type_display(value_ty);
1588    // The message names the field as R knows it.
1589    let field_r_name = slot.r_name.clone();
1590    let scalar_err = |expected: &str| -> proc_macro2::TokenStream {
1591        let prefix = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}\' must be {1}", field_r_name,
                expected))
    })format!("'{field_r_name}' must be {expected}");
1592        {
    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, "error_value");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "conversion_condition_value");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&prefix, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::parse(&mut _s, "\"value\"");
            ::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, "Some");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::ToTokens::to_tokens(&rust_type, &mut _s);
                    _s
                });
            ::quote::__private::push_comma(&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 crate_class, i) = crate_class.quote_into_iter();
                        let has_iter = has_iter | i;
                        <_ as
                                ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                        while true {
                            let crate_class =
                                match crate_class.next() {
                                    Some(_x) => ::quote::__private::RepInterp(_x),
                                    None => break,
                                };
                            if !_first { ::quote::__private::push_comma(&mut _s); }
                            _first = false;
                            ::quote::ToTokens::to_tokens(&crate_class, &mut _s);
                        }
                    }
                    _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,
                "__mx_conversion_err_parts");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "from_r");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "scalar_rejection_reason");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "value");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "true");
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "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_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_comma(&mut _s);
            _s
        });
    _s
}quote::quote! {
1593            ::miniextendr_api::error_value::conversion_condition_value(
1594                #prefix,
1595                "value",
1596                ::core::option::Option::Some(#rust_type),
1597                &[#(#crate_class),*],
1598                ::miniextendr_api::__mx_conversion_err_parts!(
1599                    ::miniextendr_api::from_r::scalar_rejection_reason(value),
1600                    true
1601                ),
1602                ::core::option::Option::None,
1603                ::core::option::Option::None,
1604            )
1605        }
1606    };
1607
1608    // Conversion-failure value of a `Conversion` or `Sidecar` slot: the field
1609    // type's expectation, else the one the type declares or the error knows at
1610    // run time (a newtype, a `match_arg` enum field), as for an argument. A
1611    // `Nullable<T>` reads as `Option<T>` does, so it is described as one
1612    // (`'f' must be NULL or ...`, #2270, #2294).
1613    let conversion_err = |ty: &syn::Type| -> proc_macro2::TokenStream {
1614        let prefix = crate::r_preconditions::conversion_expectation(ty, false)
1615            .map(|expected| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}\' must be {1}", field_r_name,
                expected))
    })format!("'{field_r_name}' must be {expected}"));
1616        let declared = crate::rust_conversion_builder::declared_expectation(ty);
1617        crate::rust_conversion_builder::conversion_value_tokens(
1618            &crate::rust_conversion_builder::ConversionSubject {
1619                expected: prefix.as_deref().map_or(
1620                    crate::rust_conversion_builder::Expected::FromError(Some(&declared)),
1621                    crate::rust_conversion_builder::Expected::Literal,
1622                ),
1623                quoted: &field_r_name,
1624                param: "value",
1625                nullable: crate::type_inspect::is_optional_type(ty),
1626                rust_type: &rust_type,
1627            },
1628            &crate::rust_conversion_builder::class_slice(&crate_class),
1629            &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "None");
    _s
}quote::quote!(::core::option::Option::None),
1630            syn::spanned::Spanned::span(ty),
1631        )
1632    };
1633
1634    match &slot.kind {
1635        SlotKind::Computed(_) => TokenStream::new(),
1636        SlotKind::Sidecar(index) => {
1637            let err_value = conversion_err(value_ty);
1638            // The receiver is checked before the value, so a wrong pointer is
1639            // reported as such whatever the value.
1640            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "use");
    ::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, "TryFromSexp");
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s, "require_live");
            ::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, "sidecar_require_live");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "require_live");
                    _s
                });
            ::quote::__private::push_semi(&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, "sidecar_r_check");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_lt(&mut _s);
            ::quote::ToTokens::to_tokens(&struct_name, &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, "x");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "require_live");
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "if");
            ::quote::__private::push_ident(&mut _s, "let");
            ::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_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Err");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "e");
                    _s
                });
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_lt(&mut _s);
            ::quote::ToTokens::to_tokens(&value_ty, &mut _s);
            ::quote::__private::push_ident(&mut _s, "as");
            ::quote::__private::push_ident(&mut _s, "TryFromSexp");
            ::quote::__private::push_gt(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "try_from_sexp");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "value");
                    _s
                });
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "return");
                    ::quote::ToTokens::to_tokens(&err_value, &mut _s);
                    ::quote::__private::push_semi(&mut _s);
                    _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, "sidecar_r_set");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_lt(&mut _s);
            ::quote::ToTokens::to_tokens(&struct_name, &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, "x");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&index, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "value");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "require_live");
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "x");
            _s
        });
    _s
}quote::quote! {
1641                use ::miniextendr_api::TryFromSexp;
1642                unsafe {
1643                    let require_live =
1644                        ::miniextendr_api::externalptr::sidecar_require_live(require_live);
1645                    ::miniextendr_api::externalptr::sidecar_r_check::<#struct_name>(x, require_live);
1646                    if let ::core::result::Result::Err(e) = <#value_ty as TryFromSexp>::try_from_sexp(value) {
1647                        return #err_value;
1648                    }
1649                    ::miniextendr_api::externalptr::sidecar_r_set::<#struct_name>(
1650                        x, #index, value, require_live,
1651                    );
1652                    x
1653                }
1654            }
1655        }
1656        SlotKind::ScalarInt => {
1657            let err_value = scalar_err("a number");
1658            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "use");
    ::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, "SexpExt");
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&extract_mut, &mut _s);
            ::quote::__private::push_ident(&mut _s, "data");
            ::quote::__private::push_dot(&mut _s);
            ::quote::ToTokens::to_tokens(&field_name, &mut _s);
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_ident(&mut _s, "match");
            ::quote::__private::push_ident(&mut _s, "value");
            ::quote::__private::push_dot(&mut _s);
            ::quote::__private::push_ident(&mut _s, "as_integer");
            ::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_ident(&mut _s, "return");
                    ::quote::ToTokens::to_tokens(&err_value, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "x");
            _s
        });
    _s
}quote::quote! {
1659                use ::miniextendr_api::SexpExt;
1660                unsafe {
1661                    #extract_mut
1662                    data.#field_name = match value.as_integer() {
1663                        ::core::option::Option::Some(v) => v,
1664                        ::core::option::Option::None => return #err_value,
1665                    };
1666                    x
1667                }
1668            }
1669        }
1670        SlotKind::ScalarReal => {
1671            let err_value = scalar_err("a number");
1672            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "use");
    ::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, "SexpExt");
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&extract_mut, &mut _s);
            ::quote::__private::push_ident(&mut _s, "data");
            ::quote::__private::push_dot(&mut _s);
            ::quote::ToTokens::to_tokens(&field_name, &mut _s);
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_ident(&mut _s, "match");
            ::quote::__private::push_ident(&mut _s, "value");
            ::quote::__private::push_dot(&mut _s);
            ::quote::__private::push_ident(&mut _s, "as_real");
            ::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_ident(&mut _s, "return");
                    ::quote::ToTokens::to_tokens(&err_value, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "x");
            _s
        });
    _s
}quote::quote! {
1673                use ::miniextendr_api::SexpExt;
1674                unsafe {
1675                    #extract_mut
1676                    data.#field_name = match value.as_real() {
1677                        ::core::option::Option::Some(v) => v,
1678                        ::core::option::Option::None => return #err_value,
1679                    };
1680                    x
1681                }
1682            }
1683        }
1684        SlotKind::ScalarLogical => {
1685            let err_value = scalar_err("TRUE or FALSE");
1686            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "use");
    ::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, "SexpExt");
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&extract_mut, &mut _s);
            ::quote::__private::push_ident(&mut _s, "data");
            ::quote::__private::push_dot(&mut _s);
            ::quote::ToTokens::to_tokens(&field_name, &mut _s);
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_ident(&mut _s, "match");
            ::quote::__private::push_ident(&mut _s, "value");
            ::quote::__private::push_dot(&mut _s);
            ::quote::__private::push_ident(&mut _s, "as_logical");
            ::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_ident(&mut _s, "return");
                    ::quote::ToTokens::to_tokens(&err_value, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "x");
            _s
        });
    _s
}quote::quote! {
1687                use ::miniextendr_api::SexpExt;
1688                unsafe {
1689                    #extract_mut
1690                    data.#field_name = match value.as_logical() {
1691                        ::core::option::Option::Some(v) => v,
1692                        ::core::option::Option::None => return #err_value,
1693                    };
1694                    x
1695                }
1696            }
1697        }
1698        SlotKind::ScalarRaw => {
1699            let err_value = scalar_err("a raw value");
1700            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "use");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&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, "SexpExt");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXPTYPE");
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&extract_mut, &mut _s);
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s, "raw_vec");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_ident(&mut _s, "value");
            ::quote::__private::push_dot(&mut _s);
            ::quote::__private::push_ident(&mut _s, "coerce");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "SEXPTYPE");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "RAWSXP");
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "if");
            ::quote::__private::push_ident(&mut _s, "raw_vec");
            ::quote::__private::push_dot(&mut _s);
            ::quote::__private::push_ident(&mut _s, "len");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_eq_eq(&mut _s);
            ::quote::__private::parse(&mut _s, "0");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "return");
                    ::quote::ToTokens::to_tokens(&err_value, &mut _s);
                    ::quote::__private::push_semi(&mut _s);
                    _s
                });
            ::quote::__private::push_ident(&mut _s, "data");
            ::quote::__private::push_dot(&mut _s);
            ::quote::ToTokens::to_tokens(&field_name, &mut _s);
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_ident(&mut _s, "raw_vec");
            ::quote::__private::push_dot(&mut _s);
            ::quote::__private::push_ident(&mut _s, "raw_elt");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s, "0");
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "x");
            _s
        });
    _s
}quote::quote! {
1701                use ::miniextendr_api::{SexpExt, SEXPTYPE};
1702                unsafe {
1703                    #extract_mut
1704                    let raw_vec = value.coerce(SEXPTYPE::RAWSXP);
1705                    if raw_vec.len() == 0 {
1706                        return #err_value;
1707                    }
1708                    data.#field_name = raw_vec.raw_elt(0);
1709                    x
1710                }
1711            }
1712        }
1713        SlotKind::Conversion => {
1714            let ty = &slot.ty;
1715            let err_value = conversion_err(ty);
1716            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "use");
    ::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, "TryFromSexp");
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&extract_mut, &mut _s);
            ::quote::__private::push_ident(&mut _s, "data");
            ::quote::__private::push_dot(&mut _s);
            ::quote::ToTokens::to_tokens(&field_name, &mut _s);
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_ident(&mut _s, "match");
            ::quote::__private::push_lt(&mut _s);
            ::quote::ToTokens::to_tokens(&ty, &mut _s);
            ::quote::__private::push_ident(&mut _s, "as");
            ::quote::__private::push_ident(&mut _s, "TryFromSexp");
            ::quote::__private::push_gt(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "try_from_sexp");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "value");
                    _s
                });
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "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_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "Ok");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "val");
                            _s
                        });
                    ::quote::__private::push_fat_arrow(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "val");
                    ::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, "result");
                    ::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, "Err");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "e");
                            _s
                        });
                    ::quote::__private::push_fat_arrow(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "return");
                    ::quote::ToTokens::to_tokens(&err_value, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "x");
            _s
        });
    _s
}quote::quote! {
1717                use ::miniextendr_api::TryFromSexp;
1718                unsafe {
1719                    #extract_mut
1720                    data.#field_name = match <#ty as TryFromSexp>::try_from_sexp(value) {
1721                        ::core::result::Result::Ok(val) => val,
1722                        ::core::result::Result::Err(e) => return #err_value,
1723                    };
1724                    x
1725                }
1726            }
1727        }
1728    }
1729}
1730
1731/// Generate R wrapper code (roxygen-annotated R functions) for a single sidecar slot.
1732///
1733/// Produces getter and setter R functions that call the corresponding C entry
1734/// points via `.Call`. The generated R code includes roxygen tags (`@rdname`,
1735/// `@param`, `@return`, `@export`) for documentation.
1736///
1737/// All class systems generate the same standalone function pattern
1738/// (`Type_get_field` / `Type_set_field`); only the roxygen title suffix
1739/// differs. Class-specific integration (e.g., R6 active bindings, S7
1740/// properties) is handled separately by [`generate_class_integration_r_code`].
1741///
1742/// Each wrapper body carries the shared tagged-condition guard
1743/// ([`crate::method_return_builder::standalone_body`]) so Rust-origin
1744/// panics/conversion failures are re-raised as structured R conditions.
1745/// Note the sidecar C functions have **no** `.call` slot — the `.Call()`
1746/// passes no `.call` argument (#344/#348); `sys.call()` inside the guard
1747/// supplies fallback attribution instead. The last `.Call()` argument is the
1748/// `require_live` flag: `FALSE` here, so the standalone accessors keep
1749/// reading a save's `Sidecar` values (#1891).
1750///
1751/// `field_name` is the field's R name (`Type_get_<name>()`). A field without
1752/// an R setter (`setter_c_name` is `None`: a `Computed` or
1753/// `#[r_data(read_only)]` one) gets the getter only.
1754///
1755/// `exported` writes them on the type's page with `@export`; otherwise they
1756/// are internal (`@noRd`, no export), the rendering a type whose class has
1757/// `$` / `[[` field syntax gets (#1900).
1758fn generate_r_wrapper_for_slot(
1759    class_system: ClassSystem,
1760    type_name: &str,
1761    field_name: &str,
1762    getter_c_name: &str,
1763    setter_c_name: Option<&str>,
1764    setter_invisible: bool,
1765    exported: bool,
1766) -> String {
1767    // Only the roxygen title suffix differs between class systems.
1768    let suffix = match class_system {
1769        ClassSystem::Env => "",
1770        ClassSystem::R6 => " (for R6)",
1771        ClassSystem::S3 => " (for S3)",
1772        ClassSystem::S4 => " (for S4)",
1773        ClassSystem::S7 => " (for S7)",
1774        ClassSystem::Vctrs => " (for vctrs)",
1775    };
1776    let r_getter_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}_get_{1}", type_name,
                field_name))
    })format!("{}_get_{}", type_name, field_name);
1777    let getter_body = crate::method_return_builder::standalone_body(
1778        &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".Call({0}, x, FALSE)",
                getter_c_name))
    })format!(".Call({getter_c_name}, x, FALSE)"),
1779        ".val",
1780        "  ",
1781    );
1782    let getter_tags = if exported {
1783        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {0}\n#\' @param x The {0} external pointer\n#\' @return The value of the `{1}` field\n#\' @export",
                type_name, field_name))
    })format!(
1784            "#' @rdname {type_name}\n#' @param x The {type_name} external pointer\n\
1785             #' @return The value of the `{field_name}` field\n#' @export"
1786        )
1787    } else {
1788        "#' @noRd".to_string()
1789    };
1790    let mut out = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n#\' Get `{1}` field from {0}{2}\n{5}\n{3} <- function(x) {{\n  {4}\n}}\n",
                type_name, field_name, suffix, r_getter_name, getter_body,
                getter_tags))
    })format!(
1791        r#"
1792#' Get `{field}` field from {type}{suffix}
1793{getter_tags}
1794{r_getter} <- function(x) {{
1795  {getter_body}
1796}}
1797"#,
1798        type = type_name,
1799        field = field_name,
1800        suffix = suffix,
1801        r_getter = r_getter_name,
1802        getter_body = getter_body,
1803    );
1804    let Some(setter_c_name) = setter_c_name else {
1805        return out;
1806    };
1807    let r_setter_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}_set_{1}", type_name,
                field_name))
    })format!("{}_set_{}", type_name, field_name);
1808    let setter_body = crate::method_return_builder::standalone_body(
1809        &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".Call({0}, x, value, FALSE)",
                setter_c_name))
    })format!(".Call({setter_c_name}, x, value, FALSE)"),
1810        if setter_invisible {
1811            "invisible(x)"
1812        } else {
1813            "x"
1814        },
1815        "  ",
1816    );
1817    let setter_tags = if exported {
1818        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {1}\n#\' @param x The {1} external pointer\n#\' @param value The new value to set\n#\' @return The {1} pointer ({0})\n#\' @export",
                if setter_invisible { "invisibly" } else { "visibly" },
                type_name))
    })format!(
1819            "#' @rdname {type_name}\n#' @param x The {type_name} external pointer\n\
1820             #' @param value The new value to set\n#' @return The {type_name} pointer ({visibility})\n\
1821             #' @export",
1822            visibility = if setter_invisible {
1823                "invisibly"
1824            } else {
1825                "visibly"
1826            },
1827        )
1828    } else {
1829        "#' @noRd".to_string()
1830    };
1831    out.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n#\' Set `{1}` field on {0}{2}\n{5}\n{3} <- function(x, value) {{\n  {4}\n}}\n",
                type_name, field_name, suffix, r_setter_name, setter_body,
                setter_tags))
    })format!(
1832        r#"
1833#' Set `{field}` field on {type}{suffix}
1834{setter_tags}
1835{r_setter} <- function(x, value) {{
1836  {setter_body}
1837}}
1838"#,
1839        type = type_name,
1840        field = field_name,
1841        suffix = suffix,
1842        r_setter = r_setter_name,
1843        setter_body = setter_body,
1844    ));
1845    out
1846}
1847
1848/// Generate class-integrated R code for sidecar fields.
1849///
1850/// For R6: generates `Type$set("active", "field", ...)` calls that add active bindings
1851/// referencing the sidecar getter/setter .Call entrypoints. The binding of a
1852/// field without an R setter (a `Computed` or `#[r_data(read_only)]` one)
1853/// refuses a value, as R6's own read-only active bindings do (#1888, #2268):
1854/// see [`r6_read_only_refusal`].
1855///
1856/// For S7: generates `.rdata_properties_Type <- list(...)` with S7::new_property()
1857/// definitions that can be spliced into the S7 class's properties list. A
1858/// field without an R setter is a property without a setter, which S7 itself
1859/// refuses to assign (#1888, #2268).
1860///
1861/// Other class systems return empty strings (their standalone accessors suffice).
1862fn generate_class_integration_r_code(
1863    class_system: ClassSystem,
1864    type_name: &str,
1865    pub_slots: &[&SidecarSlot],
1866    field_error: &FieldErrorOptions,
1867) -> String {
1868    if pub_slots.is_empty() {
1869        return String::new();
1870    }
1871
1872    // Shared tagged-condition guard (one line); `sys.call()` supplies fallback
1873    // attribution because the sidecar C functions carry no `.call` slot
1874    // (#344/#348 — a sidecar `.Call()` passes no `.call` argument).
1875    let guard =
1876        |indent: &str| crate::method_return_builder::condition_check_lines(indent).join("\n");
1877
1878    match class_system {
1879        ClassSystem::R6 => {
1880            // Generate $set("active", ...) calls for each sidecar field.
1881            // These are appended after the R6Class definition and add active bindings
1882            // that delegate to the sidecar .Call accessors.
1883            let mut code = String::new();
1884            code.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n# Auto-generated active bindings for {0} sidecar fields.\n",
                type_name))
    })format!(
1885                "\n# Auto-generated active bindings for {type} sidecar fields.\n",
1886                type = type_name,
1887            ));
1888            code.push_str(
1889                "# These are applied when `r_data_accessors` is set on the impl block.\n",
1890            );
1891            code.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".rdata_active_bindings_{0} <- function(cls) {{\n  # R CMD check: self/private are R6 runtime bindings (set by cls$set)\n  self <- private <- NULL\n",
                type_name))
    })format!(
1892                ".rdata_active_bindings_{type} <- function(cls) {{\n\
1893                 \x20 # R CMD check: self/private are R6 runtime bindings (set by cls$set)\n\
1894                 \x20 self <- private <- NULL\n",
1895                type = type_name,
1896            ));
1897            for slot in pub_slots {
1898                // The binding takes the R name; the C symbols keep the Rust
1899                // identifier (#1891).
1900                let field = &slot.r_name;
1901                let rust_field = crate::naming::ident_name(&slot.name);
1902                // Must match the sidecar accessor's actual C symbol exactly (#1273
1903                // crate-prefixing) — routed through the shared naming.rs helpers.
1904                let getter_c = crate::naming::sidecar_getter_c_name(type_name, &rust_field);
1905                // A value is written, or refused for a field without an R
1906                // setter (#2268).
1907                let write = if slot.has_r_setter() {
1908                    let setter_c = crate::naming::sidecar_setter_c_name(type_name, &rust_field);
1909                    let setter_return = if slot.setter_invisible.unwrap_or(true) {
1910                        "invisible(self)"
1911                    } else {
1912                        "self"
1913                    };
1914                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("      .val <- .Call({1}, private$.ptr, value, FALSE)\n{0}\n      {2}\n",
                guard("      "), setter_c, setter_return))
    })format!(
1915                        "\x20     .val <- .Call({setter_c}, private$.ptr, value, FALSE)\n\
1916                         {setter_guard}\n\
1917                         \x20     {setter_return}\n",
1918                        setter_guard = guard("      "),
1919                    )
1920                } else {
1921                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("      {0}\n",
                r6_read_only_refusal(slot, &field_error.class,
                    field_error.read_only_hint.as_deref())))
    })format!(
1922                        "\x20     {}\n",
1923                        r6_read_only_refusal(
1924                            slot,
1925                            &field_error.class,
1926                            field_error.read_only_hint.as_deref()
1927                        )
1928                    )
1929                };
1930                // `FALSE`: the bindings keep reading a save's `Sidecar` values.
1931                code.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  cls$set(\"active\", \"{1}\", function(value) {{\n    if (missing(value)) {{\n      .val <- .Call({2}, private$.ptr, FALSE)\n{0}\n      .val\n    }} else {{\n{3}    }}\n  }}, overwrite = TRUE)\n",
                guard("      "), field, getter_c, write))
    })format!(
1932                    "  cls$set(\"active\", \"{field}\", function(value) {{\n\
1933                     \x20   if (missing(value)) {{\n\
1934                     \x20     .val <- .Call({getter_c}, private$.ptr, FALSE)\n\
1935                     {getter_guard}\n\
1936                     \x20     .val\n\
1937                     \x20   }} else {{\n\
1938                     {write}\
1939                     \x20   }}\n\
1940                     \x20 }}, overwrite = TRUE)\n",
1941                    getter_guard = guard("      "),
1942                ));
1943            }
1944            code.push_str("}\n");
1945            code
1946        }
1947        ClassSystem::S7 => {
1948            // Generate a helper list of S7::new_property() definitions.
1949            // The S7 wrapper generator references this when `r_data_accessors` is set.
1950            let mut code = String::new();
1951            code.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n# Auto-generated S7 property definitions for {0} sidecar fields.\n",
                type_name))
    })format!(
1952                "\n# Auto-generated S7 property definitions for {type} sidecar fields.\n",
1953                type = type_name,
1954            ));
1955            code.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".rdata_properties_{0} <- list(\n",
                type_name))
    })format!(
1956                ".rdata_properties_{type} <- list(\n",
1957                type = type_name,
1958            ));
1959            for (i, slot) in pub_slots.iter().enumerate() {
1960                // The property takes the R name; the C symbols keep the Rust
1961                // identifier (#1891).
1962                let field = &slot.r_name;
1963                let rust_field = crate::naming::ident_name(&slot.name);
1964                // Must match the sidecar accessor's actual C symbol exactly (#1273
1965                // crate-prefixing) — routed through the shared naming.rs helpers.
1966                let getter_c = crate::naming::sidecar_getter_c_name(type_name, &rust_field);
1967                let comma = if i < pub_slots.len() - 1 { "," } else { "" };
1968                // A field without an R setter is a property without a
1969                // setter: S7 refuses `obj@f <- value` itself (#2268).
1970                let setter = if slot.has_r_setter() {
1971                    let setter_c = crate::naming::sidecar_setter_c_name(type_name, &rust_field);
1972                    let setter_return = if slot.setter_invisible.unwrap_or(false) {
1973                        "invisible(self)"
1974                    } else {
1975                        "self"
1976                    };
1977                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(",\n        setter = function(self, value) {{\n          .val <- .Call({1}, self@.ptr, value, FALSE)\n{0}\n          {2}\n        }}",
                guard("          "), setter_c, setter_return))
    })format!(
1978                        ",\n\
1979                         \x20       setter = function(self, value) {{\n\
1980                         \x20         .val <- .Call({setter_c}, self@.ptr, value, FALSE)\n\
1981                         {setter_guard}\n\
1982                         \x20         {setter_return}\n\
1983                         \x20       }}",
1984                        setter_guard = guard("          "),
1985                    )
1986                } else {
1987                    String::new()
1988                };
1989                // `FALSE`: the properties keep reading a save's `Sidecar` values.
1990                code.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("    {1} = S7::new_property(\n        getter = function(self) {{\n          .val <- .Call({2}, self@.ptr, FALSE)\n{0}\n          .val\n        }}{3}\n    ){4}\n",
                guard("          "), field, getter_c, setter, comma))
    })format!(
1991                    "    {field} = S7::new_property(\n\
1992                     \x20       getter = function(self) {{\n\
1993                     \x20         .val <- .Call({getter_c}, self@.ptr, FALSE)\n\
1994                     {getter_guard}\n\
1995                     \x20         .val\n\
1996                     \x20       }}{setter}\n\
1997                     \x20   ){comma}\n",
1998                    getter_guard = guard("          "),
1999                ));
2000            }
2001            code.push_str(")\n");
2002            code
2003        }
2004        // Other class systems don't need class-integrated code
2005        _ => String::new(),
2006    }
2007}
2008
2009/// The R vector of condition classes `c("pkg_a", "pkg_b", "<last>")`: the
2010/// package's `field_error` classes, then miniextendr's own.
2011fn r_class_vector(classes: &[String], last: &str) -> String {
2012    let quoted = classes
2013        .iter()
2014        .map(String::as_str)
2015        .chain([last])
2016        .map(|class| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"",
                crate::naming::r_string_escape(class)))
    })format!("\"{}\"", crate::naming::r_string_escape(class)))
2017        .collect::<Vec<_>>();
2018    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("c({0})", quoted.join(", ")))
    })format!("c({})", quoted.join(", "))
2019}
2020
2021/// The `stop()` of an R6 active binding that refuses a value (#1888,
2022/// #2268), as R6's own read-only active bindings do:
2023/// `miniextendr_read_only_field` with the package's `field_error` classes in
2024/// front, the message naming the field and the object's R6 class, then the
2025/// package's `read_only_hint`, each `%s` in it the field's R name. No call:
2026/// the binding's own call is an anonymous function. The R6 class has none of
2027/// the field-syntax helpers, so the classes and the hint are written in.
2028fn r6_read_only_refusal(slot: &SidecarSlot, classes: &[String], hint: Option<&str>) -> String {
2029    let message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("sprintf(\"`{0}` of `%s` {1}\", class(self)[[1L]])",
                crate::naming::r_string_escape(&slot.r_name),
                slot.read_only_reason()))
    })format!(
2030        "sprintf(\"`{}` of `%s` {}\", class(self)[[1L]])",
2031        crate::naming::r_string_escape(&slot.r_name),
2032        slot.read_only_reason()
2033    );
2034    let message = match hint {
2035        None => message,
2036        Some(hint) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("paste0({1}, \". \", \"{0}\")",
                crate::naming::r_string_escape(&hint.replace("%s",
                            &slot.r_name)), message))
    })format!(
2037            "paste0({message}, \". \", \"{}\")",
2038            crate::naming::r_string_escape(&hint.replace("%s", &slot.r_name))
2039        ),
2040    };
2041    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("stop(errorCondition({1}, class = {0}, call = NULL))",
                r_class_vector(classes, "miniextendr_read_only_field"),
                message))
    })format!(
2042        "stop(errorCondition({message}, class = {}, call = NULL))",
2043        r_class_vector(classes, "miniextendr_read_only_field")
2044    )
2045}
2046
2047/// Generate the R helpers the `$` / `[[` field methods of `r_data_accessors`
2048/// share on S3, S4 and env classes (#1848): the field names, a getter and a
2049/// setter `switch()` over the fields' `.Call()`s, the classed
2050/// `miniextendr_no_field` error naming the fields, the classes the methods
2051/// put in front of their own errors (`field_error`, `NULL` without them,
2052/// #1899), and the liveness check of `restored(refuse = "every_read")`
2053/// with the flag that gates it (`FALSE` and a stub without it, #1901).
2054/// Without `writes` there is no setter `switch()`: the read-only form's
2055/// writers refuse every field, and its setter routines are not registered
2056/// (#2292).
2057///
2058/// Prepared for every type with R accessors, whatever `#[externalptr(...)]`
2059/// names, and bundled with its internal accessor rendering. The writer selects
2060/// that rendering only when an impl enables field syntax, so the impl's option
2061/// never depends on the derive attribute. The
2062/// helpers are named by the Rust type ([`crate::naming::rdata_helper_name`]);
2063/// the field names and the `switch()` labels are the fields' R names, in
2064/// declared order, computed fields included (#1891, #1883).
2065///
2066/// Every arm passes `TRUE` as the accessor's `require_live` flag, so the
2067/// field methods refuse a pointer restored from a saved session (the
2068/// standalone accessors pass `FALSE` and keep reading its `Sidecar` values).
2069/// The accessors return a failed conversion or a panic as a tagged condition
2070/// value with no call; the calling method raises it with its own frame as
2071/// the fallback, so the condition reports `x$keys <- value`. The setter arm
2072/// of a field without an R setter (a `Computed` or `#[r_data(read_only)]`
2073/// one, #2268) calls `.rdata_read_only_<Type>`, which raises
2074/// `miniextendr_read_only_field` with the calling method's frame
2075/// (`parent.frame()`) resolved the same way; the writers of `r_data_accessors
2076/// = "read_only"` call it for every field. The liveness check returns the
2077/// same kind of value as the accessors, which the method raises.
2078///
2079/// `field_error(no_field_hint = "...")` adds a sentence after the field list
2080/// of the `miniextendr_no_field` message, each `%s` in it replaced by the
2081/// name asked for (#2112), and `field_error(read_only_hint = "...")` one
2082/// after the `miniextendr_read_only_field` message, each `%s` the field's
2083/// name (#2268) ([`r_hint_parts`]).
2084fn generate_field_syntax_helpers(
2085    type_name: &str,
2086    pub_slots: &[&SidecarSlot],
2087    field_error: &FieldErrorOptions,
2088    every_read: bool,
2089    writes: bool,
2090) -> String {
2091    use crate::naming::{RDataHelper, rdata_helper_name};
2092
2093    let error_class_var = rdata_helper_name(RDataHelper::ErrorClass, type_name);
2094    let read_only_fn = rdata_helper_name(RDataHelper::ReadOnly, type_name);
2095    let names = pub_slots
2096        .iter()
2097        .map(|slot| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"", slot.r_name))
    })format!("\"{}\"", slot.r_name))
2098        .collect::<Vec<_>>()
2099        .join(", ");
2100    let listed = pub_slots
2101        .iter()
2102        .map(|slot| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", slot.r_name))
    })format!("`{}`", slot.r_name))
2103        .collect::<Vec<_>>()
2104        .join(", ");
2105    // `switch()` arm labels are R symbols: a raw identifier such as `r#for`
2106    // becomes the reserved word `for`, which needs backticks. The C symbols
2107    // are named by the Rust identifier.
2108    let arms = |setter: bool| {
2109        pub_slots
2110            .iter()
2111            .map(|slot| {
2112                let rust_field = crate::naming::ident_name(&slot.name);
2113                let call = match setter {
2114                    // A field R can't write: the refusal names the field
2115                    // and why (#1883, #2268).
2116                    true if !slot.has_r_setter() => {
2117                        let field = crate::naming::r_string_escape(&slot.r_name);
2118                        match slot.read_only_reason() {
2119                            READ_ONLY_REASON => {
2120                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}(\"{1}\", x, parent.frame())",
                read_only_fn, field))
    })format!("{read_only_fn}(\"{field}\", x, parent.frame())")
2121                            }
2122                            why => {
2123                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}(\"{1}\", x, parent.frame(), \"{2}\")",
                read_only_fn, field, why))
    })format!("{read_only_fn}(\"{field}\", x, parent.frame(), \"{why}\")")
2124                            }
2125                        }
2126                    }
2127                    true => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".Call({0}, x, value, TRUE)",
                crate::naming::sidecar_setter_c_name(type_name, &rust_field)))
    })format!(
2128                        ".Call({}, x, value, TRUE)",
2129                        crate::naming::sidecar_setter_c_name(type_name, &rust_field)
2130                    ),
2131                    false => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".Call({0}, x, TRUE)",
                crate::naming::sidecar_getter_c_name(type_name, &rust_field)))
    })format!(
2132                        ".Call({}, x, TRUE)",
2133                        crate::naming::sidecar_getter_c_name(type_name, &rust_field)
2134                    ),
2135                };
2136                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0} = {1}",
                crate::naming::r_def_name(&slot.r_name), call))
    })format!("  {} = {call}", crate::naming::r_def_name(&slot.r_name))
2137            })
2138            .collect::<Vec<_>>()
2139            .join(",\n")
2140    };
2141    let error_class = if field_error.class.is_empty() {
2142        "NULL".to_string()
2143    } else {
2144        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("c({0})",
                field_error.class.iter().map(|class|
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("\"{0}\"",
                                                crate::naming::r_string_escape(class)))
                                    })).collect::<Vec<_>>().join(", ")))
    })format!(
2145            "c({})",
2146            field_error
2147                .class
2148                .iter()
2149                .map(|class| format!("\"{}\"", crate::naming::r_string_escape(class)))
2150                .collect::<Vec<_>>()
2151                .join(", ")
2152        )
2153    };
2154    // Without the option the methods never call the check (the flag is
2155    // `FALSE`), but they name it, and `R CMD check` notes a call to a binding
2156    // that is no function.
2157    let live = if every_read {
2158        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("function(x, raise) .Call({0}, x, raise)",
                crate::naming::sidecar_live_c_name(type_name)))
    })format!(
2159            "function(x, raise) .Call({}, x, raise)",
2160            crate::naming::sidecar_live_c_name(type_name)
2161        )
2162    } else {
2163        "function(x, raise) TRUE".to_string()
2164    };
2165    let every_read = if every_read { "TRUE" } else { "FALSE" };
2166    // The read-only form's `$<-` / `[[<-` refuse every field without
2167    // calling it, and its setter routines are not registered (#2292).
2168    let set_helper = if writes {
2169        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function(x, name, value) switch(name,\n{1})\n",
                rdata_helper_name(RDataHelper::Set, type_name), arms(true)))
    })format!(
2170            "{set_fn} <- function(x, name, value) switch(name,\n{set_arms})\n",
2171            set_fn = rdata_helper_name(RDataHelper::Set, type_name),
2172            set_arms = arms(true),
2173        )
2174    } else {
2175        String::new()
2176    };
2177    let no_field_message =
2178        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("sprintf(\"`%s` is not a field of `%s`; its fields are {0}\", name, cls)",
                listed))
    })format!("sprintf(\"`%s` is not a field of `%s`; its fields are {listed}\", name, cls)");
2179    let no_field_message = match &field_error.no_field_hint {
2180        None => no_field_message,
2181        Some(hint) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("paste0({1}, \". \", {0})",
                r_hint_parts(hint), no_field_message))
    })format!("paste0({no_field_message}, \". \", {})", r_hint_parts(hint)),
2182    };
2183    // The message names the receiver's R class (#1920), else the Rust type.
2184    let read_only_message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("sprintf(\"`%s` of `%s` %s\", name, if (is.null(oldClass(x))) \"{0}\" else oldClass(x)[[1L]], why)",
                type_name))
    })format!(
2185        "sprintf(\"`%s` of `%s` %s\", name, if (is.null(oldClass(x))) \"{type_name}\" else \
2186         oldClass(x)[[1L]], why)"
2187    );
2188    let read_only_message = match &field_error.read_only_hint {
2189        None => read_only_message,
2190        Some(hint) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("paste0({1}, \". \", {0})",
                r_hint_parts(hint), read_only_message))
    })format!(
2191            "paste0({read_only_message}, \". \", {})",
2192            r_hint_parts(hint)
2193        ),
2194    };
2195    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n# Field syntax helpers for {6} sidecar fields, shared by the `$` / `[[`\n# methods `r_data_accessors` generates on S3, S4 and env classes. The `TRUE`\n# is the accessors\' `require_live` flag: the methods refuse a restored pointer.\n{0} <- c({7})\n{1} <- function(x, name) switch(name,\n{5})\n{8}{9} <- {10}\n{2} <- function(name, env, cls) stop(errorCondition(\n  {11},\n  class = c({9}, \"miniextendr_no_field\"), call = .miniextendr_frame_call(env)))\n{12} <- function(name, x, env, why = \"{13}\") stop(errorCondition(\n  {14},\n  class = c({9}, \"miniextendr_read_only_field\"), call = .miniextendr_frame_call(env)))\n{3} <- {15}\n{4} <- {16}\n",
                rdata_helper_name(RDataHelper::Fields, type_name),
                rdata_helper_name(RDataHelper::Get, type_name),
                rdata_helper_name(RDataHelper::NoField, type_name),
                rdata_helper_name(RDataHelper::EveryRead, type_name),
                rdata_helper_name(RDataHelper::Live, type_name), arms(false),
                type_name, names, set_helper, error_class_var, error_class,
                no_field_message, read_only_fn, READ_ONLY_REASON,
                read_only_message, every_read, live))
    })format!(
2196        "\n# Field syntax helpers for {type_name} sidecar fields, shared by the `$` / `[[`\n\
2197         # methods `r_data_accessors` generates on S3, S4 and env classes. The `TRUE`\n\
2198         # is the accessors' `require_live` flag: the methods refuse a restored pointer.\n\
2199         {fields_var} <- c({names})\n\
2200         {get_fn} <- function(x, name) switch(name,\n{get_arms})\n\
2201         {set_helper}\
2202         {error_class_var} <- {error_class}\n\
2203         {no_field_fn} <- function(name, env, cls) stop(errorCondition(\n\
2204         \x20 {no_field_message},\n\
2205         \x20 class = c({error_class_var}, \"miniextendr_no_field\"), call = .miniextendr_frame_call(env)))\n\
2206         {read_only_fn} <- function(name, x, env, why = \"{READ_ONLY_REASON}\") stop(errorCondition(\n\
2207         \x20 {read_only_message},\n\
2208         \x20 class = c({error_class_var}, \"miniextendr_read_only_field\"), call = .miniextendr_frame_call(env)))\n\
2209         {every_read_var} <- {every_read}\n\
2210         {live_fn} <- {live}\n",
2211        fields_var = rdata_helper_name(RDataHelper::Fields, type_name),
2212        get_fn = rdata_helper_name(RDataHelper::Get, type_name),
2213        no_field_fn = rdata_helper_name(RDataHelper::NoField, type_name),
2214        every_read_var = rdata_helper_name(RDataHelper::EveryRead, type_name),
2215        live_fn = rdata_helper_name(RDataHelper::Live, type_name),
2216        get_arms = arms(false),
2217    )
2218}
2219
2220/// A `field_error` hint as `paste0()` arguments: its text split on `%s`,
2221/// each part an R string, with the R variable `name` between the parts
2222/// (#2112, #2268). Any other `%` or `\` in the hint, or in the name, stays
2223/// as written.
2224fn r_hint_parts(hint: &str) -> String {
2225    hint.split("%s")
2226        .map(|part| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"",
                crate::naming::r_string_escape(part)))
    })format!("\"{}\"", crate::naming::r_string_escape(part)))
2227        .collect::<Vec<_>>()
2228        .join(", name, ")
2229}
2230
2231/// Generate sidecar accessor constants and `extern "C-unwind"` functions.
2232///
2233/// For each public `#[r_data]` field, generates:
2234/// - A getter FFI function (`C_<crate>__mx_rdata_get_Type_field`)
2235/// - A setter FFI function (`C_<crate>__mx_rdata_set_Type_field`)
2236/// - `R_CallMethodDef` entries for routine registration: the getters' in
2237///   `MX_CALL_DEFS`, the setters' with their type in `MX_SIDECAR_SETTERS`,
2238///   which leaves them unregistered under `r_data_accessors = "read_only"`
2239///   (#2292)
2240/// - R wrapper function code (roxygen-documented)
2241/// - Class-integration code for R6 / S7 (active bindings / properties)
2242/// - The helpers of the S3 / S4 / env field methods
2243///   ([`generate_field_syntax_helpers`])
2244///
2245/// - With `restored(refuse = "every_read")`, the liveness check
2246///   (`C_<crate>__mx_rdata_live_Type`, #1901) the field methods call
2247///
2248/// The generated statics are:
2249/// - `__MX_CALL_DEF_RDATA_*`: the `R_CallMethodDef` entries
2250///   (`__MX_CALL_DEF_RDATA_SET_*` a `registry::SidecarSetterEntry` each)
2251/// - `R_WRAPPERS_RDATA_{Type}`: the R6 / S7 integration, when present
2252/// - `R_SIDECAR_ACCESSORS_{Type}`: the standalone accessors, exported,
2253///   internal, and internal without the setters, which the wrapper writer
2254///   picks between by the class's field syntax
2255///   (`registry::SidecarAccessorsEntry`, #1900; the last for
2256///   `r_data_accessors = "read_only"`, #2268). Only the internal renderings
2257///   include the field-syntax helpers.
2258///
2259/// Returns `Err` if the struct has generic type parameters (`.Call` entrypoints
2260/// cannot be generic).
2261fn generate_sidecar_accessors(
2262    input: &DeriveInput,
2263    info: &SidecarInfo,
2264    restored: &RestoredOptions,
2265    field_error: &FieldErrorOptions,
2266) -> syn::Result<TokenStream> {
2267    // Reject generic structs — .Call entrypoints cannot be generic
2268    if !input.generics.params.is_empty() {
2269        return Err(syn::Error::new_spanned(
2270            &input.generics,
2271            "ExternalPtr does not support generic structs; \
2272             .Call entrypoints cannot be generic",
2273        ));
2274    }
2275
2276    // If no selector or no public slots, nothing to register
2277    let pub_slots: Vec<_> = info.slots.iter().filter(|s| s.is_public).collect();
2278    if !info.has_selector || pub_slots.is_empty() {
2279        return Ok(::quote::__private::TokenStream::new()quote::quote! {});
2280    }
2281
2282    let name = &input.ident;
2283    let name_str = name.to_string();
2284    let name_symbol = crate::naming::ident_name(name);
2285
2286    // Generate getter/setter functions and R wrappers for each pub slot
2287    let mut c_functions = ::alloc::vec::Vec::new()vec![];
2288    // The standalone accessors, in the renderings the wrapper writer picks
2289    // between (#1900): exported, internal, and internal without the setters
2290    // for a class whose field syntax is read-only (#2268).
2291    let mut exported = String::new();
2292    let mut internal = String::new();
2293    let mut internal_read_only = String::new();
2294
2295    // The exported rendering's page header establishes the @name topic for
2296    // the accessors' `@rdname`, even if the main class definition uses @noRd.
2297    let source_line = crate::roxygen::source_tag(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated by miniextendr from `#[derive(ExternalPtr)]` on `{0}`",
                name_str))
    })format!(
2298        "Generated by miniextendr from `#[derive(ExternalPtr)]` on `{name_str}`"
2299    ))
2300    .map(|line| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\n", line))
    })format!("{line}\n"))
2301    .unwrap_or_default();
2302    exported.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n#\' @title {0} Sidecar Accessors\n#\' @name {0}\n#\' @description Getter and setter functions for `#[r_data]` fields on `{0}`.\n{1}NULL\n\n",
                name_str, source_line))
    })format!(
2303        r#"
2304#' @title {type} Sidecar Accessors
2305#' @name {type}
2306#' @description Getter and setter functions for `#[r_data]` fields on `{type}`.
2307{source_line}NULL
2308
2309"#,
2310        type = name_str,
2311    ));
2312
2313    for slot in &pub_slots {
2314        let field_name = &slot.name;
2315        // The C symbols and the `R_CallMethodDef` statics are named by the
2316        // Rust identifier (`Ident::new` would refuse an R name such as
2317        // `n.rows`); every R-facing string takes the R name (#1891).
2318        let field_name_str = crate::naming::ident_name(field_name);
2319        let r_name = &slot.r_name;
2320        let computed = #[allow(non_exhaustive_omitted_patterns)] match slot.kind {
    SlotKind::Computed(_) => true,
    _ => false,
}matches!(slot.kind, SlotKind::Computed(_));
2321        // A `Computed` field and an `#[r_data(read_only)]` one have no R
2322        // setter (#1883, #2268).
2323        let r_setter = slot.has_r_setter();
2324
2325        // C function names (crate-prefixed for webR cross-package symbol
2326        // uniqueness — #1273, routed through the shared naming.rs helpers)
2327        let getter_c_name = crate::naming::sidecar_getter_c_name(&name_str, &field_name_str);
2328        let setter_c_name = crate::naming::sidecar_setter_c_name(&name_str, &field_name_str);
2329        let getter_fn_name = Ident::new(&getter_c_name, Span::call_site());
2330        let setter_fn_name = Ident::new(&setter_c_name, Span::call_site());
2331        let source_location_doc = crate::source_location_doc(field_name.span());
2332        let getter_doc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated sidecar getter for `{0}` field on Rust type `{1}`.",
                field_name_str, name_str))
    })format!(
2333            "Generated sidecar getter for `{}` field on Rust type `{}`.",
2334            field_name_str, name_str
2335        );
2336        let setter_doc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated sidecar setter for `{0}` field on Rust type `{1}`.",
                field_name_str, name_str))
    })format!(
2337            "Generated sidecar setter for `{}` field on Rust type `{}`.",
2338            field_name_str, name_str
2339        );
2340        let getter_doc_lit = syn::LitStr::new(&getter_doc, field_name.span());
2341        let setter_doc_lit = syn::LitStr::new(&setter_doc, field_name.span());
2342        // The `require_live` flag the R side passes last: `TRUE` from the
2343        // field methods, `FALSE` from the standalone accessors, the R6
2344        // bindings and the S7 properties. Only a `Sidecar` slot reads it.
2345        let require_live = require_live_param(slot);
2346
2347        // Generate getter/setter bodies based on slot kind
2348        let getter_body = generate_getter_body(name, slot);
2349
2350        // Generate C getter function.
2351        //
2352        // The body runs under `with_r_unwind_protect` so Rust panics (and R
2353        // longjmps during allocation) become a tagged condition SEXP that the
2354        // R wrapper re-raises, matching the main call-slot path. Sidecar
2355        // accessors have no `__miniextendr_call` slot (#344/#348), so the
2356        // transport uses null call attribution; the R wrapper's guard passes
2357        // `sys.call()` to `.miniextendr_raise_condition` as the fallback.
2358        // Conditions queued inside the body (a `defer_warning!` in a field's
2359        // `IntoR` / `TryFromSexp`) are signalled at this call, through the
2360        // same `mark()` / `finish()` pair the generated wrappers have.
2361        c_functions.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&getter_doc_lit, &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::ToTokens::to_tokens(&source_location_doc, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"Generated from source file `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "file");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "no_mangle");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "non_snake_case");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "pub");
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_ident(&mut _s, "extern");
    ::quote::__private::parse(&mut _s, "\"C-unwind\"");
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::ToTokens::to_tokens(&getter_fn_name, &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, "x");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&require_live, &mut _s);
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_rarrow(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SEXP");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s,
                "__miniextendr_deferred_mark");
            ::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, "deferred_condition");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "mark");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s, "__miniextendr_value");
            ::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, "unwind_protect");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "with_r_unwind_protect");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_or_or(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&getter_body, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "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_comma(&mut _s);
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "deferred_condition");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "finish");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s,
                                "__miniextendr_deferred_mark");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_ident(&mut _s,
                                "__miniextendr_value");
                            ::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_comma(&mut _s);
                            _s
                        });
                    _s
                });
            _s
        });
    _s
}quote::quote! {
2362            #[doc = #getter_doc_lit]
2363            #[doc = #source_location_doc]
2364            #[doc = ::core::concat!("Generated from source file `", ::core::file!(), "`.")]
2365            #[doc(hidden)]
2366            #[unsafe(no_mangle)]
2367            #[allow(non_snake_case)]
2368            pub unsafe extern "C-unwind" fn #getter_fn_name(
2369                x: ::miniextendr_api::SEXP,
2370                #require_live: ::miniextendr_api::SEXP,
2371            ) -> ::miniextendr_api::SEXP {
2372                let __miniextendr_deferred_mark = ::miniextendr_api::deferred_condition::mark();
2373                let __miniextendr_value = ::miniextendr_api::unwind_protect::with_r_unwind_protect(
2374                    || { #getter_body },
2375                    ::core::option::Option::None,
2376                );
2377                unsafe {
2378                    ::miniextendr_api::deferred_condition::finish(
2379                        __miniextendr_deferred_mark,
2380                        __miniextendr_value,
2381                        ::core::option::Option::None,
2382                    )
2383                }
2384            }
2385        });
2386
2387        // Generate R_CallMethodDef entries via distributed slice
2388        let getter_def_ident = Ident::new(
2389            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__MX_CALL_DEF_RDATA_GET_{0}_{1}",
                name_symbol, field_name_str))
    })format!("__MX_CALL_DEF_RDATA_GET_{}_{}", name_symbol, field_name_str),
2390            Span::call_site(),
2391        );
2392        let getter_registration =
2393            crate::call_method_def::call_method_def(&getter_def_ident, &getter_fn_name, 2);
2394        c_functions.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::ToTokens::to_tokens(&getter_registration, &mut _s);
    _s
}quote::quote! {
2395            #[doc(hidden)]
2396            #getter_registration
2397        });
2398
2399        // A computed or read-only field has no R setter: no C function, no
2400        // `CallDef`, no `Type_set_<name>()` (#1883, #2268). The Rust
2401        // accessors of a read-only `Sidecar` field stay.
2402        if r_setter {
2403            let setter_body = generate_setter_body(name, slot);
2404            // Generate C setter function (same unwind/condition transport as
2405            // the getter above).
2406            c_functions.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&setter_doc_lit, &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::ToTokens::to_tokens(&source_location_doc, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"Generated from source file `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "file");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "no_mangle");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "non_snake_case");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "pub");
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_ident(&mut _s, "extern");
    ::quote::__private::parse(&mut _s, "\"C-unwind\"");
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::ToTokens::to_tokens(&setter_fn_name, &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, "x");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "value");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&require_live, &mut _s);
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_rarrow(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SEXP");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s,
                "__miniextendr_deferred_mark");
            ::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, "deferred_condition");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "mark");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s, "__miniextendr_value");
            ::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, "unwind_protect");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "with_r_unwind_protect");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_or_or(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&setter_body, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "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_comma(&mut _s);
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "deferred_condition");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "finish");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s,
                                "__miniextendr_deferred_mark");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_ident(&mut _s,
                                "__miniextendr_value");
                            ::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_comma(&mut _s);
                            _s
                        });
                    _s
                });
            _s
        });
    _s
}quote::quote! {
2407                #[doc = #setter_doc_lit]
2408                #[doc = #source_location_doc]
2409                #[doc = ::core::concat!("Generated from source file `", ::core::file!(), "`.")]
2410                #[doc(hidden)]
2411                #[unsafe(no_mangle)]
2412                #[allow(non_snake_case)]
2413                pub unsafe extern "C-unwind" fn #setter_fn_name(
2414                    x: ::miniextendr_api::SEXP,
2415                    value: ::miniextendr_api::SEXP,
2416                    #require_live: ::miniextendr_api::SEXP,
2417                ) -> ::miniextendr_api::SEXP {
2418                    let __miniextendr_deferred_mark = ::miniextendr_api::deferred_condition::mark();
2419                    let __miniextendr_value = ::miniextendr_api::unwind_protect::with_r_unwind_protect(
2420                        || { #setter_body },
2421                        ::core::option::Option::None,
2422                    );
2423                    unsafe {
2424                        ::miniextendr_api::deferred_condition::finish(
2425                            __miniextendr_deferred_mark,
2426                            __miniextendr_value,
2427                            ::core::option::Option::None,
2428                        )
2429                    }
2430                }
2431            });
2432
2433            // Registered with its type, not in `MX_CALL_DEFS`: the routines
2434            // R gets leave it out when an impl block of the type makes the
2435            // fields read-only (`r_data_accessors = "read_only"`), which this
2436            // expansion can't see (#2292).
2437            let setter_def_ident = Ident::new(
2438                &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__MX_CALL_DEF_RDATA_SET_{0}_{1}",
                name_symbol, field_name_str))
    })format!("__MX_CALL_DEF_RDATA_SET_{}_{}", name_symbol, field_name_str),
2439                Span::call_site(),
2440            );
2441            let setter_def = crate::call_method_def::call_method_def_value(&setter_fn_name, 3);
2442            c_functions.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "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_SIDECAR_SETTERS");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "crate");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "linkme");
                            _s
                        });
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "non_upper_case_globals");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "non_snake_case");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "static");
    ::quote::ToTokens::to_tokens(&setter_def_ident, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SidecarSetterEntry");
    ::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, "SidecarSetterEntry");
    ::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::ToTokens::to_tokens(&name_str, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "def");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&setter_def, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
2443                #[doc(hidden)]
2444                #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_SIDECAR_SETTERS), linkme(crate = ::miniextendr_api::linkme))]
2445                #[allow(non_upper_case_globals, non_snake_case)]
2446                static #setter_def_ident: ::miniextendr_api::registry::SidecarSetterEntry =
2447                    ::miniextendr_api::registry::SidecarSetterEntry {
2448                        rust_type: #name_str,
2449                        def: #setter_def,
2450                    };
2451            });
2452        }
2453
2454        // Generate R wrapper code based on class system. The read-only
2455        // rendering writes every field as a field without an R setter.
2456        let comment = |with_setter: bool| {
2457            let via = if with_setter {
2458                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` and `{1}`", getter_c_name,
                setter_c_name))
    })format!("`{getter_c_name}` and `{setter_c_name}`")
2459            } else {
2460                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", getter_c_name))
    })format!("`{getter_c_name}`")
2461            };
2462            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# Generated from Rust source {0}\n# Wraps {1} `{2}` on Rust type `{3}` via {4}.\n",
                crate::source_position(field_name.span()),
                if computed {
                    "computed field"
                } else if with_setter {
                    "sidecar field"
                } else { "read-only sidecar field" }, r_name, name_str, via))
    })format!(
2463                "# Generated from Rust source {}\n# Wraps {} `{}` on Rust type `{}` via {}.\n",
2464                crate::source_position(field_name.span()),
2465                if computed {
2466                    "computed field"
2467                } else if with_setter {
2468                    "sidecar field"
2469                } else {
2470                    "read-only sidecar field"
2471                },
2472                r_name,
2473                name_str,
2474                via,
2475            )
2476        };
2477        for (out, is_exported, with_setter) in [
2478            (&mut exported, true, r_setter),
2479            (&mut internal, false, r_setter),
2480            (&mut internal_read_only, false, false),
2481        ] {
2482            out.push_str(&comment(with_setter));
2483            out.push_str(&generate_r_wrapper_for_slot(
2484                info.class_system,
2485                &name_str,
2486                r_name,
2487                &getter_c_name,
2488                with_setter.then_some(setter_c_name.as_str()),
2489                slot.setter_invisible.unwrap_or(true),
2490                is_exported,
2491            ));
2492        }
2493    }
2494
2495    // The liveness check of `restored(refuse = "every_read")` (#1901): the
2496    // field methods ask it before a read that reaches no accessor. `raise`
2497    // refuses a pointer without its Rust value as the accessors do;
2498    // otherwise it answers whether the pointer has one.
2499    if restored.every_read {
2500        let live_c_name = crate::naming::sidecar_live_c_name(&name_str);
2501        let live_fn_name = Ident::new(&live_c_name, Span::call_site());
2502        let live_doc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated liveness check of the field methods of Rust type `{0}` (`restored(refuse = \"every_read\")`).",
                name_str))
    })format!(
2503            "Generated liveness check of the field methods of Rust type `{name_str}` \
2504             (`restored(refuse = \"every_read\")`)."
2505        );
2506        let live_def_ident = Ident::new(
2507            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__MX_CALL_DEF_RDATA_LIVE_{0}",
                name_symbol))
    })format!("__MX_CALL_DEF_RDATA_LIVE_{name_symbol}"),
2508            Span::call_site(),
2509        );
2510        let live_registration =
2511            crate::call_method_def::call_method_def(&live_def_ident, &live_fn_name, 2);
2512        c_functions.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&live_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_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "no_mangle");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "non_snake_case");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "pub");
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_ident(&mut _s, "extern");
    ::quote::__private::parse(&mut _s, "\"C-unwind\"");
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::ToTokens::to_tokens(&live_fn_name, &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, "x");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "raise");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_rarrow(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SEXP");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s,
                "__miniextendr_deferred_mark");
            ::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, "deferred_condition");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "mark");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s, "__miniextendr_value");
            ::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, "unwind_protect");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "with_r_unwind_protect");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_or_or(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "use");
                            ::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_semi(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "let");
                            ::quote::__private::push_ident(&mut _s, "raise");
                            ::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,
                                "sidecar_require_live");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s, "raise");
                                    _s
                                });
                            ::quote::__private::push_semi(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "SEXP");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "scalar_logical");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::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, "sidecar_r_live");
                                            ::quote::__private::push_colon2(&mut _s);
                                            ::quote::__private::push_lt(&mut _s);
                                            ::quote::ToTokens::to_tokens(&name, &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, "x");
                                                    ::quote::__private::push_comma(&mut _s);
                                                    ::quote::__private::push_ident(&mut _s, "raise");
                                                    _s
                                                });
                                            _s
                                        });
                                    _s
                                });
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "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_comma(&mut _s);
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "deferred_condition");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "finish");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s,
                                "__miniextendr_deferred_mark");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_ident(&mut _s,
                                "__miniextendr_value");
                            ::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_comma(&mut _s);
                            _s
                        });
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::ToTokens::to_tokens(&live_registration, &mut _s);
    _s
}quote::quote! {
2513            #[doc = #live_doc]
2514            #[doc(hidden)]
2515            #[unsafe(no_mangle)]
2516            #[allow(non_snake_case)]
2517            pub unsafe extern "C-unwind" fn #live_fn_name(
2518                x: ::miniextendr_api::SEXP,
2519                raise: ::miniextendr_api::SEXP,
2520            ) -> ::miniextendr_api::SEXP {
2521                let __miniextendr_deferred_mark = ::miniextendr_api::deferred_condition::mark();
2522                let __miniextendr_value = ::miniextendr_api::unwind_protect::with_r_unwind_protect(
2523                    || {
2524                        use ::miniextendr_api::SEXP;
2525                        let raise = ::miniextendr_api::externalptr::sidecar_require_live(raise);
2526                        SEXP::scalar_logical(unsafe {
2527                            ::miniextendr_api::externalptr::sidecar_r_live::<#name>(x, raise)
2528                        })
2529                    },
2530                    ::core::option::Option::None,
2531                );
2532                unsafe {
2533                    ::miniextendr_api::deferred_condition::finish(
2534                        __miniextendr_deferred_mark,
2535                        __miniextendr_value,
2536                        ::core::option::Option::None,
2537                    )
2538                }
2539            }
2540
2541            #[doc(hidden)]
2542            #live_registration
2543        });
2544    }
2545
2546    // R6 / S7 integration is independent of S3 / S4 / env field syntax.
2547    let r_wrappers =
2548        generate_class_integration_r_code(info.class_system, &name_str, &pub_slots, field_error);
2549    // The writer selects these renderings only when an impl enables field
2550    // syntax. Other types need their standalone accessors, not these helpers.
2551    let helpers = |writes| {
2552        generate_field_syntax_helpers(
2553            &name_str,
2554            &pub_slots,
2555            field_error,
2556            restored.every_read,
2557            writes,
2558        )
2559    };
2560    internal.push_str(&helpers(true));
2561    internal_read_only.push_str(&helpers(false));
2562
2563    let const_name_wrappers = Ident::new(
2564        &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("R_WRAPPERS_RDATA_{0}",
                name_symbol))
    })format!("R_WRAPPERS_RDATA_{}", name_symbol),
2565        Span::call_site(),
2566    );
2567    let const_name_accessors = Ident::new(
2568        &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("R_SIDECAR_ACCESSORS_{0}",
                name_symbol))
    })format!("R_SIDECAR_ACCESSORS_{}", name_symbol),
2569        Span::call_site(),
2570    );
2571    let source_location_doc = crate::source_location_doc(name.span());
2572    let source_line_lit = syn::LitInt::new(&name.span().start().line.to_string(), name.span());
2573
2574    // For S7 class systems, emit MX_S7_SIDECAR_PROPS entries so the S7 codegen
2575    // can substitute @prop lines for sidecar properties at write time.
2576    let sidecar_prop_entries = if info.class_system == ClassSystem::S7 {
2577        let entries: Vec<_> = pub_slots
2578            .iter()
2579            .map(|slot| {
2580                // The property's R name; `registry.rs` derives the
2581                // `<Class>_get_<name>` collision names from it too, and
2582                // `<Class>_set_<name>` for a field with an R setter.
2583                let field_str = slot.r_name.as_str();
2584                let read_only = !slot.has_r_setter();
2585                let doc_str = slot
2586                    .prop_doc
2587                    .as_deref()
2588                    .unwrap_or("(undocumented sidecar property)");
2589                // The static is named by the Rust identifier: an R name may
2590                // hold a `.`.
2591                let entry_ident = Ident::new(
2592                    &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__MX_S7_SIDECAR_PROP_{0}_{1}",
                name_symbol, crate::naming::ident_name(&slot.name)))
    })format!(
2593                        "__MX_S7_SIDECAR_PROP_{}_{}",
2594                        name_symbol,
2595                        crate::naming::ident_name(&slot.name)
2596                    ),
2597                    Span::call_site(),
2598                );
2599                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "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_S7_SIDECAR_PROPS");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "crate");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "linkme");
                            _s
                        });
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "non_upper_case_globals");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "static");
    ::quote::ToTokens::to_tokens(&entry_ident, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SidecarPropEntry");
    ::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, "SidecarPropEntry");
    ::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::ToTokens::to_tokens(&name_str, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "field_name");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&field_str, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "prop_doc");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&doc_str, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "read_only");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&read_only, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
2600                    #[doc(hidden)]
2601                    #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_S7_SIDECAR_PROPS), linkme(crate = ::miniextendr_api::linkme))]
2602                    #[allow(non_upper_case_globals)]
2603                    static #entry_ident: ::miniextendr_api::registry::SidecarPropEntry =
2604                        ::miniextendr_api::registry::SidecarPropEntry {
2605                            rust_type: #name_str,
2606                            field_name: #field_str,
2607                            prop_doc: #doc_str,
2608                            read_only: #read_only,
2609                        };
2610                }
2611            })
2612            .collect();
2613        {
    let mut _s = ::quote::__private::TokenStream::new();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut entries, i) = entries.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let entries =
                match entries.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&entries, &mut _s);
        }
    }
    _s
}quote::quote! { #(#entries)* }
2614    } else {
2615        ::quote::__private::TokenStream::new();quote::quote! {}
2616    };
2617
2618    let class_integration_wrappers = (!r_wrappers.is_empty()).then(|| {
    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::__private::parse(&mut _s,
                "r\" Sidecar accessor R wrapper code via distributed slice.\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&source_location_doc, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"Generated from source file `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "file");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "cfg_attr");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "not");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "target_arch");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::parse(&mut _s, "\"wasm32\"");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "distributed_slice");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "registry");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "MX_R_WRAPPERS");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "crate");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "linkme");
                            _s
                        });
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "non_upper_case_globals");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "static");
    ::quote::ToTokens::to_tokens(&const_name_wrappers, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "RWrapperEntry");
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "RWrapperEntry");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "priority");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "registry");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "RWrapperPriority");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Sidecar");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "source_file");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "file");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "source_line");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&source_line_lit, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "content");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&r_wrappers, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
2619        /// Sidecar accessor R wrapper code via distributed slice.
2620        #[doc = #source_location_doc]
2621        #[doc = ::core::concat!("Generated from source file `", ::core::file!(), "`.")]
2622        #[doc(hidden)]
2623        #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_R_WRAPPERS), linkme(crate = ::miniextendr_api::linkme))]
2624        #[allow(non_upper_case_globals)]
2625        static #const_name_wrappers: ::miniextendr_api::registry::RWrapperEntry =
2626            ::miniextendr_api::registry::RWrapperEntry {
2627                priority: ::miniextendr_api::registry::RWrapperPriority::Sidecar,
2628                source_file: ::core::file!(),
2629                source_line: #source_line_lit,
2630                content: #r_wrappers,
2631            };
2632    });
2633
2634    Ok({
    let mut _s = ::quote::__private::TokenStream::new();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut c_functions, i) = c_functions.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let c_functions =
                match c_functions.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&c_functions, &mut _s);
        }
    }
    ::quote::ToTokens::to_tokens(&class_integration_wrappers, &mut _s);
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" The standalone sidecar accessors, exported, internal and internal\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" without setters, via distributed slice.\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&source_location_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_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "cfg_attr");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "not");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "target_arch");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::parse(&mut _s, "\"wasm32\"");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "distributed_slice");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "registry");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s,
                                "MX_SIDECAR_ACCESSORS");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "crate");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "linkme");
                            _s
                        });
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "non_upper_case_globals");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "static");
    ::quote::ToTokens::to_tokens(&const_name_accessors, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SidecarAccessorsEntry");
    ::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, "SidecarAccessorsEntry");
    ::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::ToTokens::to_tokens(&name_str, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "exported");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&exported, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "internal");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&internal, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "internal_read_only");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&internal_read_only, &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);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&sidecar_prop_entries, &mut _s);
    _s
}quote::quote! {
2635        #(#c_functions)*
2636
2637        #class_integration_wrappers
2638
2639        /// The standalone sidecar accessors, exported, internal and internal
2640        /// without setters, via distributed slice.
2641        #[doc = #source_location_doc]
2642        #[doc(hidden)]
2643        #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_SIDECAR_ACCESSORS), linkme(crate = ::miniextendr_api::linkme))]
2644        #[allow(non_upper_case_globals)]
2645        static #const_name_accessors: ::miniextendr_api::registry::SidecarAccessorsEntry =
2646            ::miniextendr_api::registry::SidecarAccessorsEntry {
2647                rust_type: #name_str,
2648                exported: #exported,
2649                internal: #internal,
2650                internal_read_only: #internal_read_only,
2651                source_file: ::core::file!(),
2652                source_line: #source_line_lit,
2653            };
2654
2655        #sidecar_prop_entries
2656    })
2657}
2658
2659/// The `Sidecar<T>` slots of a type, in protection-list order.
2660fn sidecar_slots(info: &SidecarInfo) -> impl Iterator<Item = (usize, &SidecarSlot)> {
2661    info.slots.iter().filter_map(|slot| match slot.kind {
2662        SlotKind::Sidecar(index) => Some((index, slot)),
2663        _ => None,
2664    })
2665}
2666
2667/// Generate the `TypedExternal` trait implementation for the derive target.
2668///
2669/// Produces the associated constants:
2670/// - `TYPE_NAME`: the struct name as a `&'static str`
2671/// - `TYPE_NAME_CSTR`: null-terminated byte string of the struct name
2672/// - `TYPE_ID_CSTR`: globally unique ID in the format
2673///   `"<crate_name>@<crate_version>::<module_path>::<type_name>\0"`,
2674///   using `CARGO_PKG_NAME`, `CARGO_PKG_VERSION`, and `module_path!()`.
2675/// - `R_SLOT_COUNT`: the number of `Sidecar<T>` fields, when there are any,
2676///   with the `__mx_visit_sidecars` hook that hands each of them, with its
2677///   slot index and name, to the handle (which flushes their pending values
2678///   into the slots and loads the slots back into them).
2679/// - `CACHED_FIELD_COUNT`: the number of `#[r_data(cache)]` fields, when
2680///   there are any (#2271).
2681///
2682/// Supports generic structs (generics are forwarded to the impl).
2683fn generate_typed_external(
2684    input: &DeriveInput,
2685    info: &SidecarInfo,
2686    restored: &RestoredOptions,
2687    field_error: &FieldErrorOptions,
2688    display_name: Option<&str>,
2689    snapshot: bool,
2690) -> TokenStream {
2691    let name = &input.ident;
2692    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
2693
2694    let name_str = name.to_string();
2695    let name_lit = syn::LitStr::new(&name_str, name.span());
2696    let display_name = display_name.unwrap_or(&name_str);
2697    let display_lit = syn::LitStr::new(display_name, name.span());
2698    let name_cstr = syn::LitByteStr::new(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\0", display_name))
    })format!("{display_name}\0").as_bytes(), name.span());
2699    // `#[externalptr(restored(class = ..., message = ...))]` (#1891): the
2700    // package's classes go in front of the `miniextendr_restored*` classes,
2701    // its message replaces miniextendr's, on every restored refusal of the
2702    // type (`refuse_restored`, `TypeMismatchError`).
2703    let restored_class = (!restored.class.is_empty()).then(|| {
2704        let classes = &restored.class;
2705        {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "const");
    ::quote::__private::push_ident(&mut _s, "RESTORED_ERROR_CLASS");
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::__private::push_lifetime(&mut _s, "\'static");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_lifetime(&mut _s, "\'static");
            ::quote::__private::push_ident(&mut _s, "str");
            _s
        });
    ::quote::__private::push_eq(&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 classes, i) = classes.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let classes =
                        match classes.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&classes, &mut _s);
                }
            }
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
2706            const RESTORED_ERROR_CLASS: &'static [&'static str] = &[#(#classes),*];
2707        }
2708    });
2709    let restored_message = restored.message.as_ref().map(|message| {
2710        {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "const");
    ::quote::__private::push_ident(&mut _s, "RESTORED_ERROR_MESSAGE");
    ::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, "option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Option");
    ::quote::__private::push_lt(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::__private::push_lifetime(&mut _s, "\'static");
    ::quote::__private::push_ident(&mut _s, "str");
    ::quote::__private::push_gt(&mut _s);
    ::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, "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::ToTokens::to_tokens(&message, &mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
2711            const RESTORED_ERROR_MESSAGE: ::core::option::Option<&'static str> =
2712                ::core::option::Option::Some(#message);
2713        }
2714    });
2715    // `restored(no_handle = ...)` (#2218): the message of a list or
2716    // environment of the class without a pointer.
2717    let no_handle_message = restored.no_handle.as_ref().map(|message| {
2718        {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "const");
    ::quote::__private::push_ident(&mut _s, "NO_HANDLE_MESSAGE");
    ::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, "option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Option");
    ::quote::__private::push_lt(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::__private::push_lifetime(&mut _s, "\'static");
    ::quote::__private::push_ident(&mut _s, "str");
    ::quote::__private::push_gt(&mut _s);
    ::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, "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::ToTokens::to_tokens(&message, &mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
2719            const NO_HANDLE_MESSAGE: ::core::option::Option<&'static str> =
2720                ::core::option::Option::Some(#message);
2721        }
2722    });
2723    // `#[externalptr(field_error(class = ..., message = ...))]` (#1899,
2724    // #1920): the classes in front of the R accessors' type-mismatch and
2725    // no-pointer errors, and the package's message for both.
2726    let field_error_class = (!field_error.class.is_empty()).then(|| {
2727        let classes = &field_error.class;
2728        {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "const");
    ::quote::__private::push_ident(&mut _s, "FIELD_ERROR_CLASS");
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::__private::push_lifetime(&mut _s, "\'static");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_lifetime(&mut _s, "\'static");
            ::quote::__private::push_ident(&mut _s, "str");
            _s
        });
    ::quote::__private::push_eq(&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 classes, i) = classes.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let classes =
                        match classes.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&classes, &mut _s);
                }
            }
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
2729            const FIELD_ERROR_CLASS: &'static [&'static str] = &[#(#classes),*];
2730        }
2731    });
2732    let field_error_message = field_error.message.as_ref().map(|message| {
2733        {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "const");
    ::quote::__private::push_ident(&mut _s, "FIELD_ERROR_MESSAGE");
    ::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, "option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Option");
    ::quote::__private::push_lt(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::__private::push_lifetime(&mut _s, "\'static");
    ::quote::__private::push_ident(&mut _s, "str");
    ::quote::__private::push_gt(&mut _s);
    ::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, "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::ToTokens::to_tokens(&message, &mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
2734            const FIELD_ERROR_MESSAGE: ::core::option::Option<&'static str> =
2735                ::core::option::Option::Some(#message);
2736        }
2737    });
2738    // A type that is `Serialize + DeserializeOwned` comes back after
2739    // `readRDS()` (#2186). The probe resolves here, in the type's own impl,
2740    // where the type is concrete (the derive takes no generic struct): to the
2741    // serde arm when both traits hold (with miniextendr-api's `serde`
2742    // feature), else to the fallback. A hand-written `TypedExternal` impl
2743    // keeps the trait's default (`None`).
2744    let snapshot = snapshot.then(|| {
2745        {
    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, "inline");
            _s
        });
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::__private::push_ident(&mut _s, "__mx_snapshot");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_rarrow(&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_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, "externalptr");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Snapshot");
    ::quote::__private::push_lt(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Self");
    ::quote::__private::push_shr(&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, "static");
            ::quote::__private::push_ident(&mut _s, "CLASS");
            ::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, "externalptr");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SnapshotClass");
            ::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, "SnapshotClass");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "new");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::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, "allow");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "unused_imports");
                            _s
                        });
                    _s
                });
            ::quote::__private::push_ident(&mut _s, "use");
            ::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_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "SnapshotNone");
                    ::quote::__private::push_ident(&mut _s, "as");
                    ::quote::__private::push_underscore(&mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "SnapshotSerde");
                    ::quote::__private::push_ident(&mut _s, "as");
                    ::quote::__private::push_underscore(&mut _s);
                    _s
                });
            ::quote::__private::push_semi(&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_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, "SnapshotProbe");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_lt(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "Self");
                    ::quote::__private::push_gt(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "new");
                    ::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, "CLASS");
                            _s
                        });
                    _s
                });
            ::quote::__private::push_dot(&mut _s);
            ::quote::__private::push_ident(&mut _s, "__mx_snapshot");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            _s
        });
    _s
}quote::quote! {
2746            #[inline]
2747            fn __mx_snapshot() -> ::core::option::Option<::miniextendr_api::externalptr::Snapshot<Self>> {
2748                static CLASS: ::miniextendr_api::externalptr::SnapshotClass =
2749                    ::miniextendr_api::externalptr::SnapshotClass::new();
2750                #[allow(unused_imports)]
2751                use ::miniextendr_api::externalptr::{SnapshotNone as _, SnapshotSerde as _};
2752                (&::miniextendr_api::externalptr::SnapshotProbe::<Self>::new(&CLASS)).__mx_snapshot()
2753            }
2754        }
2755    });
2756    // `#[r_data(cache)]` fields (#2271): every exclusive borrow of the value
2757    // drops their kept values, and the pointer's finalizer drops them too.
2758    let cached_field_count = {
2759        let count = info
2760            .slots
2761            .iter()
2762            .filter(|slot| slot.cache.is_some())
2763            .count();
2764        (count > 0).then(|| {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "const");
    ::quote::__private::push_ident(&mut _s, "CACHED_FIELD_COUNT");
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_ident(&mut _s, "usize");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&count, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! { const CACHED_FIELD_COUNT: usize = #count; })
2765    };
2766    let sidecars: Vec<_> = sidecar_slots(info).collect();
2767    // A save names its slots by the fields' R names (#2215), so renaming a
2768    // Rust field keeps every earlier save readable.
2769    let r_slot_count = (!sidecars.is_empty()).then(|| {
2770        let count = sidecars.len();
2771        let names = sidecars.iter().map(|&(_, slot)| slot.r_name.as_str());
2772        let visits = sidecars.iter().map(|&(index, slot)| {
2773            let field = &slot.name;
2774            let r_name = slot.r_name.as_str();
2775            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "visit");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&index, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&r_name, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_ident(&mut _s, "self");
            ::quote::__private::push_dot(&mut _s);
            ::quote::ToTokens::to_tokens(&field, &mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! { visit(#index, #r_name, &self.#field); }
2776        });
2777        {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "const");
    ::quote::__private::push_ident(&mut _s, "R_SLOT_COUNT");
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_ident(&mut _s, "usize");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&count, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "const");
    ::quote::__private::push_ident(&mut _s, "SIDECAR_NAMES");
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_and(&mut _s);
    ::quote::__private::push_lifetime(&mut _s, "\'static");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_lifetime(&mut _s, "\'static");
            ::quote::__private::push_ident(&mut _s, "str");
            _s
        });
    ::quote::__private::push_eq(&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 names, i) = names.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let names =
                        match names.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&names, &mut _s);
                }
            }
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::__private::push_ident(&mut _s, "__mx_visit_sidecars");
    ::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");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "visit");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_ident(&mut _s, "mut");
            ::quote::__private::push_ident(&mut _s, "dyn");
            ::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, "ops");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "FnMut");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "usize");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_and(&mut _s);
                    ::quote::__private::push_lifetime(&mut _s, "\'static");
                    ::quote::__private::push_ident(&mut _s, "str");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_and(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "dyn");
                    ::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, "SidecarField");
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::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 visits, i) = visits.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let visits =
                        match visits.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    ::quote::ToTokens::to_tokens(&visits, &mut _s);
                }
            }
            _s
        });
    _s
}quote::quote! {
2778            const R_SLOT_COUNT: usize = #count;
2779            const SIDECAR_NAMES: &'static [&'static str] = &[#(#names),*];
2780
2781            fn __mx_visit_sidecars(
2782                &self,
2783                visit: &mut dyn ::core::ops::FnMut(usize, &'static str, &dyn ::miniextendr_api::externalptr::SidecarField),
2784            ) {
2785                #(#visits)*
2786            }
2787        }
2788    });
2789
2790    // TYPE_ID_CSTR format: "<crate_name>@<crate_version>::<module_path>::<type_name>\0"
2791    //
2792    // Uses env!("CARGO_PKG_NAME") and env!("CARGO_PKG_VERSION") for the crate identifier,
2793    // ensuring two packages with the same type name from the same crate+version are compatible,
2794    // while different crate versions are considered distinct types.
2795    //
2796    // The module_path!() may include "crate::" prefix when compiled within the crate,
2797    // but combined with the explicit crate@version prefix, this is unambiguous.
2798    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::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, "externalptr");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "TypedExternal");
    ::quote::__private::push_ident(&mut _s, "for");
    ::quote::ToTokens::to_tokens(&name, &mut _s);
    ::quote::ToTokens::to_tokens(&ty_generics, &mut _s);
    ::quote::ToTokens::to_tokens(&where_clause, &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, "const");
            ::quote::__private::push_ident(&mut _s, "TYPE_NAME");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_lifetime(&mut _s, "\'static");
            ::quote::__private::push_ident(&mut _s, "str");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&display_lit, &mut _s);
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "const");
            ::quote::__private::push_ident(&mut _s, "TYPE_NAME_CSTR");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_lifetime(&mut _s, "\'static");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "u8");
                    _s
                });
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&name_cstr, &mut _s);
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "const");
            ::quote::__private::push_ident(&mut _s, "TYPE_ID_CSTR");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_lifetime(&mut _s, "\'static");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "u8");
                    _s
                });
            ::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::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "env");
                    ::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, "\"CARGO_PKG_NAME\"");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"@\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "env");
                    ::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, "\"CARGO_PKG_VERSION\"");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"::\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "module_path");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"::\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&name_lit, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"\\0\"");
                    _s
                });
            ::quote::__private::push_dot(&mut _s);
            ::quote::__private::push_ident(&mut _s, "as_bytes");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_semi(&mut _s);
            ::quote::ToTokens::to_tokens(&r_slot_count, &mut _s);
            ::quote::ToTokens::to_tokens(&cached_field_count, &mut _s);
            ::quote::ToTokens::to_tokens(&restored_class, &mut _s);
            ::quote::ToTokens::to_tokens(&restored_message, &mut _s);
            ::quote::ToTokens::to_tokens(&no_handle_message, &mut _s);
            ::quote::ToTokens::to_tokens(&field_error_class, &mut _s);
            ::quote::ToTokens::to_tokens(&field_error_message, &mut _s);
            ::quote::ToTokens::to_tokens(&snapshot, &mut _s);
            _s
        });
    _s
}quote::quote! {
2799        impl #impl_generics ::miniextendr_api::externalptr::TypedExternal for #name #ty_generics #where_clause {
2800            const TYPE_NAME: &'static str = #display_lit;
2801            const TYPE_NAME_CSTR: &'static [u8] = #name_cstr;
2802            const TYPE_ID_CSTR: &'static [u8] =
2803                ::core::concat!(
2804                    ::core::env!("CARGO_PKG_NAME"), "@", ::core::env!("CARGO_PKG_VERSION"),
2805                    "::", ::core::module_path!(), "::", #name_lit, "\0"
2806                ).as_bytes();
2807            #r_slot_count
2808            #cached_field_count
2809            #restored_class
2810            #restored_message
2811            #no_handle_message
2812            #field_error_class
2813            #field_error_message
2814            #snapshot
2815        }
2816    }
2817}
2818
2819/// ALTREP stores its owner in an ordinary ExternalPtr, so it needs the same
2820/// slot visitor and handle accessors. Only storage is generated here: ALTREP
2821/// has its own IntoR and registration, and isn't an R class with field methods.
2822pub(crate) fn generate_altrep_storage(
2823    input: &DeriveInput,
2824    class_name: &str,
2825) -> syn::Result<TokenStream> {
2826    if let syn::Data::Struct(data) = &input.data {
2827        for field in &data.fields {
2828            for attr in field.attrs.iter().filter(|a| a.path().is_ident("r_data")) {
2829                if sidecar_inner_type(&field.ty).is_none() {
2830                    return Err(syn::Error::new_spanned(
2831                        field,
2832                        "ALTREP #[r_data] fields must be Sidecar<T>; R field accessors belong to ExternalPtr classes",
2833                    ));
2834                }
2835                if #[allow(non_exhaustive_omitted_patterns)] match &attr.meta {
    syn::Meta::List(_) => true,
    _ => false,
}matches!(&attr.meta, syn::Meta::List(_)) {
2836                    attr.parse_nested_meta(|meta| {
2837                        if meta.path.is_ident("ref") || meta.path.is_ident("mut") {
2838                            Ok(())
2839                        } else {
2840                            Err(meta.error("ALTREP sidecars support only `ref` and `mut` access; they have no R field wrappers"))
2841                        }
2842                    })?;
2843                }
2844            }
2845        }
2846    }
2847    let info = parse_sidecar_info(input, ClassSystem::Env)?;
2848    let storage = generate_typed_external(
2849        input,
2850        &info,
2851        &RestoredOptions::default(),
2852        &FieldErrorOptions::default(),
2853        Some(class_name),
2854        // R never saves an ALTREP's data1 pointer: no carrier.
2855        false,
2856    );
2857    let accessors = generate_sidecar_rust_accessors(input, &info);
2858    Ok({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&storage, &mut _s);
    ::quote::ToTokens::to_tokens(&accessors, &mut _s);
    _s
}quote::quote! { #storage #accessors })
2859}
2860
2861/// Generate the Rust accessors of each `Sidecar<T>` field, as associated
2862/// functions of the struct taking an owner handle, with the field's visibility:
2863/// `fn keys(ptr: &impl SidecarOwner<Self>) -> T` for `#[r_data(ref)]`,
2864/// `fn set_keys(ptr: &mut impl SidecarOwnerMut<Self>, value: T)` for `#[r_data(mut)]`,
2865/// both for `#[r_data(ref, mut)]` or a bare `#[r_data]`. The struct holds no
2866/// reference to its pointer, so there is no accessor on `&self` (#1856).
2867///
2868/// A non-`pub` accessor is `#[allow(dead_code)]`: it is generated whether or
2869/// not the crate calls it. The accessors (and the `TypedExternal` hook) read
2870/// the fields, so rustc sees them used.
2871fn generate_sidecar_rust_accessors(input: &DeriveInput, info: &SidecarInfo) -> TokenStream {
2872    let methods: Vec<TokenStream> = sidecar_slots(info)
2873        .flat_map(|(index, slot)| {
2874            let inner = sidecar_inner_type(&slot.ty).expect("a Sidecar slot has an inner type");
2875            let field = &slot.name;
2876            let field_name = crate::naming::ident_name(field);
2877            // The accessors are named by the Rust field; the save, and the
2878            // messages R users read, by its R name (#2215).
2879            let r_name = slot.r_name.as_str();
2880            let vis = &slot.vis;
2881            let allow = (!#[allow(non_exhaustive_omitted_patterns)] match vis {
    Visibility::Public(_) => true,
    _ => false,
}matches!(vis, Visibility::Public(_)))
2882                .then(|| {
    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
        });
    _s
}quote::quote! { #[allow(dead_code)] });
2883            let mut methods = Vec::with_capacity(3);
2884            if slot.access.get {
2885                let doc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("The value of the `{0}` sidecar field of the object `ptr` holds: the R value the external pointer keeps, converted to its Rust type (a copy for a converting type), after moving a pending value into the pointer. On R\'s main thread.",
                field_name))
    })format!(
2886                    "The value of the `{field_name}` sidecar field of the object `ptr` holds: \
2887                     the R value the external pointer keeps, converted to its Rust type (a copy \
2888                     for a converting type), after moving a pending value into the pointer. On \
2889                     R's main thread."
2890                );
2891                methods.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&doc, &mut _s);
            _s
        });
    ::quote::ToTokens::to_tokens(&allow, &mut _s);
    ::quote::ToTokens::to_tokens(&vis, &mut _s);
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::ToTokens::to_tokens(&field, &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, "ptr");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_and(&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, "externalptr");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SidecarOwner");
            ::quote::__private::push_lt(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Self");
            ::quote::__private::push_gt(&mut _s);
            _s
        });
    ::quote::__private::push_rarrow(&mut _s);
    ::quote::ToTokens::to_tokens(&inner, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "externalptr");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "sidecar_get");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_lt(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Self");
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&inner, &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, "ptr");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&index, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&r_name, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_or(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "this");
                    ::quote::__private::push_colon(&mut _s);
                    ::quote::__private::push_and(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "Self");
                    ::quote::__private::push_or(&mut _s);
                    ::quote::__private::push_and(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "this");
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::ToTokens::to_tokens(&field, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            _s
        });
    _s
}quote::quote! {
2892                    #[doc = #doc]
2893                    #allow
2894                    #vis fn #field(ptr: &impl ::miniextendr_api::externalptr::SidecarOwner<Self>) -> #inner {
2895                        ::miniextendr_api::externalptr::sidecar_get::<Self, #inner>(
2896                            ptr, #index, #r_name, |this: &Self| &this.#field,
2897                        )
2898                    }
2899                });
2900            }
2901            if slot.access.set {
2902                let setter = match ::quote::__private::IdentFragmentAdapter(&field_name) {
    arg =>
        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("set_{0}", arg))
                    }), ::quote::__private::Option::None.or(arg.span())),
}quote::format_ident!("set_{}", field_name);
2903                let doc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Stores `value` in the `{0}` sidecar field of the object `ptr` holds: in the external pointer\'s protection list, dropping a pending value. On R\'s main thread.",
                field_name))
    })format!(
2904                    "Stores `value` in the `{field_name}` sidecar field of the object `ptr` \
2905                     holds: in the external pointer's protection list, dropping a pending value. \
2906                     On R's main thread."
2907                );
2908                methods.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&doc, &mut _s);
            _s
        });
    ::quote::ToTokens::to_tokens(&allow, &mut _s);
    ::quote::ToTokens::to_tokens(&vis, &mut _s);
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::ToTokens::to_tokens(&setter, &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, "ptr");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_ident(&mut _s, "mut");
            ::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, "externalptr");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SidecarOwnerMut");
            ::quote::__private::push_lt(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Self");
            ::quote::__private::push_gt(&mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "value");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&inner, &mut _s);
            _s
        });
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "externalptr");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "sidecar_set");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_lt(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Self");
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&inner, &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, "ptr");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&index, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&r_name, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_or(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "this");
                    ::quote::__private::push_colon(&mut _s);
                    ::quote::__private::push_and(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "Self");
                    ::quote::__private::push_or(&mut _s);
                    ::quote::__private::push_and(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "this");
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::ToTokens::to_tokens(&field, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "value");
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            _s
        });
    _s
}quote::quote! {
2909                    #[doc = #doc]
2910                    #allow
2911                    #vis fn #setter(ptr: &mut impl ::miniextendr_api::externalptr::SidecarOwnerMut<Self>, value: #inner) {
2912                        ::miniextendr_api::externalptr::sidecar_set::<Self, #inner>(
2913                            ptr, #index, #r_name, |this: &Self| &this.#field, value,
2914                        )
2915                    }
2916                });
2917            }
2918            methods
2919        })
2920        .collect();
2921    if methods.is_empty() {
2922        return TokenStream::new();
2923    }
2924    let name = &input.ident;
2925    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
2926    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "impl");
    ::quote::ToTokens::to_tokens(&impl_generics, &mut _s);
    ::quote::ToTokens::to_tokens(&name, &mut _s);
    ::quote::ToTokens::to_tokens(&ty_generics, &mut _s);
    ::quote::ToTokens::to_tokens(&where_clause, &mut _s);
    ::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 methods, i) = methods.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let methods =
                        match methods.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    ::quote::ToTokens::to_tokens(&methods, &mut _s);
                }
            }
            _s
        });
    _s
}quote::quote! {
2927        impl #impl_generics #name #ty_generics #where_clause {
2928            #(#methods)*
2929        }
2930    }
2931}
2932
2933/// Generate the `IntoExternalPtr` marker trait impl.
2934///
2935/// This marker trait enables the blanket `impl<T: IntoExternalPtr> IntoR for T`
2936/// in miniextendr-api, allowing the type to be returned directly from functions.
2937fn generate_into_external_ptr(input: &DeriveInput) -> TokenStream {
2938    let name = &input.ident;
2939    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
2940
2941    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::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, "externalptr");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "IntoExternalPtr");
    ::quote::__private::push_ident(&mut _s, "for");
    ::quote::ToTokens::to_tokens(&name, &mut _s);
    ::quote::ToTokens::to_tokens(&ty_generics, &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::quote! {
2942        impl #impl_generics ::miniextendr_api::externalptr::IntoExternalPtr for #name #ty_generics #where_clause {}
2943    }
2944}
2945
2946/// Generate the concrete `IntoRVecElement` impl (issue #1284).
2947///
2948/// Lights up the single `impl<T: IntoRVecElement> IntoR for Vec<T>` blanket in
2949/// miniextendr-api, so `-> Vec<MyType>` returns compile and produce a `VECSXP`
2950/// of external pointers. The impl must be concrete (not a blanket over
2951/// `IntoExternalPtr`) because the `MatchArg` bridge already occupies a blanket
2952/// on `IntoRVecElement` and two blankets would collide (E0119) — the same
2953/// funnel design `#[derive(IntoR)]` newtypes use (see
2954/// `miniextendr_api::newtype` module docs).
2955///
2956/// GC discipline: `ExternalPtr::collect_into_r_list` allocates each
2957/// `EXTPTRSXP` directly into the already-protected destination list, so no
2958/// element is ever live-but-unrooted across a later allocation.
2959fn generate_into_r_vec_element(input: &DeriveInput) -> TokenStream {
2960    let name = &input.ident;
2961    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
2962
2963    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::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, "IntoRVecElement");
    ::quote::__private::push_ident(&mut _s, "for");
    ::quote::ToTokens::to_tokens(&name, &mut _s);
    ::quote::ToTokens::to_tokens(&ty_generics, &mut _s);
    ::quote::ToTokens::to_tokens(&where_clause, &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, "inline");
                    _s
                });
            ::quote::__private::push_ident(&mut _s, "fn");
            ::quote::__private::push_ident(&mut _s, "elements_into_sexp");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "values");
                    ::quote::__private::push_colon(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "std");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "vec");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "Vec");
                    ::quote::__private::push_lt(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "Self");
                    ::quote::__private::push_gt(&mut _s);
                    _s
                });
            ::quote::__private::push_rarrow(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "externalptr");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "ExternalPtr");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_lt(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "Self");
                    ::quote::__private::push_gt(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "collect_into_r_list");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "values");
                            _s
                        });
                    _s
                });
            _s
        });
    _s
}quote::quote! {
2964        impl #impl_generics ::miniextendr_api::IntoRVecElement for #name #ty_generics #where_clause {
2965            #[inline]
2966            fn elements_into_sexp(values: ::std::vec::Vec<Self>) -> ::miniextendr_api::SEXP {
2967                ::miniextendr_api::externalptr::ExternalPtr::<Self>::collect_into_r_list(values)
2968            }
2969        }
2970    }
2971}
2972
2973/// Main entry point for `#[derive(ExternalPtr)]`.
2974///
2975/// Orchestrates the full derive expansion:
2976/// 1. Parses `#[externalptr(...)]` attributes for class system selection.
2977/// 2. Analyzes struct fields for `#[r_data]` sidecar slots.
2978/// 3. Generates `TypedExternal` impl (type identity for `ExternalPtr<T>`).
2979/// 4. Generates `IntoExternalPtr` marker impl (enables `IntoR` blanket impl)
2980///    and a concrete `IntoRVecElement` impl (enables the `IntoR for Vec<T>`
2981///    blanket, so `-> Vec<MyType>` returns a `VECSXP` of external pointers —
2982///    #1284). Both are suppressed when `emit_into_r_marker` is `false`, which
2983///    the struct-level `#[miniextendr(prefer = "native")]` path uses so its
2984///    concrete `AsRNative` `IntoR` does not collide with the blanket
2985///    `IntoExternalPtr` `IntoR` (E0119, #1283).
2986/// 5. Generates sidecar accessor FFI functions, registration constants, and R wrappers.
2987///
2988/// Returns the combined token stream of all generated items.
2989pub fn derive_external_ptr(
2990    input: DeriveInput,
2991    emit_into_r_marker: bool,
2992) -> syn::Result<TokenStream> {
2993    // Parse the class system and the restored refusal's classes / message
2994    // from the #[externalptr(...)] attribute
2995    let ExternalPtrAttrs {
2996        class_system,
2997        restored,
2998        field_error,
2999    } = parse_externalptr_attrs(&input)?;
3000
3001    // Parse sidecar information from struct fields
3002    let sidecar_info = parse_sidecar_info(&input, class_system)?;
3003
3004    let typed_external =
3005        generate_typed_external(&input, &sidecar_info, &restored, &field_error, None, true);
3006    let snapshot_registration = generate_snapshot_registration(&input);
3007    let sidecar_rust_accessors = generate_sidecar_rust_accessors(&input, &sidecar_info);
3008    let (into_external_ptr, into_r_vec_element) = if emit_into_r_marker {
3009        (
3010            generate_into_external_ptr(&input),
3011            generate_into_r_vec_element(&input),
3012        )
3013    } else {
3014        (
3015            proc_macro2::TokenStream::new(),
3016            proc_macro2::TokenStream::new(),
3017        )
3018    };
3019    let sidecar_accessors =
3020        generate_sidecar_accessors(&input, &sidecar_info, &restored, &field_error)?;
3021    let erased_wrapper = generate_erased_wrapper(&input);
3022
3023    Ok({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&typed_external, &mut _s);
    ::quote::ToTokens::to_tokens(&snapshot_registration, &mut _s);
    ::quote::ToTokens::to_tokens(&sidecar_rust_accessors, &mut _s);
    ::quote::ToTokens::to_tokens(&into_external_ptr, &mut _s);
    ::quote::ToTokens::to_tokens(&into_r_vec_element, &mut _s);
    ::quote::ToTokens::to_tokens(&sidecar_accessors, &mut _s);
    ::quote::ToTokens::to_tokens(&erased_wrapper, &mut _s);
    _s
}quote::quote! {
3024        #typed_external
3025        #snapshot_registration
3026        #sidecar_rust_accessors
3027        #into_external_ptr
3028        #into_r_vec_element
3029        #sidecar_accessors
3030        #erased_wrapper
3031    })
3032}
3033
3034/// Generate the `R_init` registration of the type's carrier class (#2186): a
3035/// `#[no_mangle]` function and its `MX_ALTREP_REGISTRATIONS` entry, which
3036/// the wasm registry lists by symbol. The derive can't tell whether the type
3037/// is serde, so every type gets one; it registers the class only when the
3038/// type's snapshot probe found serde.
3039fn generate_snapshot_registration(input: &DeriveInput) -> TokenStream {
3040    let ident = &input.ident;
3041    let reg_fn_name = crate::naming::snapshot_reg_fn_ident(ident);
3042    let entry_ident =
3043        match ::quote::__private::IdentFragmentAdapter(&crate::naming::unraw(ident)) {
    arg =>
        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("__MX_SNAPSHOT_REG_ENTRY_{0}",
                                arg))
                    }), ::quote::__private::Option::None.or(arg.span())),
}quote::format_ident!("__MX_SNAPSHOT_REG_ENTRY_{}", crate::naming::unraw(ident));
3044    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "no_mangle");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "non_snake_case");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "pub");
    ::quote::__private::push_ident(&mut _s, "extern");
    ::quote::__private::parse(&mut _s, "\"C-unwind\"");
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::ToTokens::to_tokens(&reg_fn_name, &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, "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, "__mx_register_snapshot");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_lt(&mut _s);
            ::quote::ToTokens::to_tokens(&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_semi(&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, "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_ALTREP_REGISTRATIONS");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "crate");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "linkme");
                            _s
                        });
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "non_upper_case_globals");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "static");
    ::quote::ToTokens::to_tokens(&entry_ident, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "AltrepRegistration");
    ::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, "AltrepRegistration");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "register");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&reg_fn_name, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "symbol");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "stringify");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::ToTokens::to_tokens(&reg_fn_name, &mut _s);
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote::quote! {
3045        #[doc(hidden)]
3046        #[unsafe(no_mangle)]
3047        #[allow(non_snake_case)]
3048        pub extern "C-unwind" fn #reg_fn_name() {
3049            ::miniextendr_api::externalptr::__mx_register_snapshot::<#ident>();
3050        }
3051
3052        #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_ALTREP_REGISTRATIONS), linkme(crate = ::miniextendr_api::linkme))]
3053        #[doc(hidden)]
3054        #[allow(non_upper_case_globals)]
3055        static #entry_ident: ::miniextendr_api::registry::AltrepRegistration =
3056            ::miniextendr_api::registry::AltrepRegistration {
3057                register: #reg_fn_name,
3058                symbol: ::core::stringify!(#reg_fn_name),
3059            };
3060    }
3061}
3062
3063/// Generate the type-erased wrapper infrastructure for trait ABI dispatch.
3064///
3065/// For `#[derive(ExternalPtr)] struct MyCounter { ... }` generates:
3066/// - `__MX_TAG_MyCounter` - concrete type tag (FNV-1a hash of module_path + type)
3067/// - `__MX_BASE_VTABLE_MyCounter` - base vtable with trait/sidecar query
3068/// - `__mx_wrap_MyCounter` - constructor returning `*mut mx_erased`
3069fn generate_erased_wrapper(input: &DeriveInput) -> TokenStream {
3070    let type_ident = &input.ident;
3071
3072    // Only for non-generic types (generics can't participate in trait dispatch)
3073    if !input.generics.params.is_empty() {
3074        return ::quote::__private::TokenStream::new()quote::quote! {};
3075    }
3076
3077    // Preserve case: distinct Rust types need distinct module-local helpers.
3078    let type_name = crate::naming::unraw(type_ident);
3079
3080    let base_vtable_name = match ::quote::__private::IdentFragmentAdapter(&type_name) {
    arg =>
        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("__MX_BASE_VTABLE_{0}",
                                arg))
                    }), ::quote::__private::Option::None.or(arg.span())),
}quote::format_ident!("__MX_BASE_VTABLE_{}", type_name);
3081    let concrete_tag_name = match ::quote::__private::IdentFragmentAdapter(&type_name) {
    arg =>
        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("__MX_TAG_{0}", arg))
                    }), ::quote::__private::Option::None.or(arg.span())),
}quote::format_ident!("__MX_TAG_{}", type_name);
3082    let wrap_fn_name = match ::quote::__private::IdentFragmentAdapter(&type_name) {
    arg =>
        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("__mx_wrap_{0}", arg))
                    }), ::quote::__private::Option::None.or(arg.span())),
}quote::format_ident!("__mx_wrap_{}", type_name);
3083    let source_loc_doc = crate::source_location_doc(type_ident.span());
3084    let tag_path = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("::{0}", type_ident))
    })format!("::{}", type_ident);
3085
3086    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "non_upper_case_globals");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "const");
    ::quote::ToTokens::to_tokens(&concrete_tag_name, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "abi");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "mx_tag");
    ::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, "abi");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "mx_tag_from_path");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "module_path");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&tag_path, &mut _s);
                    _s
                });
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "non_upper_case_globals");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "static");
    ::quote::ToTokens::to_tokens(&base_vtable_name, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "abi");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "mx_base_vtable");
    ::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, "abi");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "mx_base_vtable");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "drop");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "abi");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "ErasedObject");
            ::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, "drop_raw");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concrete_tag");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&concrete_tag_name, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "query");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "abi");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "ErasedObject");
            ::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, "query");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "data_offset");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "abi");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "ErasedObject");
            ::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, "DATA_OFFSET");
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "hidden");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "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, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "non_snake_case");
                    _s
                });
            _s
        });
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::ToTokens::to_tokens(&wrap_fn_name, &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, "data");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
            _s
        });
    ::quote::__private::push_rarrow(&mut _s);
    ::quote::__private::push_star(&mut _s);
    ::quote::__private::push_ident(&mut _s, "mut");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "abi");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "mx_erased");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::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, "abi");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "ErasedObject");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "into_raw");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "data");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_and(&mut _s);
                            ::quote::ToTokens::to_tokens(&base_vtable_name, &mut _s);
                            _s
                        });
                    _s
                });
            _s
        });
    _s
}quote::quote! {
3087        #[doc(hidden)]
3088        #[allow(non_upper_case_globals)]
3089        const #concrete_tag_name: ::miniextendr_api::abi::mx_tag =
3090            ::miniextendr_api::abi::mx_tag_from_path(::core::concat!(::core::module_path!(), #tag_path));
3091
3092        #[doc(hidden)]
3093        #[allow(non_upper_case_globals)]
3094        static #base_vtable_name: ::miniextendr_api::abi::mx_base_vtable =
3095            ::miniextendr_api::abi::mx_base_vtable {
3096                drop: ::miniextendr_api::abi::ErasedObject::<#type_ident>::drop_raw,
3097                concrete_tag: #concrete_tag_name,
3098                query: ::miniextendr_api::abi::ErasedObject::<#type_ident>::query,
3099                data_offset: ::miniextendr_api::abi::ErasedObject::<#type_ident>::DATA_OFFSET,
3100            };
3101
3102        #[doc(hidden)]
3103        #[doc = #source_loc_doc]
3104        #[allow(non_snake_case)]
3105        fn #wrap_fn_name(data: #type_ident) -> *mut ::miniextendr_api::abi::mx_erased {
3106            // SAFETY: the matching base vtable above uses this storage's
3107            // destructor/offset and this concrete type's registry tag.
3108            unsafe {
3109                ::miniextendr_api::abi::ErasedObject::into_raw(data, &#base_vtable_name)
3110            }
3111        }
3112    }
3113}
3114
3115#[cfg(test)]
3116mod tests;