Skip to main content

miniextendr_macros/miniextendr_impl/
field_syntax.rs

1//! `$` / `[[` field syntax for the `#[r_data]` fields of S3, S4 and env
2//! classes: `s3(r_data_accessors)`, `s4(r_data_accessors)`,
3//! `env(r_data_accessors)`, their getters-only form
4//! `r_data_accessors = "get"` (#1848), and their read-only form
5//! `r_data_accessors = "read_only"`, whose `$<-` / `[[<-` refuse every field
6//! with `miniextendr_read_only_field` (#2268).
7//!
8//! The methods call the helpers `#[derive(ExternalPtr)]` emits for the type
9//! (`.rdata_fields_T`, `.rdata_get_T`, `.rdata_set_T`, `.rdata_no_field_T`,
10//! `.rdata_read_only_T`, see
11//! `externalptr_derive::generate_field_syntax_helpers`), which call the
12//! per-field `.Call()` accessors. Those carry no call slot (#344, #348), so
13//! each method raises a tagged condition value with its own frame as the
14//! fallback (`environment()`), which `.miniextendr_frame_call` turns into the
15//! generic's call: `x$keys`, `x$keys <- value` (#1851).
16//!
17//! No reader matches a prefix of a name (#1922). On an S3 bare pointer `$`
18//! and `[[` take an exact field name, and `[[` also a whole-number position
19//! in the field order (`subscriptOutOfBoundsError` past the last field,
20//! through the preamble's `.miniextendr_field_at`); an unknown name raises
21//! `miniextendr_no_field` there, as a write does (#1921).
22//! `s3(r_data_accessors, lookup = "list")` keeps a list's other lenience
23//! (#1891): an unknown name or `NA` reads `NULL`, and `[[` takes a logical
24//! or a fractional position (truncated) as a list's does. In both, a `[[`
25//! index that is neither one name nor one position raises the preamble's
26//! `.miniextendr_field_index_error` (the type's `field_error` classes, then
27//! `notSubsettableError`, on the user's call) instead of reaching
28//! `[[.default` (#1920). The S3 class also gets `names()` (the field names),
29//! `as.list()` (every field, in order, `NULL` fields kept; #1890) and
30//! `.DollarNames()` (#1885), and S4 and env classes `.DollarNames()`. A name
31//! that is not a field falls through on a list or an environment receiver,
32//! by the exact name: `$` reads a list's element with `.subset2()` (R's `$`
33//! on a list matches a prefix) and an environment's through `NextMethod()`,
34//! `[[` and the writes go to R's own `[[` (with `exact = TRUE`) / `$<-` /
35//! `[[<-`, as do `names()` and `as.list()` there (`as.list.environment()`
36//! by name on an environment, whose class attribute would send
37//! `NextMethod()` to the default method, which can't coerce one). The writes
38//! raise `miniextendr_no_field`, naming the R class and its fields, on a bare
39//! pointer (an S3 or env object), as `$` does on an S4 object, which have
40//! nothing to fall through to. A `[[<-` index that is not a name falls
41//! through. Under `restored(refuse = "every_read")` every S3 reader first
42//! checks a pointer, list or environment receiver (#1901, #1919): a restored
43//! pointer and a list or environment without one are refused before the
44//! index is looked at. Every replacement method puts `value` last and
45//! returns the object (#1853).
46//!
47//! The S3 `[[`, `as.list()` and `[[<-` take `...` because their generics
48//! do, and read none of it on a bare pointer, so there they refuse every
49//! argument in it (#2174) with `dots = empty`'s check (`dots_policy`), on
50//! the generic's call, with the formal each one most likely meant and the
51//! type's `field_error` classes in front: `x[["data", exatc = TRUE]]`,
52//! `x[[1, 2]]`, `as.list(x, all.names = TRUE)`, `x[["data", 2]] <- v`. `[[`
53//! takes `exact` as a formal after `...`, as `[[.data.frame` does, so
54//! `exact = FALSE` is no extra argument; field names match exactly whatever
55//! it says. A list or environment receiver hands its dots on, as before. An
56//! env class's `[[` (`env_class.rs`) takes `exact` the same way and refuses
57//! the rest on every receiver, since nothing reads its dots.
58//!
59//! A field fallback (`fallback = "Self::f"`, #2150; see
60//! `miniextendr_impl::FieldFallback`) answers the names no field has
61//! on the bare pointer, through a `.Call` entry the impl block emits
62//! (`fallback_c_entries`): `$` and `[[` by name on an S3 object, `$` on an
63//! S4 object, and `$` / `[[` on an env object after its methods. The
64//! fallback's `None` reads what an unknown name reads without it. Fields win,
65//! a position counts the fields only, `names()`, `as.list()` and the writes
66//! don't see it, and a list or environment receiver keeps its own elements
67//! for those names. With `fallback_names = "Self::g"`, `.DollarNames()`
68//! offers the fallback's names after the fields (and an env class's
69//! methods).
70//!
71//! `.DollarNames()` is registered with `@exportS3Method utils::.DollarNames`
72//! (`S3method(utils::.DollarNames, Class)`): the `@method` + `@export` pair
73//! writes an unqualified `S3method(.DollarNames, Class)`, which fails to load
74//! with only base attached (`R CMD check` loads a namespace that way). S4
75//! takes the same S3 method, which `utils` dispatches on the S4 class.
76
77use super::{ClassSystem, FieldLookup, ParsedImpl};
78use crate::naming::{RDataHelper, rdata_helper_name};
79
80/// The names of the type's field helpers.
81struct Helpers {
82    fields: String,
83    get: String,
84    set: String,
85    no_field: String,
86    /// The `miniextendr_read_only_field` refusal (#2268), which the writers
87    /// of `r_data_accessors = "read_only"` call for every field.
88    read_only: String,
89    /// The classes in front of the methods' own errors (#1899), `NULL`
90    /// without `field_error(...)`.
91    error_class: String,
92    /// `TRUE` under `restored(refuse = "every_read")` (#1901): it gates the
93    /// calls of `live`.
94    every_read: String,
95    /// The liveness check of `restored(refuse = "every_read")` (#1901), a
96    /// stub that is never called without it.
97    live: String,
98    /// The `.Call` entry of the impl's `fallback = "..."` (#2150), for a
99    /// name no field has ([`fallback_c_entries`]).
100    fallback: Option<String>,
101    /// The `.Call` entry of its `fallback_names = "..."`, for
102    /// `.DollarNames()`.
103    fallback_names: Option<String>,
104}
105
106impl Helpers {
107    fn new(parsed_impl: &ParsedImpl) -> Self {
108        let type_name = parsed_impl.type_ident.to_string();
109        Helpers {
110            fields: rdata_helper_name(RDataHelper::Fields, &type_name),
111            get: rdata_helper_name(RDataHelper::Get, &type_name),
112            set: rdata_helper_name(RDataHelper::Set, &type_name),
113            no_field: rdata_helper_name(RDataHelper::NoField, &type_name),
114            read_only: rdata_helper_name(RDataHelper::ReadOnly, &type_name),
115            error_class: rdata_helper_name(RDataHelper::ErrorClass, &type_name),
116            every_read: rdata_helper_name(RDataHelper::EveryRead, &type_name),
117            live: rdata_helper_name(RDataHelper::Live, &type_name),
118            fallback: parsed_impl
119                .field_fallback
120                .as_ref()
121                .map(|_| crate::naming::sidecar_fallback_c_name(&type_name)),
122            fallback_names: parsed_impl
123                .field_fallback
124                .as_ref()
125                .and_then(|fallback| fallback.names.as_ref())
126                .map(|_| crate::naming::sidecar_fallback_names_c_name(&type_name)),
127        }
128    }
129
130    /// The fallback's read of `name`, a name no field has, on the bare
131    /// pointer `receiver` (#2150): the method returns the value the fallback
132    /// has for it. The method passes its own frame (`environment()`) as the
133    /// value of `None`, which the entry hands back untouched, so no value the
134    /// fallback computes can be taken for it; the lines after these decide
135    /// what `None` reads. Nothing without a fallback.
136    fn fallback_read(&self, receiver: &str, name: &str, indent: &str) -> Vec<String> {
137        let Some(entry) = &self.fallback else {
138            return Vec::new();
139        };
140        let mut lines = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("{0}.val <- .Call({1}, {2}, {3}, environment())",
                                indent, entry, receiver, name))
                    })]))vec![format!(
141            "{indent}.val <- .Call({entry}, {receiver}, {name}, environment())"
142        )];
143        lines.extend(guard(indent));
144        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}if (!identical(.val, environment())) return(.val)",
                indent))
    })format!(
145            "{indent}if (!identical(.val, environment())) return(.val)"
146        ));
147        lines
148    }
149
150    /// The last lines of a `$<-` / `[[<-` once `name` is known to be a
151    /// field: under `r_data_accessors` the write through `.rdata_set_<Type>`
152    /// on `receiver`, checked, and the object `x`; under `r_data_accessors =
153    /// "read_only"` the `miniextendr_read_only_field` refusal (#2268), on
154    /// the method's call, naming the R class of `x`.
155    fn field_write(&self, parsed_impl: &ParsedImpl, receiver: &str, name: &str) -> Vec<String> {
156        if !parsed_impl.r_data_accessors.setters() {
157            return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("  {0}({1}, x, environment())",
                                self.read_only, name))
                    })]))vec![format!("  {}({name}, x, environment())", self.read_only)];
158        }
159        let mut lines = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("  .val <- {0}({1}, {2}, value)",
                                self.set, receiver, name))
                    })]))vec![format!("  .val <- {}({receiver}, {name}, value)", self.set)];
160        lines.extend(guard("  "));
161        lines.push("  x".to_string());
162        lines
163    }
164
165    /// The call of the impl's `fallback_names` entry (#2150) on the bare
166    /// pointer `receiver`, for `.DollarNames()`; `None` without one. The
167    /// entry gives `character(0)` for a pointer without its Rust value, so
168    /// completion still never raises on a restored object.
169    fn fallback_names_call(&self, receiver: &str) -> Option<String> {
170        let entry = self.fallback_names.as_ref()?;
171        Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".Call({0}, {1})", entry, receiver))
    })format!(".Call({entry}, {receiver})"))
172    }
173
174    /// The last lines of a `.DollarNames()` with a `fallback_names` (#2150):
175    /// `value`, which reads the fallback's names (or a list's own), bound to
176    /// `.val` and checked, then `pattern` over `known` and `.val`, each name
177    /// once (a name the fallback shares with a field reads the field).
178    fn dollar_names_with_fallback(value: &str, known: &str) -> Vec<String> {
179        let mut lines = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("  .val <- {0}", value))
                    })]))vec![format!("  .val <- {value}")];
180        lines.extend(guard("  "));
181        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  grep(pattern, unique(c({0}, .val)), value = TRUE)",
                known))
    })format!(
182            "  grep(pattern, unique(c({known}, .val)), value = TRUE)"
183        ));
184        lines
185    }
186
187    /// Under `restored(refuse = "every_read")` (#1901), the check a read
188    /// that reaches no accessor makes first on the bare pointer `receiver`:
189    /// a pointer without its Rust value raises the type's restored error. A
190    /// type without the option skips it (its flag is `FALSE`).
191    fn live_check(&self, receiver: &str, indent: &str) -> Vec<String> {
192        let mut lines = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("{1}if ({0}) {{",
                                self.every_read, indent))
                    })]))vec![format!("{indent}if ({}) {{", self.every_read)];
193        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}  .val <- {0}({2}, TRUE)",
                self.live, indent, receiver))
    })format!("{indent}  .val <- {}({receiver}, TRUE)", self.live));
194        lines.extend(guard(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}  ", indent))
    })format!("{indent}  ")));
195        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}}}", indent))
    })format!("{indent}}}"));
196        lines
197    }
198
199    /// The first check of every S3 reader under `restored(refuse =
200    /// "every_read")` (#1901, #1919), on a bare pointer and on a list or
201    /// environment receiver: a pointer without its Rust value, a `.ptr` that
202    /// is one, and a list or environment that carries none (the shape an
203    /// earlier release may have saved) raise the type's refusal before the
204    /// index is looked at, so a position or an unknown name is refused too.
205    /// An atomic receiver was never saved; its field reads refuse it.
206    fn every_read_check(&self) -> Vec<String> {
207        let mut lines = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("  if ({0} && typeof(x) %in% c(\"externalptr\", \"list\", \"environment\")) {{",
                                self.every_read))
                    })]))vec![format!(
208            "  if ({} && typeof(x) %in% c(\"externalptr\", \"list\", \"environment\")) {{",
209            self.every_read
210        )];
211        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("    .val <- {0}(x, TRUE)",
                self.live))
    })format!("    .val <- {}(x, TRUE)", self.live));
212        lines.extend(guard("    "));
213        lines.push("  }".to_string());
214        lines
215    }
216
217    /// The guard of the S3 `.DollarNames()`, which reads a list's or
218    /// environment's own `names()`: under `restored(refuse = "every_read")`
219    /// a receiver without a live Rust value (#1901), a restored pointer or a
220    /// list or environment carrying one or none (#1919), completes to the
221    /// field names, which need no value (#2218), since its `names()` would
222    /// refuse. A serde type's restored pointer gets its value back in the
223    /// check first (#2186). `.DollarNames()` serves completion, so it never
224    /// raises. The S4 and env completions read only static names and the
225    /// fallback's, whose entry gives none without a value, so they need no
226    /// guard.
227    fn dollar_names_guard(&self) -> String {
228        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  if ({0} && !{1}(x, FALSE)) return(grep(pattern, {2}, value = TRUE))",
                self.every_read, self.live, self.fields))
    })format!(
229            "  if ({every_read} && !{live}(x, FALSE)) return(grep(pattern, {fields}, value = TRUE))",
230            every_read = self.every_read,
231            live = self.live,
232            fields = self.fields,
233        )
234    }
235}
236
237/// The tagged-condition guard after an accessor call: the method's frame is
238/// the raise fallback, resolved to the generic's call (#1851).
239fn guard(indent: &str) -> Vec<String> {
240    crate::method_return_builder::condition_check_lines_with_default(indent, "environment()")
241}
242
243/// The formals of the S3 `[[` reader: `exact` after `...`, as
244/// `[[.data.frame` has it, so R matches it by name and `...` holds only
245/// what the reader refuses (#2174).
246const SUBSET_FORMALS: &str = "x, i, ..., exact = TRUE";
247
248/// The formals of the S3 `as.list()` reader, its generic's.
249const AS_LIST_FORMALS: &str = "x, ...";
250
251/// The formals of the S3 `[[<-` writer, `value` last (#1853).
252const SUBSET_ASSIGN_FORMALS: &str = "x, i, ..., value";
253
254/// The formals of an env class's `[[`: its `$`'s, then `...` and `exact`,
255/// as the S3 `[[` has them (#2174).
256pub(super) const ENV_SUBSET_FORMALS: &str = "self, name, ..., exact = TRUE";
257
258/// The check a method with `formals` makes before it reads its index
259/// (#2174): `dots = empty`'s statement
260/// ([`DotsPolicy::r_check`](crate::dots_policy::DotsPolicy::r_check)), which
261/// refuses every argument in `...` on the generic's call (the method's
262/// frame), with the formal each one most likely meant. `class` is an R
263/// expression for the classes in front, the type's `field_error` classes.
264fn dots_check(formals: &str, class: Option<&str>, indent: &str) -> String {
265    let check = crate::dots_policy::DotsPolicy::empty(class.map(str::to_owned))
266        .r_check(formals, Some("environment()"))
267        .expect("the methods take `...`");
268    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", indent, check))
    })format!("{indent}{check}")
269}
270
271/// The first line of an env class's `[[` (#2174): it takes no argument
272/// past `name` but `exact`, which it ignores (field and method names match
273/// exactly), and nothing reads its `...`, on any receiver. Under
274/// `env(r_data_accessors)` the refusal carries the type's `field_error`
275/// classes.
276pub(super) fn env_subset_dots_check(parsed_impl: &ParsedImpl) -> String {
277    let class = parsed_impl
278        .r_data_accessors
279        .enabled()
280        .then(|| Helpers::new(parsed_impl).error_class);
281    dots_check(ENV_SUBSET_FORMALS, class.as_deref(), "  ")
282}
283
284/// The help topic of the field methods (and of the S3 and vctrs class
285/// environment):
286/// the impl block's own `@rdname`, else the class page (#1900).
287pub(super) fn topic(parsed_impl: &ParsedImpl) -> String {
288    crate::roxygen::rdname_value(&parsed_impl.doc_tags)
289        .map_or_else(|| parsed_impl.class_name(), str::to_owned)
290}
291
292/// The page lines of a field method's block: `@rdname` its topic
293/// ([`topic`]) with the `@param` lines of `params` the page needs, or, on a
294/// topic the author names with the impl's `@rdname`, `@order NaN` and no
295/// `@param` lines: the topic's own block documents the arguments, and a
296/// later block's `@param` would replace its text (#1590).
297pub(super) fn page_lines(parsed_impl: &ParsedImpl, params: &[(&str, &str)]) -> Vec<String> {
298    let topic = topic(parsed_impl);
299    let mut lines = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("#\' @rdname {0}", topic))
                    })]))vec![format!("#' @rdname {topic}")];
300    if topic == parsed_impl.class_name() {
301        lines.extend(param_lines(parsed_impl, params));
302    } else {
303        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' {0}",
                crate::roxygen::ORDER_AFTER_TOPIC_BLOCKS))
    })format!("#' {}", crate::roxygen::ORDER_AFTER_TOPIC_BLOCKS));
304    }
305    lines
306}
307
308/// The `@param value` text of the writers: the new value, or under
309/// `r_data_accessors = "read_only"` the refused one (#2268).
310fn value_param(parsed_impl: &ParsedImpl) -> &'static str {
311    if parsed_impl.r_data_accessors.setters() {
312        "The new value of the field."
313    } else {
314        "A value for a field; the fields are read-only, so the assignment is refused."
315    }
316}
317
318/// The test of a `[[` / `[[<-` index (or env's `$` / `[[` name): a field
319/// name is a length-1 character vector naming a field.
320fn not_a_field_name(var: &str, fields: &str) -> String {
321    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("!is.character({0}) || length({0}) != 1L || is.na(match({0}, {1}))",
                var, fields))
    })format!("!is.character({var}) || length({var}) != 1L || is.na(match({var}, {fields}))")
322}
323
324/// A top-level check, emitted next to the class's methods, that the type has
325/// the field helpers: an impl that opts in for a type without an `RSidecar`
326/// selector or without a `pub` `#[r_data]` field fails at install time
327/// instead of at the first `$` (for env, at every method call).
328fn load_check(parsed_impl: &ParsedImpl, system: &str) -> String {
329    let helpers = Helpers::new(parsed_impl);
330    let type_name = parsed_impl.type_ident.to_string();
331    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if (!is.character(get0(\"{0}\", envir = topenv(environment()), inherits = FALSE))) stop(\"`{1}(r_data_accessors)` on `{2}` needs the field helpers `#[derive(ExternalPtr)]` emits for a type with an `#[r_data]` `RSidecar` selector and a `pub` `#[r_data]` field\", call. = FALSE)",
                helpers.fields, system, type_name))
    })format!(
332        "if (!is.character(get0(\"{fields}\", envir = topenv(environment()), inherits = FALSE))) \
333         stop(\"`{system}(r_data_accessors)` on `{type_name}` needs the field helpers \
334         `#[derive(ExternalPtr)]` emits for a type with an `#[r_data]` `RSidecar` selector and a \
335         `pub` `#[r_data]` field\", call. = FALSE)",
336        fields = helpers.fields,
337    )
338}
339
340/// The `@param` lines of the field methods on the class page, without the
341/// names the constructor documents there: roxygen2 keeps the last `@param`
342/// of a name on a page, and these blocks must not replace the constructor's
343/// text. An env class's `Class$new()` lists its arguments in a `\describe{}`
344/// list, not as `@param` lines, so it takes nothing away. (The type's
345/// standalone accessors, which documented `x` / `value` on the page named
346/// after the type, are internal under field syntax, #1900.)
347fn param_lines(parsed_impl: &ParsedImpl, params: &[(&str, &str)]) -> Vec<String> {
348    let documented: Vec<String> = parsed_impl
349        .constructor()
350        .filter(|_| parsed_impl.class_system != ClassSystem::Env)
351        .map(|ctor| {
352            let formals = ctor.formals();
353            crate::r_wrapper_builder::r_formal_names(&ctor.sig.inputs, &formals)
354                .map(|(name, _)| name)
355                .collect()
356        })
357        .unwrap_or_default();
358    params
359        .iter()
360        .filter(|(name, _)| !documented.iter().any(|f| f == name))
361        .map(|(name, text)| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @param {0} {1}", name, text))
    })format!("#' @param {name} {text}"))
362        .collect()
363}
364
365/// The roxygen block of an S3 or env field method `<generic>.<Class>`: on the
366/// class's topic ([`page_lines`]) for an exported class with a page, else no
367/// page. The method is registered (`S3method()`) when `register` is set.
368fn s3_method_doc(
369    lines: &mut Vec<String>,
370    parsed_impl: &ParsedImpl,
371    generic: &str,
372    on_page: bool,
373    register: bool,
374    params: &[(&str, &str)],
375) {
376    let class_name = parsed_impl.class_name();
377    if on_page {
378        lines.extend(page_lines(parsed_impl, params));
379    } else {
380        lines.push("#' @noRd".to_string());
381    }
382    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @method {0} {1}", generic,
                class_name))
    })format!("#' @method {generic} {class_name}"));
383    if register {
384        lines.push("#' @export".to_string());
385    }
386}
387
388/// The roxygen block of a `.DollarNames.<Class>` method: on the class's
389/// topic ([`page_lines`]) for an exported class with a page, else no page,
390/// and registered with `@exportS3Method utils::.DollarNames` when `register`
391/// is set (see the module docs for why not `@method` + `@export`).
392fn dollar_names_doc(
393    lines: &mut Vec<String>,
394    parsed_impl: &ParsedImpl,
395    on_page: bool,
396    register: bool,
397) {
398    if on_page {
399        lines.extend(page_lines(
400            parsed_impl,
401            &[
402                ("x", "An object."),
403                (
404                    "pattern",
405                    "A regular expression; the names matching it are the completions.",
406                ),
407            ],
408        ));
409    } else {
410        lines.push("#' @noRd".to_string());
411    }
412    if register {
413        lines.push("#' @exportS3Method utils::.DollarNames".to_string());
414    }
415}
416
417/// `$.Class`, `[[.Class`, `names.Class`, `as.list.Class` and
418/// `.DollarNames.Class`, and with writers `$<-.Class` / `[[<-.Class` (which
419/// refuse every field under `r_data_accessors = "read_only"`, #2268), for an
420/// S3 class with `s3(r_data_accessors)`.
421///
422/// The receiver is the classed pointer the constructor (or the package's own
423/// R code) returns, on which the reads look the fields up as a list's do, or
424/// a list or environment carrying the pointer in `.ptr` (#1469), whose own
425/// elements a name that is not a field reaches through `NextMethod()`.
426pub(super) fn s3_field_methods(
427    parsed_impl: &ParsedImpl,
428    on_page: bool,
429    register: bool,
430) -> Vec<String> {
431    let class_name = parsed_impl.class_name();
432    let h = Helpers::new(parsed_impl);
433    let def = |generic: &str| crate::naming::r_def_name(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.{1}", generic, class_name))
    })format!("{generic}.{class_name}"));
434    let mut lines = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("# Field syntax for the `#[r_data]` fields of {0} (`s3(r_data_accessors)`).",
                                parsed_impl.type_ident))
                    }), load_check(parsed_impl, "s3"), String::new()]))vec![
435        format!(
436            "# Field syntax for the `#[r_data]` fields of {} (`s3(r_data_accessors)`).",
437            parsed_impl.type_ident
438        ),
439        load_check(parsed_impl, "s3"),
440        String::new(),
441    ];
442
443    let class_lit = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"",
                crate::naming::r_string_escape(&class_name)))
    })format!("\"{}\"", crate::naming::r_string_escape(&class_name));
444    let x = ("x", "An object.");
445    // One text for `[[`, `as.list()` and `[[<-`, which share the page.
446    let dots = (
447        "...",
448        "Passed on by a list or an environment carrying the pointer; on the pointer \
449         itself any argument here is refused.",
450    );
451    let exact = (
452        "exact",
453        "Ignored on the pointer itself, whose field names match exactly. A list or an \
454         environment carrying the pointer reads its own elements with `exact = TRUE` \
455         whatever is passed.",
456    );
457    // One text per name for the page: roxygen2 keeps the last `@param` of a
458    // name on a page, so the reader's and the writer's blocks say the same.
459    let fallback = h.fallback.is_some();
460    let (name, i) = match parsed_impl.field_lookup {
461        FieldLookup::Strict if fallback => (
462            (
463                "name",
464                "A field name, exactly; on the pointer itself another name is read through \
465                 the class's fallback, an error when it has no value for it.",
466            ),
467            (
468                "i",
469                "A field name, exactly; `[[` on the pointer itself also takes a whole-number \
470                 position in the field order and reads another name through the class's \
471                 fallback. On a list or an environment carrying the pointer, any other index \
472                 goes to the object's own `[[` / `[[<-`, which matches names exactly.",
473            ),
474        ),
475        FieldLookup::List if fallback => (
476            (
477                "name",
478                "A field name, exactly; on the pointer itself another name is read through \
479                 the class's fallback, `NULL` when it has no value for it.",
480            ),
481            (
482                "i",
483                "A field name, exactly; `[[` on the pointer itself also takes a position in \
484                 the field order, as for a list, and reads another name through the class's \
485                 fallback. On a list or an environment carrying the pointer, any other index \
486                 goes to the object's own `[[` / `[[<-`, which matches names exactly.",
487            ),
488        ),
489        FieldLookup::Strict => (
490            (
491                "name",
492                "A field name, exactly; on the pointer itself any other name is an error.",
493            ),
494            (
495                "i",
496                "A field name, exactly; `[[` on the pointer itself also takes a whole-number \
497                 position in the field order. On a list or an environment carrying the \
498                 pointer, any other index goes to the object's own `[[` / `[[<-`, which \
499                 matches names exactly.",
500            ),
501        ),
502        FieldLookup::List => (
503            (
504                "name",
505                "A field name, exactly; on the pointer itself any other name reads `NULL`.",
506            ),
507            (
508                "i",
509                "A field name, exactly; `[[` on the pointer itself also takes a position in \
510                 the field order, as for a list. On a list or an environment carrying the \
511                 pointer, any other index goes to the object's own `[[` / `[[<-`, which \
512                 matches names exactly.",
513            ),
514        ),
515    };
516    let value = ("value", value_param(parsed_impl));
517
518    // `$`: an exact field name reads the field. On a bare pointer any other
519    // name raises `miniextendr_no_field`, or reads NULL under
520    // `lookup = "list"`; a list receiver reads its own element by the exact
521    // name (`.subset2()`: R's `$` on a list would match a prefix, #1922), an
522    // environment receiver through R's `$`, which is exact there.
523    s3_method_doc(&mut lines, parsed_impl, "$", on_page, register, &[x, name]);
524    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function(x, name) {{",
                def("$")))
    })format!("{} <- function(x, name) {{", def("$")));
525    lines.extend(h.every_read_check());
526    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  if (is.na(match(name, {0}))) {{",
                h.fields))
    })format!("  if (is.na(match(name, {}))) {{", h.fields));
527    // What an unknown name reads on the bare pointer, and what the
528    // fallback's `None` reads (#2150).
529    let unknown = |name: &str| match parsed_impl.field_lookup {
530        FieldLookup::Strict => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}({1}, environment(), {2})",
                h.no_field, name, class_lit))
    })format!("{}({name}, environment(), {class_lit})", h.no_field),
531        FieldLookup::List => "return(NULL)".to_string(),
532    };
533    if fallback {
534        lines.push("    if (typeof(x) == \"externalptr\") {".to_string());
535        lines.extend(h.fallback_read("x", "name", "      "));
536        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("      {0}", unknown("name")))
    })format!("      {}", unknown("name")));
537        lines.push("    }".to_string());
538    } else {
539        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("    if (typeof(x) == \"externalptr\") {0}",
                unknown("name")))
    })format!(
540            "    if (typeof(x) == \"externalptr\") {}",
541            unknown("name")
542        ));
543    }
544    lines.push("    if (is.list(x)) return(.subset2(x, name))".to_string());
545    lines.push("    return(NextMethod())".to_string());
546    lines.push("  }".to_string());
547    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  .val <- {0}(x, name)", h.get))
    })format!("  .val <- {}(x, name)", h.get));
548    lines.extend(guard("  "));
549    lines.push("  .val".to_string());
550    lines.push("}".to_string());
551    lines.push(String::new());
552
553    // `[[`: on a bare pointer one exact name or one position. The default
554    // takes a whole number only and refuses an unknown name with
555    // `miniextendr_no_field`; `lookup = "list"` takes a number or a logical
556    // as a list's `[[` does (`NA` reads NULL, since a character vector's
557    // `[[NA]]` is `NA` where a list's is NULL; the rest through
558    // `.miniextendr_field_at`) and reads NULL for an unknown name. Any other
559    // index raises the bad-index error there (#1920). The bare pointer first
560    // refuses any argument in `...` (#2174); `exact` is a formal, ignored
561    // there. A list or environment receiver reaches its own `[[` for
562    // everything but an exact field, with its dots and `exact = TRUE`
563    // whatever the call passed (#1922).
564    s3_method_doc(
565        &mut lines,
566        parsed_impl,
567        "[[",
568        on_page,
569        register,
570        &[x, i, dots, exact],
571    );
572    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                def("[["), SUBSET_FORMALS))
    })format!("{} <- function({SUBSET_FORMALS}) {{", def("[[")));
573    lines.extend(h.every_read_check());
574    lines.push("  if (typeof(x) == \"externalptr\") {".to_string());
575    lines.push(dots_check(SUBSET_FORMALS, Some(&h.error_class), "    "));
576    let field_at = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("      i <- .miniextendr_field_at({0}, i, environment(), {1})",
                h.fields, h.error_class))
    })format!(
577        "      i <- .miniextendr_field_at({}, i, environment(), {})",
578        h.fields, h.error_class
579    );
580    match parsed_impl.field_lookup {
581        FieldLookup::List => {
582            lines.push("    if (is.character(i) && length(i) == 1L) {".to_string());
583            if fallback {
584                // `NA` reads NULL, as without the fallback.
585                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("      if (is.na(match(i, {0}))) {{",
                h.fields))
    })format!("      if (is.na(match(i, {}))) {{", h.fields));
586                lines.push("        if (!is.na(i)) {".to_string());
587                lines.extend(h.fallback_read("x", "i", "          "));
588                lines.push("        }".to_string());
589                lines.push("        return(NULL)".to_string());
590                lines.push("      }".to_string());
591            } else {
592                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("      if (is.na(match(i, {0}))) return(NULL)",
                h.fields))
    })format!(
593                    "      if (is.na(match(i, {}))) return(NULL)",
594                    h.fields
595                ));
596            }
597            lines.push(
598                "    } else if (length(i) == 1L && (is.numeric(i) || is.logical(i))) {".to_string(),
599            );
600            lines.push("      if (is.na(i)) return(NULL)".to_string());
601            lines.push(field_at);
602            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("    }} else .miniextendr_field_index_error({1}, environment(), {0})",
                h.error_class, class_lit))
    })format!(
603                "    }} else .miniextendr_field_index_error({class_lit}, environment(), {})",
604                h.error_class
605            ));
606        }
607        FieldLookup::Strict => {
608            lines.push("    if (is.character(i) && length(i) == 1L && !is.na(i)) {".to_string());
609            if fallback {
610                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("      if (is.na(match(i, {0}))) {{",
                h.fields))
    })format!("      if (is.na(match(i, {}))) {{", h.fields));
611                lines.extend(h.fallback_read("x", "i", "        "));
612                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("        {0}", unknown("i")))
    })format!("        {}", unknown("i")));
613                lines.push("      }".to_string());
614            } else {
615                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("      if (is.na(match(i, {0}))) {1}",
                h.fields, unknown("i")))
    })format!(
616                    "      if (is.na(match(i, {}))) {}",
617                    h.fields,
618                    unknown("i")
619                ));
620            }
621            lines.push(
622                "    } else if (is.numeric(i) && length(i) == 1L && !is.na(i) && i == trunc(i)) {"
623                    .to_string(),
624            );
625            lines.push(field_at);
626            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("    }} else .miniextendr_field_index_error({1}, environment(), {0}, strict = TRUE)",
                h.error_class, class_lit))
    })format!(
627                "    }} else .miniextendr_field_index_error({class_lit}, environment(), {}, strict = TRUE)",
628                h.error_class
629            ));
630        }
631    }
632    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  }} else if ({0}) {{",
                not_a_field_name("i", &h.fields)))
    })format!(
633        "  }} else if ({}) {{",
634        not_a_field_name("i", &h.fields)
635    ));
636    lines.push("    return(NextMethod(exact = TRUE))".to_string());
637    lines.push("  }".to_string());
638    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  .val <- {0}(x, i)", h.get))
    })format!("  .val <- {}(x, i)", h.get));
639    lines.extend(guard("  "));
640    lines.push("  .val".to_string());
641    lines.push("}".to_string());
642    lines.push(String::new());
643
644    // `names()` and `as.list()` on a bare pointer only (#1890): a list or
645    // environment receiver keeps R's own, so `names(x)` agrees with
646    // `length(x)` and `x[[i]]` there. An environment gets
647    // `as.list.environment()` by name: its class attribute would send
648    // `NextMethod()` to `as.list.default()`, which can't coerce one.
649    // `as.list()` reads every field through the getters, in declared order,
650    // and keeps a NULL field (`out[k] <- list(.val)`; `out[[k]] <- NULL`
651    // would drop it). It takes no argument there and refuses any in `...`
652    // (#2174); an environment's `as.list()` takes `all.names` / `sorted`.
653    s3_method_doc(&mut lines, parsed_impl, "names", on_page, register, &[x]);
654    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function(x) {{",
                def("names")))
    })format!("{} <- function(x) {{", def("names")));
655    lines.extend(h.every_read_check());
656    lines.push("  if (typeof(x) != \"externalptr\") return(NextMethod())".to_string());
657    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0}", h.fields))
    })format!("  {}", h.fields));
658    lines.push("}".to_string());
659    lines.push(String::new());
660
661    s3_method_doc(
662        &mut lines,
663        parsed_impl,
664        "as.list",
665        on_page,
666        register,
667        &[x, dots],
668    );
669    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                def("as.list"), AS_LIST_FORMALS))
    })format!(
670        "{} <- function({AS_LIST_FORMALS}) {{",
671        def("as.list")
672    ));
673    lines.extend(h.every_read_check());
674    lines.push("  if (is.environment(x)) return(as.list.environment(x, ...))".to_string());
675    lines.push("  if (typeof(x) != \"externalptr\") return(NextMethod())".to_string());
676    lines.push(dots_check(AS_LIST_FORMALS, Some(&h.error_class), "  "));
677    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  .out <- vector(\"list\", length({0}))",
                h.fields))
    })format!("  .out <- vector(\"list\", length({}))", h.fields));
678    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  names(.out) <- {0}", h.fields))
    })format!("  names(.out) <- {}", h.fields));
679    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  for (.k in seq_along({0})) {{",
                h.fields))
    })format!("  for (.k in seq_along({})) {{", h.fields));
680    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("    .val <- {0}(x, {1}[[.k]])",
                h.get, h.fields))
    })format!("    .val <- {}(x, {}[[.k]])", h.get, h.fields));
681    lines.extend(guard("    "));
682    lines.push("    .out[.k] <- list(.val)".to_string());
683    lines.push("  }".to_string());
684    lines.push("  .out".to_string());
685    lines.push("}".to_string());
686    lines.push(String::new());
687
688    // `.DollarNames()` (#1885): the fields, then a list's or environment's
689    // own names. It reads only names, so it never raises; under
690    // `restored(refuse = "every_read")` a restored pointer completes to the
691    // fields alone (#1901, #2218).
692    dollar_names_doc(&mut lines, parsed_impl, on_page, register);
693    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function(x, pattern = \"\") {{",
                def(".DollarNames")))
    })format!(
694        "{} <- function(x, pattern = \"\") {{",
695        def(".DollarNames")
696    ));
697    lines.push(h.dollar_names_guard());
698    match h.fallback_names_call("x") {
699        // The fallback's names follow the fields on the bare pointer, where
700        // `$` reads them (#2150).
701        Some(call) => lines.extend(Helpers::dollar_names_with_fallback(
702            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if (typeof(x) == \"externalptr\") {0} else names(x)",
                call))
    })format!("if (typeof(x) == \"externalptr\") {call} else names(x)"),
703            &h.fields,
704        )),
705        None => lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  grep(pattern, c({0}, if (typeof(x) != \"externalptr\") names(x)), value = TRUE)",
                h.fields))
    })format!(
706            "  grep(pattern, c({}, if (typeof(x) != \"externalptr\") names(x)), value = TRUE)",
707            h.fields
708        )),
709    }
710    lines.push("}".to_string());
711    lines.push(String::new());
712
713    if !parsed_impl.r_data_accessors.writers() {
714        return lines;
715    }
716
717    // The writers: a field is written, or under `r_data_accessors =
718    // "read_only"` refused (#2268); any other name is refused on the bare
719    // pointer and goes to a list's or environment's own `$<-` / `[[<-`.
720    s3_method_doc(
721        &mut lines,
722        parsed_impl,
723        "$<-",
724        on_page,
725        register,
726        &[x, name, value],
727    );
728    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function(x, name, value) {{",
                def("$<-")))
    })format!("{} <- function(x, name, value) {{", def("$<-")));
729    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  if (is.na(match(name, {0}))) {{",
                h.fields))
    })format!("  if (is.na(match(name, {}))) {{", h.fields));
730    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("    if (typeof(x) == \"externalptr\") {0}(name, environment(), {1})",
                h.no_field, class_lit))
    })format!(
731        "    if (typeof(x) == \"externalptr\") {}(name, environment(), {class_lit})",
732        h.no_field
733    ));
734    lines.push("    return(NextMethod())".to_string());
735    lines.push("  }".to_string());
736    lines.extend(h.field_write(parsed_impl, "x", "name"));
737    lines.push("}".to_string());
738    lines.push(String::new());
739
740    s3_method_doc(
741        &mut lines,
742        parsed_impl,
743        "[[<-",
744        on_page,
745        register,
746        &[x, i, dots, value],
747    );
748    // The bare pointer refuses any argument in `...` (#2174): `x[["a", 2]] <-
749    // v` would otherwise write `a`. A list or environment receiver hands
750    // them to its own `[[<-`.
751    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                def("[[<-"), SUBSET_ASSIGN_FORMALS))
    })format!(
752        "{} <- function({SUBSET_ASSIGN_FORMALS}) {{",
753        def("[[<-")
754    ));
755    lines.push("  if (typeof(x) == \"externalptr\") {".to_string());
756    lines.push(dots_check(
757        SUBSET_ASSIGN_FORMALS,
758        Some(&h.error_class),
759        "    ",
760    ));
761    lines.push("  }".to_string());
762    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  if ({0}) {{",
                not_a_field_name("i", &h.fields)))
    })format!("  if ({}) {{", not_a_field_name("i", &h.fields)));
763    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("    if (typeof(x) == \"externalptr\" && is.character(i) && length(i) == 1L) {0}(i, environment(), {1})",
                h.no_field, class_lit))
    })format!(
764        "    if (typeof(x) == \"externalptr\" && is.character(i) && length(i) == 1L) {}(i, environment(), {class_lit})",
765        h.no_field
766    ));
767    lines.push("    return(NextMethod())".to_string());
768    lines.push("  }".to_string());
769    lines.extend(h.field_write(parsed_impl, "x", "i"));
770    lines.push("}".to_string());
771    lines.push(String::new());
772    lines
773}
774
775/// `setMethod("$")`, `.DollarNames.Class`, and with writers
776/// `setMethod("$<-")` (refusing every field under `r_data_accessors =
777/// "read_only"`, #2268), for an S4 class with `s4(r_data_accessors)`. An S4
778/// object of the class is no list (its only slot is `ptr`), so a name that
779/// is not a field raises `miniextendr_no_field`. The methods pass `x@ptr` to
780/// the accessors. `.DollarNames` is an S3 method, which `utils` dispatches on
781/// the S4 class; it is registered unless the class is `noexport`, as an S3
782/// class's methods are.
783pub(super) fn s4_field_methods(
784    parsed_impl: &ParsedImpl,
785    on_page: bool,
786    export: bool,
787) -> Vec<String> {
788    let class_name = parsed_impl.class_name();
789    let class_lit = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"",
                crate::naming::r_string_escape(&class_name)))
    })format!("\"{}\"", crate::naming::r_string_escape(&class_name));
790    let h = Helpers::new(parsed_impl);
791    let mut lines = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("# Field syntax for the `#[r_data]` fields of {0} (`s4(r_data_accessors)`).",
                                parsed_impl.type_ident))
                    }), load_check(parsed_impl, "s4"), String::new()]))vec![
792        format!(
793            "# Field syntax for the `#[r_data]` fields of {} (`s4(r_data_accessors)`).",
794            parsed_impl.type_ident
795        ),
796        load_check(parsed_impl, "s4"),
797        String::new(),
798    ];
799    let doc = |lines: &mut Vec<String>, generic: &str, params: &[(&str, &str)]| {
800        if on_page {
801            lines.extend(page_lines(parsed_impl, params));
802        } else {
803            lines.push("#' @noRd".to_string());
804        }
805        if export {
806            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @exportMethod {0}", generic))
    })format!("#' @exportMethod {generic}"));
807        }
808    };
809    let x = ("x", "An object.");
810    let name = (
811        "name",
812        if h.fallback.is_some() {
813            "A field name, or a name the class's fallback reads."
814        } else {
815            "A field name."
816        },
817    );
818    let value = ("value", value_param(parsed_impl));
819
820    doc(&mut lines, "$", &[x, name]);
821    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("methods::setMethod(\"$\", \"{0}\", function(x, name) {{",
                class_name))
    })format!(
822        "methods::setMethod(\"$\", \"{class_name}\", function(x, name) {{"
823    ));
824    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  if (is.na(match(name, {0}))) {{",
                h.fields))
    })format!("  if (is.na(match(name, {}))) {{", h.fields));
825    lines.extend(h.live_check("x@ptr", "    "));
826    lines.extend(h.fallback_read("x@ptr", "name", "    "));
827    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("    {0}(name, environment(), {1})",
                h.no_field, class_lit))
    })format!(
828        "    {}(name, environment(), {class_lit})",
829        h.no_field
830    ));
831    lines.push("  }".to_string());
832    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  .val <- {0}(x@ptr, name)",
                h.get))
    })format!("  .val <- {}(x@ptr, name)", h.get));
833    lines.extend(guard("  "));
834    lines.push("  .val".to_string());
835    lines.push("})".to_string());
836    lines.push(String::new());
837
838    dollar_names_doc(&mut lines, parsed_impl, on_page, !parsed_impl.noexport);
839    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function(x, pattern = \"\") {{",
                crate::naming::r_def_name(&::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!(".DollarNames.{0}",
                                        class_name))
                            }))))
    })format!(
840        "{} <- function(x, pattern = \"\") {{",
841        crate::naming::r_def_name(&format!(".DollarNames.{class_name}"))
842    ));
843    match h.fallback_names_call("x@ptr") {
844        Some(call) => lines.extend(Helpers::dollar_names_with_fallback(&call, &h.fields)),
845        None => lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  grep(pattern, {0}, value = TRUE)",
                h.fields))
    })format!("  grep(pattern, {}, value = TRUE)", h.fields)),
846    }
847    lines.push("}".to_string());
848    lines.push(String::new());
849
850    if parsed_impl.r_data_accessors.writers() {
851        doc(&mut lines, "$<-", &[x, name, value]);
852        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("methods::setMethod(\"$<-\", \"{0}\", function(x, name, value) {{",
                class_name))
    })format!(
853            "methods::setMethod(\"$<-\", \"{class_name}\", function(x, name, value) {{"
854        ));
855        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  if (is.na(match(name, {0}))) {1}(name, environment(), {2})",
                h.fields, h.no_field, class_lit))
    })format!(
856            "  if (is.na(match(name, {}))) {}(name, environment(), {class_lit})",
857            h.fields, h.no_field
858        ));
859        lines.extend(h.field_write(parsed_impl, "x@ptr", "name"));
860        lines.push("})".to_string());
861        lines.push(String::new());
862    }
863    lines
864}
865
866/// The field branch at the top of an env class's `$.Class` (and its
867/// `[[.Class` alias), ahead of the method lookup: a field wins over a method
868/// of the same name, as R6's active bindings do, and a field read doesn't
869/// pay for the lookup.
870pub(super) fn env_field_branch(parsed_impl: &ParsedImpl) -> Vec<String> {
871    let h = Helpers::new(parsed_impl);
872    let mut lines = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("  if (!({0})) {{",
                                not_a_field_name("name", &h.fields)))
                    })]))vec![format!(
873        "  if (!({})) {{",
874        not_a_field_name("name", &h.fields)
875    )];
876    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("    .val <- {0}(self, name)",
                h.get))
    })format!("    .val <- {}(self, name)", h.get));
877    lines.extend(guard("    "));
878    lines.push("    return(.val)".to_string());
879    lines.push("  }".to_string());
880    lines
881}
882
883/// The check in an env class's `$.Class` before it returns `NULL` for a name
884/// that is neither a field nor a method: under `restored(refuse =
885/// "every_read")` a pointer without its Rust value raises the type's
886/// restored error there (#1901). With a `fallback` (#2150) the bare pointer
887/// then asks it, after the fields and the methods, so a value of the
888/// fallback never hides a method; its `None` reads `NULL`, as an unknown
889/// name does.
890pub(super) fn env_unknown_name_check(parsed_impl: &ParsedImpl) -> Vec<String> {
891    let h = Helpers::new(parsed_impl);
892    let mut lines = h.live_check("self", "    ");
893    if h.fallback.is_some() {
894        lines.push("    if (typeof(self) == \"externalptr\") {".to_string());
895        lines.extend(h.fallback_read("self", "name", "      "));
896        lines.push("    }".to_string());
897    }
898    lines
899}
900
901/// The `@param name` text of an env class's `$.Class`.
902pub(super) fn env_name_param(parsed_impl: &ParsedImpl) -> &'static str {
903    if parsed_impl.field_fallback.is_some() {
904        "A method or field name, or a name the class's fallback reads."
905    } else {
906        "A method or field name."
907    }
908}
909
910/// The load check of an env class with `env(r_data_accessors)`.
911pub(super) fn env_load_check(parsed_impl: &ParsedImpl) -> String {
912    load_check(parsed_impl, "env")
913}
914
915/// `.DollarNames.Class` for an env class with `env(r_data_accessors)`: the
916/// fields, then the class's methods (`ls(<Class>)`), since `$` reaches both.
917/// Both are static, so a restored object completes to them too, under
918/// `refuse = "every_read"` as well (#2218). `on_page` follows the `$.Class`
919/// block's gating; the method is always registered, as `$.Class` is.
920pub(super) fn env_dollar_names(parsed_impl: &ParsedImpl, on_page: bool) -> Vec<String> {
921    let class_name = parsed_impl.class_name();
922    let h = Helpers::new(parsed_impl);
923    let mut lines = Vec::new();
924    dollar_names_doc(&mut lines, parsed_impl, on_page, true);
925    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function(x, pattern = \"\") {{",
                crate::naming::r_def_name(&::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!(".DollarNames.{0}",
                                        class_name))
                            }))))
    })format!(
926        "{} <- function(x, pattern = \"\") {{",
927        crate::naming::r_def_name(&format!(".DollarNames.{class_name}"))
928    ));
929    match h.fallback_names_call("x") {
930        // The fallback's names follow the methods, which `$` tries first
931        // (#2150).
932        Some(call) => lines.extend(Helpers::dollar_names_with_fallback(
933            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if (typeof(x) == \"externalptr\") {0}",
                call))
    })format!("if (typeof(x) == \"externalptr\") {call}"),
934            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, ls({1})", h.fields,
                class_name))
    })format!("{}, ls({class_name})", h.fields),
935        )),
936        None => lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  grep(pattern, c({0}, ls({1})), value = TRUE)",
                h.fields, class_name))
    })format!(
937            "  grep(pattern, c({}, ls({})), value = TRUE)",
938            h.fields, class_name
939        )),
940    }
941    lines.push("}".to_string());
942    lines
943}
944
945/// `$<-.Class` and its `[[<-.Class` alias for an env class with
946/// `env(r_data_accessors)`, refusing every field under `r_data_accessors =
947/// "read_only"` (#2268). An env object is a classed pointer, so a name
948/// that is not a field raises `miniextendr_no_field`; a list or environment
949/// carrying the pointer in `.ptr` writes its own element (`NextMethod()`).
950/// `on_page` follows the `$.Class` block's gating; the methods are always
951/// registered, as `$.Class` is.
952pub(super) fn env_replacement_methods(parsed_impl: &ParsedImpl, on_page: bool) -> Vec<String> {
953    let class_name = parsed_impl.class_name();
954    let h = Helpers::new(parsed_impl);
955    let mut lines = Vec::new();
956    let class_lit = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"",
                crate::naming::r_string_escape(&class_name)))
    })format!("\"{}\"", crate::naming::r_string_escape(&class_name));
957    let x = ("x", "An object.");
958    let value = ("value", value_param(parsed_impl));
959    s3_method_doc(&mut lines, parsed_impl, "$<-", on_page, true, &[x, value]);
960    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`$<-.{0}` <- function(x, name, value) {{",
                class_name))
    })format!("`$<-.{class_name}` <- function(x, name, value) {{"));
961    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  if ({0}) {{",
                not_a_field_name("name", &h.fields)))
    })format!("  if ({}) {{", not_a_field_name("name", &h.fields)));
962    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("    if (typeof(x) == \"externalptr\" && is.character(name) && length(name) == 1L) {0}(name, environment(), {1})",
                h.no_field, class_lit))
    })format!(
963        "    if (typeof(x) == \"externalptr\" && is.character(name) && length(name) == 1L) {}(name, environment(), {class_lit})",
964        h.no_field
965    ));
966    lines.push("    return(NextMethod())".to_string());
967    lines.push("  }".to_string());
968    lines.extend(h.field_write(parsed_impl, "x", "name"));
969    lines.push("}".to_string());
970    s3_method_doc(&mut lines, parsed_impl, "[[<-", on_page, true, &[]);
971    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`[[<-.{0}` <- `$<-.{0}`",
                class_name))
    })format!("`[[<-.{class_name}` <- `$<-.{class_name}`"));
972    lines
973}
974
975/// Refuses an impl method on a generic the field methods define: two
976/// definitions of `$.Class` (or `setMethod("$", "Class")`) would follow, and
977/// the later one would win. The getters-only form generates no `$<-` /
978/// `[[<-`, so a hand-written one is the point of it; the read-only form
979/// generates refusing ones (#2268); the readers (`$`, `[[`, `names`,
980/// `as.list` and `.DollarNames` on S3, `$` and `.DollarNames` on S4) are
981/// generated in every form. Env classes have no check: their methods are not
982/// S3 methods.
983pub(super) fn check_collisions(parsed_impl: &ParsedImpl) -> syn::Result<()> {
984    let writers = parsed_impl.r_data_accessors.writers();
985    let generated: &[&str] = match (parsed_impl.class_system, writers) {
986        _ if !parsed_impl.r_data_accessors.enabled() => return Ok(()),
987        (ClassSystem::S3, true) => &["$", "[[", "names", "as.list", ".DollarNames", "$<-", "[[<-"],
988        (ClassSystem::S3, false) => &["$", "[[", "names", "as.list", ".DollarNames"],
989        (ClassSystem::S4, true) => &["$", ".DollarNames", "$<-"],
990        (ClassSystem::S4, false) => &["$", ".DollarNames"],
991        _ => return Ok(()),
992    };
993    let class_name = parsed_impl.class_name();
994    for method in parsed_impl.instance_methods() {
995        // S3 dispatches an instance method under its generic, else its R
996        // name; S4 under its generic, else `s4_<name>`.
997        let generic = match parsed_impl.class_system {
998            ClassSystem::S3 => method
999                .method_attrs
1000                .generic
1001                .clone()
1002                .unwrap_or_else(|| method.r_method_name()),
1003            _ => match &method.method_attrs.generic {
1004                Some(generic) => generic.clone(),
1005                None => continue,
1006            },
1007        };
1008        // A method on another class (`s3(generic = "$", class = "other")`)
1009        // defines another class's method.
1010        if method
1011            .method_attrs
1012            .class
1013            .as_deref()
1014            .is_some_and(|class| class != class_name)
1015        {
1016            continue;
1017        }
1018        if !generated.contains(&generic.as_str()) {
1019            continue;
1020        }
1021        let system = if parsed_impl.class_system == ClassSystem::S3 {
1022            "s3"
1023        } else {
1024            "s4"
1025        };
1026        let advice = if writers && generic.ends_with("<-") {
1027            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" To write the fields with your own replacement methods, use the getters-only form `{0}(r_data_accessors = \"get\")`, which generates no `$<-` / `[[<-`.",
                system))
    })format!(
1028                " To write the fields with your own replacement methods, use the getters-only \
1029                 form `{system}(r_data_accessors = \"get\")`, which generates no `$<-` / `[[<-`."
1030            )
1031        } else {
1032            String::new()
1033        };
1034        return Err(syn::Error::new_spanned(
1035            &method.ident,
1036            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` defines the `{1}` method of `{2}`, which `{3}(r_data_accessors)` generates for the `#[r_data]` fields: the class would get two `{1}` methods. Remove the method or the option.{4}",
                method.ident, generic, class_name, system, advice))
    })format!(
1037                "`{}` defines the `{generic}` method of `{class_name}`, which \
1038                 `{system}(r_data_accessors)` generates for the `#[r_data]` fields: the class \
1039                 would get two `{generic}` methods. Remove the method or the option.{advice}",
1040                method.ident
1041            ),
1042        ));
1043    }
1044    Ok(())
1045}
1046
1047/// The `.Call` entries of the impl's field fallback (#2150): `fallback =
1048/// "Self::f"` as `C_<crate>__mx_rdata_fallback_<Type>(x, name, none)`, and
1049/// `fallback_names = "Self::g"` as `C_<crate>__mx_rdata_names_<Type>(x)`.
1050/// Nothing without a fallback.
1051///
1052/// They are the sidecar getters' kind (`externalptr_derive`): no call slot
1053/// (#344, #348), the body under `with_r_unwind_protect`, so a panic or the
1054/// function's own `rust_error!(class = ...)` reaches R as a tagged condition
1055/// the method raises on its call, and the deferred conditions signalled at
1056/// the call. They borrow the value through `sidecar_r_struct`, as a struct
1057/// field's getter does: a restored pointer raises the type's restored error
1058/// before the function runs, a pointer of another type the receiver error,
1059/// and a running method holding the value mutably
1060/// `miniextendr_borrow_conflict`.
1061///
1062/// `none` is the value of `None`: the method passes its own frame, which the
1063/// entry returns untouched, so the entry holds no R value across an
1064/// allocation and the method tells `None` from any value with
1065/// `identical()`. `Some(v)` converts `v` with `IntoR`, so `Some(None)` of an
1066/// `Option<Option<i32>>` reads `NA`. The names entry gives `character(0)`
1067/// for a pointer without its Rust value, since `.DollarNames()` never
1068/// raises; a live one calls the function on the value.
1069///
1070/// The paths resolve a leading `Self` to the impl's type, since the entries
1071/// are free functions; a function of the wrong signature is reported at the
1072/// attribute's string.
1073pub(super) fn fallback_c_entries(parsed_impl: &ParsedImpl) -> proc_macro2::TokenStream {
1074    use quote::{format_ident, quote, quote_spanned};
1075
1076    let Some(fallback) = &parsed_impl.field_fallback else {
1077        return proc_macro2::TokenStream::new();
1078    };
1079    let ty = &parsed_impl.type_ident;
1080    let type_name = crate::naming::ident_name(ty);
1081    let cfg_attrs = &parsed_impl.cfg_attrs;
1082    let path = |lit: &syn::LitStr| {
1083        let mut path: syn::Path = lit
1084            .parse()
1085            .expect("the impl attribute parser checked the path");
1086        crate::util::resolve_self(&mut path, ty);
1087        path
1088    };
1089
1090    let get = path(&fallback.get);
1091    let span = fallback.get.span();
1092    // The `Option` and the conversion are spanned at the attribute's string,
1093    // so a function that returns no `Option`, or an `Option` of a type
1094    // without `IntoR`, is reported there. A failed conversion raises the
1095    // classed `result_err` condition (#2272).
1096    let conversion = crate::c_wrapper_builder::return_conversion_at(
1097        &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "v");
    _s
}quote!(v),
1098        &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "None");
    _s
}quote!(::core::option::Option::None),
1099        span,
1100    );
1101    let value = {
    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, "match");
    ::quote::ToTokens::to_tokens(&get, &mut _s);
    ::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");
            ::quote::__private::push_comma_spanned(&mut _s, _span);
            ::quote::__private::push_and_spanned(&mut _s, _span);
            ::quote::__private::push_ident_spanned(&mut _s, _span,
                "__mx_name");
            _s
        });
    ::quote::__private::push_group_spanned(&mut _s, _span,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            let _span: ::quote::__private::Span =
                ::quote::__private::get_span(_span).__into_span();
            ::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, "option");
            ::quote::__private::push_colon2_spanned(&mut _s, _span);
            ::quote::__private::push_ident_spanned(&mut _s, _span, "Option");
            ::quote::__private::push_colon2_spanned(&mut _s, _span);
            ::quote::__private::push_ident_spanned(&mut _s, _span, "Some");
            ::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, "v");
                    _s
                });
            ::quote::__private::push_fat_arrow_spanned(&mut _s, _span);
            ::quote::ToTokens::to_tokens(&conversion, &mut _s);
            ::quote::__private::push_comma_spanned(&mut _s, _span);
            ::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, "option");
            ::quote::__private::push_colon2_spanned(&mut _s, _span);
            ::quote::__private::push_ident_spanned(&mut _s, _span, "Option");
            ::quote::__private::push_colon2_spanned(&mut _s, _span);
            ::quote::__private::push_ident_spanned(&mut _s, _span, "None");
            ::quote::__private::push_fat_arrow_spanned(&mut _s, _span);
            ::quote::__private::push_ident_spanned(&mut _s, _span, "none");
            ::quote::__private::push_comma_spanned(&mut _s, _span);
            _s
        });
    _s
}quote_spanned! {span=>
1102        match #get(__mx_value, &__mx_name) {
1103            ::core::option::Option::Some(v) => #conversion,
1104            ::core::option::Option::None => none,
1105        }
1106    };
1107    let c_ident = match ::quote::__private::IdentFragmentAdapter(&crate::naming::sidecar_fallback_c_name(&type_name))
    {
    arg =>
        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("{0}", arg))
                    }), ::quote::__private::Option::None.or(arg.span())),
}format_ident!("{}", crate::naming::sidecar_fallback_c_name(&type_name));
1108    let def_ident = ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__MX_CALL_DEF_RDATA_FALLBACK_{0}",
                        type_name))
            }), ::quote::__private::Option::None)format_ident!("__MX_CALL_DEF_RDATA_FALLBACK_{type_name}");
1109    let registration = crate::call_method_def::call_method_def(&def_ident, &c_ident, 3);
1110    let doc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated fallback of the field methods of Rust type `{1}` (`fallback = {0:?}`).",
                fallback.get.value(), type_name))
    })format!(
1111        "Generated fallback of the field methods of Rust type `{type_name}` (`fallback = {:?}`).",
1112        fallback.get.value()
1113    );
1114    let mut entries = {
    let mut _s = ::quote::__private::TokenStream::new();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut cfg_attrs, i) = cfg_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let cfg_attrs =
                match cfg_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&cfg_attrs, &mut _s);
        }
    }
    ::quote::__private::push_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::__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(&c_ident, &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, "name");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "none");
            ::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, "let");
                            ::quote::__private::push_ident(&mut _s, "__mx_name");
                            ::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, "string");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "String");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "match");
                            ::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_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, "name");
                                    _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, "name");
                                            _s
                                        });
                                    ::quote::__private::push_fat_arrow(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "name");
                                    ::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, "err");
                                            _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, "core");
                                            ::quote::__private::push_colon2(&mut _s);
                                            ::quote::__private::push_ident(&mut _s, "panic");
                                            ::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,
                                                        "\"the field fallback takes one name: {err}\"");
                                                    _s
                                                });
                                            _s
                                        });
                                    _s
                                });
                            ::quote::__private::push_semi(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "let");
                            ::quote::__private::push_ident(&mut _s, "__mx_data");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "unsafe");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Brace,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "externalptr");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "sidecar_r_struct");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::ToTokens::to_tokens(&ty, &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
                                        });
                                    _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_colon(&mut _s);
                            ::quote::__private::push_and(&mut _s);
                            ::quote::ToTokens::to_tokens(&ty, &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);
                            ::quote::ToTokens::to_tokens(&value, &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
        });
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut cfg_attrs, i) = cfg_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let cfg_attrs =
                match cfg_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&cfg_attrs, &mut _s);
        }
    }
    ::quote::__private::push_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(&registration, &mut _s);
    _s
}quote! {
1115        #(#cfg_attrs)*
1116        #[doc = #doc]
1117        #[doc(hidden)]
1118        #[unsafe(no_mangle)]
1119        #[allow(non_snake_case)]
1120        pub unsafe extern "C-unwind" fn #c_ident(
1121            x: ::miniextendr_api::SEXP,
1122            name: ::miniextendr_api::SEXP,
1123            none: ::miniextendr_api::SEXP,
1124        ) -> ::miniextendr_api::SEXP {
1125            let __miniextendr_deferred_mark = ::miniextendr_api::deferred_condition::mark();
1126            let __miniextendr_value = ::miniextendr_api::unwind_protect::with_r_unwind_protect(
1127                || {
1128                    // The readers pass one name, a string.
1129                    let __mx_name: ::std::string::String =
1130                        match ::miniextendr_api::TryFromSexp::try_from_sexp(name) {
1131                            ::core::result::Result::Ok(name) => name,
1132                            ::core::result::Result::Err(err) => {
1133                                ::core::panic!("the field fallback takes one name: {err}")
1134                            }
1135                        };
1136                    let __mx_data =
1137                        unsafe { ::miniextendr_api::externalptr::sidecar_r_struct::<#ty>(x) };
1138                    let __mx_value: &#ty = &__mx_data;
1139                    #value
1140                },
1141                ::core::option::Option::None,
1142            );
1143            unsafe {
1144                ::miniextendr_api::deferred_condition::finish(
1145                    __miniextendr_deferred_mark,
1146                    __miniextendr_value,
1147                    ::core::option::Option::None,
1148                )
1149            }
1150        }
1151
1152        #(#cfg_attrs)*
1153        #[doc(hidden)]
1154        #registration
1155    };
1156
1157    if let Some(names) = &fallback.names {
1158        let names_path = path(names);
1159        let span = names.span();
1160        let value = {
    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, "let");
    ::quote::__private::push_ident_spanned(&mut _s, _span, "__mx_names");
    ::quote::__private::push_colon_spanned(&mut _s, _span);
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "std");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "vec");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "Vec");
    ::quote::__private::push_lt_spanned(&mut _s, _span);
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "std");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "string");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "String");
    ::quote::__private::push_gt_spanned(&mut _s, _span);
    ::quote::__private::push_eq_spanned(&mut _s, _span);
    ::quote::ToTokens::to_tokens(&names_path, &mut _s);
    ::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
        });
    ::quote::__private::push_semi_spanned(&mut _s, _span);
    _s
}quote_spanned! {span=>
1161            let __mx_names: ::std::vec::Vec<::std::string::String> = #names_path(__mx_value);
1162        };
1163        let names_sexp = crate::c_wrapper_builder::return_conversion(
1164            &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "__mx_names");
    _s
}quote!(__mx_names),
1165            &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "None");
    _s
}quote!(::core::option::Option::None),
1166        );
1167        let c_ident = match ::quote::__private::IdentFragmentAdapter(&crate::naming::sidecar_fallback_names_c_name(&type_name))
    {
    arg =>
        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("{0}", arg))
                    }), ::quote::__private::Option::None.or(arg.span())),
}format_ident!(
1168            "{}",
1169            crate::naming::sidecar_fallback_names_c_name(&type_name)
1170        );
1171        let def_ident = ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__MX_CALL_DEF_RDATA_NAMES_{0}",
                        type_name))
            }), ::quote::__private::Option::None)format_ident!("__MX_CALL_DEF_RDATA_NAMES_{type_name}");
1172        let registration = crate::call_method_def::call_method_def(&def_ident, &c_ident, 1);
1173        let doc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated completions of the field fallback of Rust type `{1}` (`fallback_names = {0:?}`).",
                names.value(), type_name))
    })format!(
1174            "Generated completions of the field fallback of Rust type `{type_name}` \
1175             (`fallback_names = {:?}`).",
1176            names.value()
1177        );
1178        entries.extend({
    let mut _s = ::quote::__private::TokenStream::new();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut cfg_attrs, i) = cfg_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let cfg_attrs =
                match cfg_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&cfg_attrs, &mut _s);
        }
    }
    ::quote::__private::push_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::__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(&c_ident, &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);
            _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, "into_r");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "IntoR");
                            ::quote::__private::push_semi(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "if");
                            ::quote::__private::push_bang(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "unsafe");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Brace,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "externalptr");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "sidecar_r_live");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::ToTokens::to_tokens(&ty, &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, "false");
                                            _s
                                        });
                                    _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::__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_colon2(&mut _s);
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "std");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "string");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "String");
                                    ::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,
                                        ::quote::__private::TokenStream::new());
                                    ::quote::__private::push_dot(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "into_sexp");
                                    ::quote::__private::push_group(&mut _s,
                                        ::quote::__private::Delimiter::Parenthesis,
                                        ::quote::__private::TokenStream::new());
                                    ::quote::__private::push_semi(&mut _s);
                                    _s
                                });
                            ::quote::__private::push_ident(&mut _s, "let");
                            ::quote::__private::push_ident(&mut _s, "__mx_data");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "unsafe");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Brace,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "externalptr");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "sidecar_r_struct");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::ToTokens::to_tokens(&ty, &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
                                        });
                                    _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_colon(&mut _s);
                            ::quote::__private::push_and(&mut _s);
                            ::quote::ToTokens::to_tokens(&ty, &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);
                            ::quote::ToTokens::to_tokens(&value, &mut _s);
                            ::quote::ToTokens::to_tokens(&names_sexp, &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
        });
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut cfg_attrs, i) = cfg_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let cfg_attrs =
                match cfg_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&cfg_attrs, &mut _s);
        }
    }
    ::quote::__private::push_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(&registration, &mut _s);
    _s
}quote! {
1179            #(#cfg_attrs)*
1180            #[doc = #doc]
1181            #[doc(hidden)]
1182            #[unsafe(no_mangle)]
1183            #[allow(non_snake_case)]
1184            pub unsafe extern "C-unwind" fn #c_ident(
1185                x: ::miniextendr_api::SEXP,
1186            ) -> ::miniextendr_api::SEXP {
1187                let __miniextendr_deferred_mark = ::miniextendr_api::deferred_condition::mark();
1188                let __miniextendr_value = ::miniextendr_api::unwind_protect::with_r_unwind_protect(
1189                    || {
1190                        use ::miniextendr_api::into_r::IntoR;
1191                        if !unsafe { ::miniextendr_api::externalptr::sidecar_r_live::<#ty>(x, false) } {
1192                            return ::std::vec::Vec::<::std::string::String>::new().into_sexp();
1193                        }
1194                        let __mx_data =
1195                            unsafe { ::miniextendr_api::externalptr::sidecar_r_struct::<#ty>(x) };
1196                        let __mx_value: &#ty = &__mx_data;
1197                        #value
1198                        #names_sexp
1199                    },
1200                    ::core::option::Option::None,
1201                );
1202                unsafe {
1203                    ::miniextendr_api::deferred_condition::finish(
1204                        __miniextendr_deferred_mark,
1205                        __miniextendr_value,
1206                        ::core::option::Option::None,
1207                    )
1208                }
1209            }
1210
1211            #(#cfg_attrs)*
1212            #[doc(hidden)]
1213            #registration
1214        });
1215    }
1216    entries
1217}