Skip to main content

miniextendr_macros/
lib.rs

1//! # miniextendr-macros - Procedural macros for Rust <-> R interop
2//!
3//! This crate provides the procedural macros that power miniextendr's code
4//! generation. Most users should depend on `miniextendr-api` and use its
5//! re-exports, but this crate can be used directly when you only need macros.
6//!
7//! Primary macros and derives:
8//! - `#[miniextendr]` on functions, impl blocks, trait defs, and trait impls.
9//! - `#[r_ffi_checked]` for main-thread routing of C-ABI wrappers.
10//! - Derives: `ExternalPtr`, `RNativeType`, ALTREP derives, `RFactor`.
11//! - Helpers: `typed_list` for typed list builders.
12//!
13//! R wrapper generation is driven by Rust doc comments (roxygen tags are
14//! extracted). During package build, the wrapper-gen pass loads the installed
15//! shared object into R and calls `miniextendr_write_wrappers`, which walks the
16//! linkme `#[distributed_slice]` tables and writes `R/<pkg>-wrappers.R`.
17//!
18//! ## Quick start
19//!
20//! ```ignore
21//! use miniextendr_api::miniextendr;
22//!
23//! #[miniextendr]
24//! fn add(a: i32, b: i32) -> i32 {
25//!     a + b
26//! }
27//! ```
28//!
29//! ## Macro expansion pipeline
30//!
31//! ### Overview
32//!
33//! ```text
34//! ┌──────────────────────────────────────────────────────────────────────────┐
35//! │                         #[miniextendr] on fn                             │
36//! │                                                                          │
37//! │  1. Parse: syn::ItemFn → MiniextendrFunctionParsed                       │
38//! │  2. Analyze return type (Result<T>, Option<T>, raw SEXP, etc.)           │
39//! │  3. Generate:                                                            │
40//! │     ├── C wrapper: extern "C-unwind" fn C_<crate>_<name>(...) → SEXP     │
41//! │     ├── R wrapper: static R_WRAPPER_<name>: RWrapperEntry                  │
42//! │     └── Registration: const call_method_def_<name>: R_CallMethodDef      │
43//! │  4. Original function preserved (with added attributes)                  │
44//! └──────────────────────────────────────────────────────────────────────────┘
45//!
46//! ┌──────────────────────────────────────────────────────────────────────────┐
47//! │                    #[miniextendr(env|r6|s3|s4|s7)] on impl               │
48//! │                                                                          │
49//! │  1. Parse: syn::ItemImpl → extract methods                               │
50//! │  2. For each method:                                                     │
51//! │     ├── Generate C wrapper (handles self parameter)                      │
52//! │     ├── Generate R method wrapper string                                 │
53//! │     └── Generate registration entry                                      │
54//! │  3. Generate class definition code per class system:                     │
55//! │     ├── env: new.env() + method assignment                               │
56//! │     ├── r6: R6Class() definition                                         │
57//! │     ├── s3: S3 generics + methods                                        │
58//! │     ├── s4: setClass() + setMethod()                                     │
59//! │     └── s7: new_class() definition                                       │
60//! │  4. Emit const with combined R code                                      │
61//! └──────────────────────────────────────────────────────────────────────────┘
62//!
63//! ┌──────────────────────────────────────────────────────────────────────────┐
64//! │                         #[miniextendr] on trait                          │
65//! │                                                                          │
66//! │  1. Parse: syn::ItemTrait → extract method signatures                    │
67//! │  2. Generate:                                                            │
68//! │     ├── Trait tag constant: const TAG_<TRAIT>: mx_tag = ...              │
69//! │     ├── Vtable struct: struct __vtable_<Trait> { ... }                   │
70//! │     └── CCalls table: static MX_CCALL_<TRAIT>: [...] = ...               │
71//! │  3. Original trait preserved                                             │
72//! └──────────────────────────────────────────────────────────────────────────┘
73//!
74//! ┌──────────────────────────────────────────────────────────────────────────┐
75//! │                    #[miniextendr] impl Trait for Type                    │
76//! │                                                                          │
77//! │  1. Parse: syn::ItemImpl (trait impl)                                    │
78//! │  2. Generate:                                                            │
79//! │     ├── Vtable instance: static __VTABLE_<crate>_<Trait>_FOR_<Type>     │
80//! │     ├── Shared runtime storage: ErasedObject<Type>                     │
81//! │     ├── Shared query: registry::universal_query                        │
82//! │     └── Base vtable: static __MX_BASE_VTABLE_<Type>: ...                 │
83//! │  3. Original impl preserved                                              │
84//! └──────────────────────────────────────────────────────────────────────────┘
85//!
86//! ```
87//!
88//! ### Key Modules
89//!
90//! | Module | Purpose |
91//! |--------|---------|
92//! | `miniextendr_fn` | Function parsing and attribute handling |
93//! | `c_wrapper_builder` | C wrapper generation (`extern "C-unwind"`) |
94//! | `r_wrapper_builder` | R wrapper code generation |
95//! | `rust_conversion_builder` | Rust→SEXP return value conversion |
96//! | `miniextendr_impl` | `impl Type` block processing |
97//! | `r_class_formatter` | Class system code generation (env/r6/s3/s4/s7) |
98//! | `miniextendr_trait` | Trait ABI metadata generation |
99//! | `miniextendr_impl_trait` | `impl Trait for Type` vtable generation |
100//! | `altrep` / `altrep_derive` | ALTREP struct derivation |
101//! | `externalptr_derive` | `#[derive(ExternalPtr)]` |
102//! | `roxygen` | Roxygen doc comment handling |
103//!
104//! ### Generated Symbol Naming
105//!
106//! Every `#[no_mangle]` symbol is prefixed with the consuming crate's name
107//! (from `CARGO_CRATE_NAME`) so two packages loaded into one webR session
108//! can't collide on a C symbol (#1273; helpers in `naming.rs`). For a
109//! function `my_func` in a crate `mypkg`:
110//! - C wrapper: `C_mypkg_my_func`
111//! - R wrapper registration: `R_WRAPPER_my_func`
112//! - Registration: `call_method_def_my_func`
113//!
114//! For a type `MyType` with trait `Counter` in a crate `mypkg`:
115//! - Vtable: `__VTABLE_mypkg_Counter_FOR_MyType`
116//! - Storage: runtime `ErasedObject<MyType>`
117//! - Query: `__mx_query_mytype`
118//!
119//! ## Return Type Handling
120//!
121//! `c_wrapper_builder::detect_return_handling` determines how to convert Rust returns to SEXP:
122//!
123//! | Rust Type | Strategy | R Result |
124//! |-----------|----------|----------|
125//! | `T: IntoR` | `.try_into_sexp()`, a failure raised like an `Err` | Converted value or error |
126//! | `Result<T, E>` | Unwrap or R error | Value or error |
127//! | `Option<T>` | `Some` → value, `None` → `NULL` | Value or NULL |
128//! | `SEXP` | Pass through | Raw SEXP |
129//! | `()` | Invisible NULL | `invisible(NULL)` |
130//!
131//! Use `#[miniextendr(unwrap_in_r)]` to return `Result<T, E>` to R without unwrapping.
132//!
133//! ## Execution
134//!
135//! `#[miniextendr]` functions run on R's main thread, inside
136//! `with_r_unwind_protect`: a Rust panic becomes an R condition, and an R
137//! error unwinds through the Rust frames with their destructors.
138//!
139//! ## Class Systems
140//!
141//! The `r_class_formatter` module generates R code for different class systems:
142//!
143//! | System | Generated R Code | Self Parameter |
144//! |--------|------------------|----------------|
145//! | `env` | `new.env()` with methods | `self` environment |
146//! | `r6` | `R6Class()` | `self` environment |
147//! | `s3` | `structure()` + generics | First argument |
148//! | `s4` | `setClass()` + `setMethod()` | First argument |
149//! | `s7` | `new_class()` | `self` property |
150
151// miniextendr-macros procedural macros
152
153mod altrep;
154mod c_wrapper_builder;
155mod call_method_def;
156mod cfg_gates;
157mod dots_policy;
158mod externalptr_args;
159mod list_macro;
160mod match_arg_keys;
161mod miniextendr_fn;
162mod receiver_body;
163mod return_wrap;
164mod s7_conversion;
165mod trait_receiver;
166mod trait_self_ref;
167mod trait_signature;
168mod type_inspect;
169mod typed_dataframe;
170mod typed_list;
171mod util;
172use crate::miniextendr_fn::{MiniextendrFnAttrs, MiniextendrFunctionParsed};
173mod miniextendr_impl;
174mod r_wrapper_builder;
175/// Builder utilities for formatting R wrapper arguments and calls.
176pub(crate) use r_wrapper_builder::RArgumentBuilder;
177mod rust_conversion_builder;
178/// Helper for generating Rust→R conversion code for return values.
179pub(crate) use rust_conversion_builder::RustConversionBuilder;
180mod method_return_builder;
181/// Helpers for shaping method return handling (R vs Rust wrapper code).
182pub(crate) use method_return_builder::{MethodReturnBuilder, ReturnStrategy};
183mod altrep_derive;
184mod condition_derive;
185mod dataframe_derive;
186mod lifecycle;
187mod list_derive;
188mod r_class_formatter;
189mod r_preconditions;
190mod r_shadowing;
191mod return_type_analysis;
192mod roxygen;
193
194// Trait ABI support modules
195mod all_equal_derive;
196mod externalptr_derive;
197mod miniextendr_impl_trait;
198mod miniextendr_trait;
199mod typed_external_macro;
200
201// Factor support
202mod factor_derive;
203mod match_arg_derive;
204mod newtype_derive;
205
206// Struct/enum dispatch for #[miniextendr] on structs and enums
207mod struct_enum_dispatch;
208// Its fallback's diagnostic for a Rust `...` parameter that is not last
209mod misplaced_dots;
210
211// r! proc-macro implementation
212mod r_macro;
213
214// reexport! proc-macro implementation
215mod reexport;
216
217// vctrs support
218#[cfg(feature = "vctrs")]
219mod vctrs_derive;
220mod vctrs_generics;
221
222mod crate_config;
223mod naming;
224pub(crate) use naming::r_wrapper_const_ident_for;
225
226// Feature default mutual exclusivity guards
227#[cfg(all(feature = "r6-default", feature = "s7-default"))]
228compile_error!(
229    "features \"r6-default\" and \"s7-default\" are mutually exclusive — \
230     enable exactly one, or omit both to fall back to the unspecified default"
231);
232pub(crate) use type_inspect::{
233    SeveralOkContainer, classify_several_ok_container, first_type_argument, match_arg_choices_ty,
234    second_type_argument,
235};
236pub(crate) use util::{
237    extract_cfg_attrs, r_wrapper_raw_literal, source_location_doc, source_position,
238};
239
240/// Validate the signature of an `extern "C-unwind"` fn exported via `#[miniextendr]`.
241///
242/// R's `.Call` interface passes all arguments as `SEXP` and expects a `SEXP`
243/// return value. For `extern "C-unwind"` functions the user writes the C symbol
244/// directly, so the signature must satisfy those invariants statically —
245/// otherwise the generated registration produces UB at runtime.
246///
247/// Called before any codegen so we fail fast on an invalid extern signature
248/// rather than emitting a wrapper that would only matter after the error.
249fn validate_extern_signature(
250    abi: &syn::Abi,
251    attrs: &[syn::Attribute],
252    inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
253    output: &syn::ReturnType,
254) -> syn::Result<()> {
255    use syn::spanned::Spanned;
256
257    // Reject `self` receivers up front — they are never valid for `.Call`
258    // exports, and a missing-return-type error would only hide the real
259    // problem (users write `fn foo(self)` to ask "can I export a method?").
260    for input in inputs.iter() {
261        if let syn::FnArg::Receiver(recv) = input {
262            return Err(syn::Error::new_spanned(
263                recv,
264                "self parameter not allowed in standalone functions; \
265                 use #[miniextendr(env|r6|s3|s4|s7)] on impl blocks instead",
266            ));
267        }
268    }
269
270    // Require one of #[no_mangle] / #[unsafe(no_mangle)] / #[export_name].
271    let has_no_mangle = attrs.iter().any(|attr| {
272        attr.path().is_ident("no_mangle")
273            || attr
274                .parse_nested_meta(|meta| {
275                    if meta.path.is_ident("no_mangle") {
276                        Err(meta.error("found #[no_mangle]"))
277                    } else {
278                        Ok(())
279                    }
280                })
281                .is_err()
282    });
283    let has_export_name = attrs.iter().any(|attr| attr.path().is_ident("export_name"));
284    if !has_no_mangle && !has_export_name {
285        return Err(syn::Error::new(
286            attrs
287                .first()
288                .map(|attr| attr.span())
289                .unwrap_or_else(|| abi.span()),
290            "extern \"C-unwind\" functions need a visible C symbol for R's .Call interface. \
291             Add one of:\n  \
292             - `#[unsafe(no_mangle)]` (Rust 2024 edition)\n  \
293             - `#[no_mangle]` (Rust 2021 edition)\n  \
294             - `#[export_name = \"my_symbol\"]` (custom symbol name)",
295        ));
296    }
297
298    // Return type must be SEXP.
299    match output {
300        non_return_type @ syn::ReturnType::Default => {
301            return Err(syn::Error::new(
302                non_return_type.span(),
303                "extern \"C-unwind\" functions used with #[miniextendr] must return SEXP. \
304                 Add `-> miniextendr_api::SEXP` as the return type. \
305                 If you want automatic type conversion, remove `extern \"C-unwind\"` and let \
306                 the macro generate the C wrapper.",
307            ));
308        }
309        syn::ReturnType::Type(_rarrow, output_type) => match output_type.as_ref() {
310            syn::Type::Path(type_path) => {
311                if let Some(path_to_sexp) = type_path.path.segments.last().map(|x| &x.ident)
312                    && path_to_sexp != "SEXP"
313                {
314                    return Err(syn::Error::new(
315                        path_to_sexp.span(),
316                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("extern \"C-unwind\" functions must return SEXP, found `{0}`. R\'s .Call interface expects SEXP return values. Change the return type to `miniextendr_api::SEXP`, or remove `extern \"C-unwind\"` to let the macro handle type conversion.",
                path_to_sexp))
    })format!(
317                            "extern \"C-unwind\" functions must return SEXP, found `{path_to_sexp}`. \
318                             R's .Call interface expects SEXP return values. \
319                             Change the return type to `miniextendr_api::SEXP`, or remove \
320                             `extern \"C-unwind\"` to let the macro handle type conversion.",
321                        ),
322                    ));
323                }
324            }
325            _ => {
326                return Err(syn::Error::new(
327                    output_type.span(),
328                    "extern \"C-unwind\" functions must return SEXP. \
329                     R's .Call interface expects SEXP return values. \
330                     Change the return type to `miniextendr_api::SEXP`, or remove \
331                     `extern \"C-unwind\"` to let the macro handle type conversion.",
332                ));
333            }
334        },
335    }
336
337    // Every input must be SEXP. Reject variadics and receivers.
338    for input in inputs.iter() {
339        match input {
340            syn::FnArg::Receiver(recv) => {
341                return Err(syn::Error::new_spanned(
342                    recv,
343                    "extern \"C-unwind\" functions cannot have a `self` parameter. \
344                     R's .Call interface only accepts SEXP arguments. \
345                     Use `#[miniextendr(env|r6|s3|s4|s7)]` on an impl block for methods.",
346                ));
347            }
348            syn::FnArg::Typed(pat_type) => {
349                if let syn::Pat::Rest(_) = pat_type.pat.as_ref() {
350                    return Err(syn::Error::new_spanned(
351                        pat_type,
352                        "extern functions cannot use variadic (...) - .Call passes fixed arguments",
353                    ));
354                }
355                let is_sexp = match pat_type.ty.as_ref() {
356                    syn::Type::Path(type_path) => type_path
357                        .path
358                        .segments
359                        .last()
360                        .is_some_and(|seg| seg.ident == "SEXP"),
361                    _ => false,
362                };
363                if !is_sexp && crate::type_inspect::is_lazy_dots_marker(&pat_type.ty) {
364                    return Err(syn::Error::new_spanned(
365                        &pat_type.ty,
366                        "extern functions cannot take `LazyDots`: it is the generated R \
367                         wrapper's frame (`environment()`), and `.Call()` reaches an extern \
368                         function directly. Drop the `extern \"C-unwind\"` to let the macro \
369                         generate the wrapper",
370                    ));
371                }
372                if !is_sexp {
373                    let is_dots_type = if let syn::Type::Reference(type_ref) = pat_type.ty.as_ref()
374                    {
375                        if let syn::Type::Path(inner) = type_ref.elem.as_ref() {
376                            inner
377                                .path
378                                .segments
379                                .last()
380                                .is_some_and(|seg| seg.ident == "Dots")
381                        } else {
382                            false
383                        }
384                    } else if let syn::Type::Path(type_path) = pat_type.ty.as_ref() {
385                        type_path
386                            .path
387                            .segments
388                            .last()
389                            .is_some_and(|seg| seg.ident == "Dots")
390                    } else {
391                        false
392                    };
393                    let msg = if is_dots_type {
394                        "extern functions cannot use Dots; use `...` syntax in non-extern #[miniextendr] functions instead"
395                    } else {
396                        "extern function parameters must be SEXP - .Call passes all arguments as SEXP"
397                    };
398                    return Err(syn::Error::new_spanned(&pat_type.ty, msg));
399                }
400            }
401        }
402    }
403
404    Ok(())
405}
406
407/// Builds the `let dots_typed = <dots>.typed(<spec>)...` statement injected
408/// at the start of a function body when `#[miniextendr(dots =
409/// typed_list!(...))]` is used.
410///
411/// Raises through `arg_error!` so validation keeps the argument-condition
412/// kind, the R parameter name (`...`), and the crate's configured classes.
413/// Display formatting preserves TypedListError's human-readable diagnostics.
414pub(crate) fn build_dots_validation_stmt(
415    dots_param: &syn::Ident,
416    spec_tokens: &proc_macro2::TokenStream,
417) -> syn::Stmt {
418    ::syn::__private::parse_quote({
        let mut _s = ::quote::__private::TokenStream::new();
        ::quote::__private::push_ident(&mut _s, "let");
        ::quote::__private::push_ident(&mut _s, "dots_typed");
        ::quote::__private::push_eq(&mut _s);
        ::quote::ToTokens::to_tokens(&dots_param, &mut _s);
        ::quote::__private::push_dot(&mut _s);
        ::quote::__private::push_ident(&mut _s, "typed");
        ::quote::__private::push_group(&mut _s,
            ::quote::__private::Delimiter::Parenthesis,
            {
                let mut _s = ::quote::__private::TokenStream::new();
                ::quote::ToTokens::to_tokens(&spec_tokens, &mut _s);
                _s
            });
        ::quote::__private::push_dot(&mut _s);
        ::quote::__private::push_ident(&mut _s, "unwrap_or_else");
        ::quote::__private::push_group(&mut _s,
            ::quote::__private::Delimiter::Parenthesis,
            {
                let mut _s = ::quote::__private::TokenStream::new();
                ::quote::__private::push_or(&mut _s);
                ::quote::__private::push_ident(&mut _s, "e");
                ::quote::__private::push_or(&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, "arg_error");
                ::quote::__private::push_bang(&mut _s);
                ::quote::__private::push_group(&mut _s,
                    ::quote::__private::Delimiter::Parenthesis,
                    {
                        let mut _s = ::quote::__private::TokenStream::new();
                        ::quote::__private::push_ident(&mut _s, "param");
                        ::quote::__private::push_eq(&mut _s);
                        ::quote::__private::parse(&mut _s, "\"...\"");
                        ::quote::__private::push_comma(&mut _s);
                        ::quote::__private::parse(&mut _s,
                            "\"dots validation failed: {e}\"");
                        _s
                    });
                _s
            });
        ::quote::__private::push_semi(&mut _s);
        _s
    });syn::parse_quote! {
419        let dots_typed = #dots_param.typed(#spec_tokens)
420            .unwrap_or_else(|e| ::miniextendr_api::arg_error!(
421                param = "...", "dots validation failed: {e}"
422            ));
423    }
424}
425
426/// Export Rust items to R.
427///
428/// `#[miniextendr]` can be applied to:
429/// - `fn` items (generate C + R wrappers)
430/// - `impl` blocks (generate R class methods)
431/// - `trait` items (generate trait ABI metadata)
432/// - ALTREP wrapper structs (generate `RegisterAltrep` impls)
433///
434/// # Functions
435///
436/// ```ignore
437/// use miniextendr_api::miniextendr;
438///
439/// #[miniextendr]
440/// fn add(a: i32, b: i32) -> i32 { a + b }
441/// ```
442///
443/// This produces a C wrapper `C_<crate>_add` and an R wrapper `add()`.
444/// Registration is automatic via linkme distributed slices.
445///
446/// ## `extern "C-unwind"`
447///
448/// If the function is declared `extern "C-unwind"` and exported with
449/// `#[no_mangle]` (2021), `#[unsafe(no_mangle)]` (2024), or `#[export_name = "..."]`,
450/// the function itself is the C symbol and the R wrapper is prefixed with
451/// `unsafe_` to signal bypassed safety (no argument conversion or panic handling).
452///
453/// ## Variadics (`...`)
454///
455/// Use `name: ...` as the last argument. It becomes a `name: &Dots`
456/// parameter (`args: ...` → `args: &Dots`), through which the body reads
457/// the dots. For dots the function ignores, write `_: ...`. rustc rejects a
458/// bare `...` before the macro runs (the deny-by-default
459/// `varargs_without_pattern` lint) and suggests `_: ...`. The R formal is
460/// plain `...` either way.
461///
462/// An explicit `rest: &Dots` parameter is R's `...` too, at any position:
463/// `fn f(x: i32, rest: &Dots, overwrite: bool)` becomes
464/// `f <- function(x, ..., overwrite)`, and R matches a formal after `...` by
465/// its exact name only. A function takes at most one `...`.
466///
467/// ### Typed Dots Validation
468///
469/// Use `#[miniextendr(dots = typed_list!(...))]` to automatically validate dots
470/// and create a `dots_typed` variable with typed accessors:
471///
472/// ```ignore
473/// #[miniextendr(dots = typed_list!(x => numeric(), y => integer(), z? => character()))]
474/// pub fn my_func(_: ...) -> String {
475///     let x: f64 = dots_typed.get("x").expect("x");
476///     let y: i32 = dots_typed.get("y").expect("y");
477///     let z: Option<String> = dots_typed.get_opt("z").expect("z");
478///     format!("x={}, y={}", x, y)
479/// }
480/// ```
481///
482/// Type specs: `numeric()`, `integer()`, `logical()`, `character()`, `list()`,
483/// `raw()`, `complex()`, or `"class_name"` for class inheritance checks.
484/// Add `(n)` for exact length: `numeric(4)`. Use `?` suffix for optional fields.
485/// Use `@exact;` prefix for strict mode (reject extra fields).
486///
487/// ## Attributes
488///
489/// - `#[miniextendr(invisible)]` / `#[miniextendr(visible)]` — control return visibility
490///   (identical to an `Invisible<T>` / `Visible<T>` return type; the two must agree).
491///   Only unit-`NULL` returns are invisible by default; receiver-returning
492///   method tails are visible unless marked (#1213).
493/// - `#[miniextendr(check_interrupt)]` — check for a user interrupt once, before the
494///   arguments are converted and the body runs
495/// - `#[miniextendr(coerce)]` — widen the R types a parameter accepts (`i32`, `f64`, `bool` and
496///   the other numeric scalars, as `T`, `Vec<T>`, `Option<T>` or `Vec<Option<T>>`, each also
497///   under `Missing<..>`); also usable per-parameter, where a type it cannot widen is a compile
498///   error
499/// - `#[miniextendr(convert)]` on a reference parameter — use its own conversion rather than
500///   an ExternalPtr borrow; on inherent/trait impl methods, write `#[miniextendr(convert(param))]`.
501/// - `#[miniextendr(rng)]` — load R's RNG state before the body and save it after;
502///   a `&RngGuard` parameter (no R argument) receives the guard to draw from
503/// - `#[miniextendr(rng(seed = <param>))]` — `rng`, plus the seed contract of
504///   `stats::simulate()` in the R wrapper (#2198), for standalone functions and
505///   `s3(...)` methods. `<param>` names the seed parameter by its Rust name.
506///   After the argument checks the wrapper creates `.Random.seed` if it is
507///   missing; with a non-`NULL` seed it calls `set.seed(seed)` (which validates
508///   it, so the parameter has no R-side type check) and puts the session's
509///   `.Random.seed` back on exit, also after an error or a panic. The result
510///   gets a `seed` attribute: the seed with `kind = as.list(RNGkind())`, or the
511///   pre-draw `.Random.seed` for `seed = NULL`; a value that can't carry
512///   attributes is left as it is. A unit return, an impl or trait method, and a
513///   name that is no evaluated R argument are compile errors.
514/// - `#[miniextendr(serialize)]` — serialize the complete return through `AsSerialize<T>`
515///   (requires the API `serde` feature); composes with return visibility markers
516/// - `#[miniextendr(strict)]` — reject lossy conversions for i64/u64/isize/usize
517/// - `#[miniextendr(unwrap_in_r)]` — return `Result<T, E>` to R without unwrapping
518/// - `#[miniextendr(serde_error(tag = "..", prefix = "..", skip(..), rename(a = ".."))]` —
519///   options for the serde-classed `Err` arm. The path itself is automatic under the
520///   API crate's `serde` feature for every `Result<T, E>` with `E: Serialize + Display`.
521///   `as_character("a", ..)`, `as_integer(..)`, `as_double(..)` and `as_logical(..)` give
522///   payload fields that atomic R type, as the `serde::as_*` field helpers would from the
523///   error type itself; like `skip` and `rename` they name fields as the error serializes
524///   them, before any rename. A field takes one `as_*` option and is not also skipped
525///   (compile errors, all reported at once). A
526///   `miniextendr_api::condition::SerdeErrorShape` const holds any of these options;
527///   `miniextendr_api::serde_error_shape!(Error = ENGINE)` declares it once for an error
528///   type, and every function or method of the crate returning that type applies it
529///   first, with or without this attribute. `shape = PATH` names another one per
530///   function: `serde_error(shape = STRICT, as_double("n"))` applies the declared shape,
531///   then `STRICT`, then the function's own options; the later wins for a field set more
532///   than once. The path resolves from the function's module (`Self::X` on a method
533///   names the impl's type); a misspelt one is a compile error.
534/// - `#[miniextendr(dots = typed_list!(...))]` — validate dots, create `dots_typed`
535/// - `#[miniextendr(dots = empty | empty(allow = [..]) | forward(allow = [..]) | data)]` —
536///   what `...` takes; the R wrapper refuses the other arguments before
537///   evaluating any, with a "did you mean" suggestion
538/// - `#[miniextendr(internal)]` — adds `@keywords internal` to R wrapper
539/// - `#[miniextendr(noexport)]` — suppresses `@export` from R wrapper
540///
541/// ## Declared R formals (`formal`)
542///
543/// A parameter's R formal is its name without leading underscores. For an R
544/// name that is no Rust identifier (`row.names`, `na.rm`, `.data`), declare it
545/// with `formal`, on the parameter of a function or with `formal(p = "..")` on
546/// an impl method. It combines with the other per-parameter options:
547///
548/// ```ignore
549/// #[miniextendr(s3(generic = "as.data.frame", class = "fit"))]
550/// pub fn as_data_frame_fit(
551///     x: List,
552///     #[miniextendr(formal = "row.names", default = "NULL")] row_names: Option<String>,
553///     #[miniextendr(default = "FALSE")] optional: bool,
554///     _dots: ...
555/// ) -> BuiltDataFrame { /* ... */ }
556/// // as.data.frame.fit <- function(x, row.names = NULL, optional = FALSE, ...)
557///
558/// #[miniextendr(r6)]
559/// impl Tally {
560///     #[miniextendr(formal(na_rm = "na.rm"), defaults(na_rm = "FALSE"))]
561///     pub fn add(&mut self, by: f64, na_rm: bool) -> f64 { /* ... */ }
562/// }
563/// ```
564///
565/// Every R-facing name uses the formal: the usage, the `.Call()` arguments,
566/// the argument checks and their `e$param` (a failed conversion's too), the
567/// `match_arg` prelude and the generated `@param` lines; the method-level
568/// options keep the Rust name as their key. The formal must be a syntactic R
569/// name, not a reserved word, `...` or `..1`, not a name the generated wrapper
570/// uses itself (`.call`, `.val`, `.ptr`, the S3 dispatch variables, names
571/// starting `.mx_`, `.miniextendr_`, `.rdata_` or `.__MX_`, a method's
572/// receiver), and distinct from the other formals. The dots, an `NArgs`
573/// parameter, S7 property accessors and trait methods take no `formal`.
574///
575/// # Impl blocks (class systems)
576///
577/// Apply `#[miniextendr(env|r6|s7|s3|s4)]` to an `impl Type` block.
578/// A type's methods can be split over several impl blocks: they are merged into
579/// one class. One block has the constructor and the class doc comment, and
580/// every block repeats the class options.
581/// Registration is automatic.
582///
583/// ## R6 Active Bindings
584///
585/// For R6 classes, use `#[miniextendr(r6(active))]` on methods to create
586/// active bindings (computed properties accessed without parentheses):
587///
588/// ```ignore
589/// use miniextendr_api::miniextendr;
590///
591/// pub struct Rectangle {
592///     width: f64,
593///     height: f64,
594/// }
595///
596/// #[miniextendr(r6)]
597/// impl Rectangle {
598///     pub fn new(width: f64, height: f64) -> Self {
599///         Self { width, height }
600///     }
601///
602///     /// Returns the area (width * height).
603///     #[miniextendr(r6(active))]
604///     pub fn area(&self) -> f64 {
605///         self.width * self.height
606///     }
607///
608///     /// Regular method (requires parentheses).
609///     pub fn scale(&mut self, factor: f64) {
610///         self.width *= factor;
611///         self.height *= factor;
612///     }
613/// }
614/// ```
615///
616/// In R:
617/// ```r
618/// r <- Rectangle$new(3, 4)
619/// r$area        # 12 (active binding - no parentheses!)
620/// r$scale(2)    # Regular method call
621/// r$area        # 24
622/// ```
623///
624/// Active bindings must be getter-only methods taking only `&self`.
625///
626/// ## S7 Properties
627///
628/// For S7 classes, use `#[miniextendr(s7(getter))]` and `#[miniextendr(s7(setter))]`
629/// to create computed properties accessed via `@`:
630///
631/// ```ignore
632/// use miniextendr_api::{miniextendr, ExternalPtr};
633///
634/// #[derive(ExternalPtr)]
635/// pub struct Range {
636///     start: f64,
637///     end: f64,
638/// }
639///
640/// #[miniextendr(s7)]
641/// impl Range {
642///     pub fn new(start: f64, end: f64) -> Self {
643///         Self { start, end }
644///     }
645///
646///     /// Computed property (read-only): length of the range.
647///     #[miniextendr(s7(getter))]
648///     pub fn length(&self) -> f64 {
649///         self.end - self.start
650///     }
651///
652///     /// Dynamic property getter.
653///     #[miniextendr(s7(getter, prop = "midpoint"))]
654///     pub fn get_midpoint(&self) -> f64 {
655///         (self.start + self.end) / 2.0
656///     }
657///
658///     /// Dynamic property setter.
659///     #[miniextendr(s7(setter, prop = "midpoint"))]
660///     pub fn set_midpoint(&mut self, value: f64) {
661///         let half = self.length() / 2.0;
662///         self.start = value - half;
663///         self.end = value + half;
664///     }
665/// }
666/// ```
667///
668/// In R:
669/// ```r
670/// r <- Range(0, 10)
671/// r@length     # 10 (computed, read-only)
672/// r@midpoint   # 5 (dynamic property)
673/// r@midpoint <- 20  # Adjusts start/end to center at 20
674/// ```
675///
676/// ### Property Attributes
677///
678/// - `#[miniextendr(s7(getter))]` - Read-only computed property
679/// - `#[miniextendr(s7(getter, prop = "name"))]` - Named property getter
680/// - `#[miniextendr(s7(setter, prop = "name"))]` - Named property setter
681/// - `#[miniextendr(s7(getter, default = "0.0"))]` - Property with default value
682/// - `#[miniextendr(s7(getter, required))]` - Required property (error if not provided)
683/// - `#[miniextendr(s7(getter, frozen))]` - Property that can only be set once
684/// - `#[miniextendr(s7(getter, deprecated = "Use X instead"))]` - Deprecated property
685/// - `#[miniextendr(s7(validate))]` - Validator function for property
686///
687/// ## S7 Generic Dispatch Control
688///
689/// Control how S7 generics are created:
690///
691/// - `#[miniextendr(s7(no_dots))]` - Create strict generic without `...`
692/// - `#[miniextendr(s7(dispatch = "x, other"))]` - Multi-dispatch: the receiver
693///   (`x`), then the method's leading parameters (`other`), in order
694/// - `#[miniextendr(s7(fallback))]` - Register method for `class_any` (catch-all).
695///   The generated R wrapper uses `tryCatch(x@.ptr, error = function(e) x)` to
696///   safely extract the self argument, so non-miniextendr objects won't crash with
697///   a slot-access error. Instead, incompatible objects produce a Rust type-conversion
698///   error when the method tries to interpret the argument as `&Self`.
699///
700/// ```ignore
701/// #[miniextendr(s7)]
702/// impl MyClass {
703///     /// Strict generic: function(x) instead of function(x, ...)
704///     #[miniextendr(s7(no_dots))]
705///     pub fn strict_method(&self) -> i32 { 42 }
706///
707///     /// Fallback method dispatched on class_any.
708///     /// Calling this on a non-MyClass object produces a type-conversion error,
709///     /// not a slot-access crash.
710///     #[miniextendr(s7(fallback))]
711///     pub fn describe(&self) -> String { "generic description".into() }
712/// }
713/// ```
714///
715/// ## S7 Type Conversion (`convert`)
716///
717/// Use `convert_from` and `convert_to` to enable S7's `convert()` for type coercion:
718///
719/// ```ignore
720/// use miniextendr_api::{miniextendr, ExternalPtr};
721///
722/// #[derive(ExternalPtr)]
723/// pub struct Celsius { value: f64 }
724///
725/// #[derive(ExternalPtr)]
726/// pub struct Fahrenheit { value: f64 }
727///
728/// #[miniextendr(s7)]
729/// impl Fahrenheit {
730///     pub fn new(value: f64) -> Self { Self { value } }
731///
732///     /// Convert FROM Celsius TO Fahrenheit.
733///     /// Usage: S7::convert(celsius_obj, Fahrenheit)
734///     #[miniextendr(s7(convert_from = "Celsius"))]
735///     pub fn from_celsius(c: &Celsius) -> Self {
736///         Fahrenheit { value: c.value * 9.0 / 5.0 + 32.0 }
737///     }
738///
739///     /// Convert FROM Fahrenheit TO Celsius.
740///     /// Usage: S7::convert(fahrenheit_obj, Celsius)
741///     #[miniextendr(s7(convert_to = "Celsius"))]
742///     pub fn to_celsius(&self) -> Celsius {
743///         Celsius { value: (self.value - 32.0) * 5.0 / 9.0 }
744///     }
745/// }
746/// ```
747///
748/// In R:
749/// ```r
750/// c <- Celsius(100)
751/// f <- S7::convert(c, Fahrenheit)  # Uses convert_from
752/// c2 <- S7::convert(f, Celsius)    # Uses convert_to
753/// ```
754///
755/// **Note:** Classes must be defined before they can be referenced in convert methods.
756/// Define the "from" class before the "to" class to avoid forward reference issues.
757///
758/// # Traits (ABI)
759///
760/// Apply `#[miniextendr]` to a trait to generate ABI metadata, then use
761/// `#[miniextendr] impl Trait for Type`. Registration is automatic.
762///
763/// # ALTREP
764///
765/// `#[miniextendr]` no longer generates ALTREP classes — `class`/`base`
766/// attributes on a one-field struct are a compile error. Use the per-family
767/// derives (`#[derive(AltrepInteger)]`, …) with `#[altrep(class = "...")]`
768/// instead; registration is automatic there.
769#[proc_macro_attribute]
770pub fn miniextendr(
771    attr: proc_macro::TokenStream,
772    item: proc_macro::TokenStream,
773) -> proc_macro::TokenStream {
774    // rustc must select gated members before any expansion reads them (#2107).
775    if let Ok(parsed) = syn::parse::<syn::Item>(item.clone()) {
776        match cfg_gates::select(&attr.clone().into(), &parsed) {
777            Ok(Some(selected)) => return selected.into(),
778            Ok(None) => {}
779            Err(error) => return error.into_compile_error().into(),
780        }
781    }
782
783    // Try to parse as function first
784    if syn::parse::<syn::ItemFn>(item.clone()).is_ok() {
785        expand_fn(attr.into(), item.into())
786    } else if syn::parse::<syn::ItemImpl>(item.clone()).is_ok() {
787        // Delegate to impl block parser
788        miniextendr_impl::expand_impl(attr, item)
789    } else if syn::parse::<syn::ItemTrait>(item.clone()).is_ok() {
790        // Delegate to trait ABI generator
791        miniextendr_trait::expand_trait(attr, item)
792    } else {
793        // Delegate to struct/enum dispatch (handles ALTREP, ExternalPtr, list, dataframe, factor, match_arg)
794        struct_enum_dispatch::expand_struct_or_enum(attr, item)
795    }
796}
797
798/// `#[miniextendr]` on a function. It reads `proc_macro2` tokens and returns
799/// the token type its caller asks for: `proc_macro`'s from the attribute, or
800/// `proc_macro2`'s in the unit tests, which run outside a proc macro.
801fn expand_fn<T: From<proc_macro2::TokenStream>>(
802    attr: proc_macro2::TokenStream,
803    item: proc_macro2::TokenStream,
804) -> T {
805    let MiniextendrFnAttrs {
806        force_invisible,
807        check_interrupt,
808        coerce_all,
809        rng,
810        rng_seed,
811        unwrap_in_r,
812        serialize,
813        wrap,
814        serde_error,
815        preconditions,
816        call_attribution: call_attribution_attr,
817        call_arg,
818        return_pref,
819        return_pref_span,
820        s3_generic,
821        s3_class,
822        dots_spec,
823        dots_policy,
824        dots_span,
825        lifecycle,
826        strict,
827        internal,
828        noexport,
829        export,
830        doc,
831        c_symbol,
832        r_name: fn_r_name,
833        postfix: fn_postfix,
834        r_entry,
835        r_post_checks,
836        r_on_exit,
837    } = match syn::parse2(attr) {
838        Ok(attrs) => attrs,
839        Err(err) => return err.into_compile_error().into(),
840    };
841
842    let mut parsed = match syn::parse2::<MiniextendrFunctionParsed>(item) {
843        Ok(parsed) => parsed,
844        Err(err) => return err.into_compile_error().into(),
845    };
846
847    // Reject async functions
848    if let Some(asyncness) = &parsed.item().sig.asyncness {
849        return syn::Error::new_spanned(
850            asyncness,
851            "async functions are not supported by #[miniextendr]; \
852             R's C API is synchronous and incompatible with async executors",
853        )
854        .into_compile_error()
855        .into();
856    }
857
858    // Validate: reject type/const generic functions.
859    // Lifetime params ARE allowed — they are erased at codegen and produce a single monomorphic
860    // symbol, so `#[no_mangle] extern "C-unwind" fn f<'a>(...)` is valid.
861    // Type and const params require monomorphization → multiple symbols → cannot be #[no_mangle].
862    {
863        let params = &parsed.item().sig.generics.params;
864        let has_type_or_const = params
865            .iter()
866            .any(|p| #[allow(non_exhaustive_omitted_patterns)] match p {
    syn::GenericParam::Type(_) | syn::GenericParam::Const(_) => true,
    _ => false,
}matches!(p, syn::GenericParam::Type(_) | syn::GenericParam::Const(_)));
867
868        if has_type_or_const {
869            let err = syn::Error::new_spanned(
870                &parsed.item().sig.generics,
871                "#[miniextendr] functions cannot have generic type or const parameters. \
872                 Generic functions are incompatible with `extern \"C-unwind\"` and `#[no_mangle]` \
873                 required for R FFI. Consider using trait objects or monomorphization instead. \
874                 Explicit lifetime parameters are allowed (lifetimes are erased at codegen).",
875            );
876            return err.into_compile_error().into();
877        }
878    }
879
880    // NB: no automatic `#[track_caller]` (dropped in #1121). It made a *direct*
881    // panic's hook-location resolve to the generated wrapper glue instead of the
882    // user's `panic!` line, which defeats the `(at file:line)` suffix now folded
883    // into the R error message from the panic hook. See docs/TRACK_CALLER.md.
884    parsed.add_inline_never_if_needed();
885
886    // Extract commonly used values
887    let uses_internal_c_wrapper = parsed.uses_internal_c_wrapper();
888    let c_ident = if let Some(ref sym) = c_symbol {
889        syn::Ident::new(sym, parsed.c_wrapper_ident().span())
890    } else {
891        parsed.c_wrapper_ident()
892    };
893    let r_wrapper_generator = parsed.r_wrapper_const_ident();
894
895    // Extract references to parsed components
896    let rust_ident = parsed.ident();
897    let all_inputs = parsed.inputs();
898    // Return-visibility markers (`Invisible<T>` / `Visible<T>`, #1213) are
899    // peeled here so every later analysis sees the inner type; the marker's
900    // decision is folded in below, next to the attribute form.
901    let (visibility_marker, peeled_output) = {
902        let output = parsed.output();
903        if let syn::ReturnType::Type(_, ty) = output
904            && let Some(err) = crate::type_inspect::visibility_marker_error(ty, "return")
905        {
906            return err.into_compile_error().into();
907        }
908        crate::type_inspect::peel_return_visibility(output)
909    };
910    let (return_wrap, peeled_output) = match crate::return_wrap::resolve(&peeled_output, wrap) {
911        Ok(resolved) => resolved,
912        Err(error) => return error.into_compile_error().into(),
913    };
914    if return_wrap
915        .as_ref()
916        .is_some_and(|wrap| wrap.conversion.is_some())
917    {
918        return syn::Error::new_spanned(
919            parsed.output(),
920            "ConvertTo/ConvertFrom require an inherent S7 impl method",
921        )
922        .into_compile_error()
923        .into();
924    }
925    if return_wrap.is_some() && (serialize || unwrap_in_r) {
926        return syn::Error::new_spanned(
927            parsed.output(),
928            "explicit class wrapping cannot be combined with serialize or unwrap_in_r",
929        )
930        .into_compile_error()
931        .into();
932    }
933    if return_wrap.is_some() && parsed.abi().is_some() {
934        return syn::Error::new_spanned(parsed.output(), "explicit class wrapping requires a generated Rust-to-R wrapper, not an extern function").into_compile_error().into();
935    }
936    let converted_output = crate::type_inspect::serialize_return_type(&peeled_output, serialize);
937    let output = &converted_output;
938    let abi = parsed.abi();
939    if serialize && abi.is_some() {
940        return syn::Error::new_spanned(
941            parsed.output(),
942            "`serialize` requires a generated Rust-to-R conversion and cannot be used on an extern function",
943        )
944        .into_compile_error()
945        .into();
946    }
947    let attrs = parsed.attrs();
948    let vis = parsed.vis();
949    let generics = parsed.generics();
950    let has_dots = parsed.has_dots();
951    let dots_ident = parsed.dots_ident().cloned();
952    // The R formal of each parameter (#1842): what every R-facing name below
953    // is written as.
954    let formals = parsed.formals();
955
956    // Fail fast on invalid extern "C-unwind" signatures *before* any codegen,
957    // so we never emit a wrapper that would be discarded by the surfaced error.
958    if let Some(user_abi) = abi
959        && let Err(e) = validate_extern_signature(user_abi, attrs, all_inputs, output)
960    {
961        return e.into_compile_error().into();
962    }
963
964    // Condition-call markers (#1566): a `Call` / `CallerCall` parameter is the
965    // type-level spelling of `call = wrapper` / `call = caller`. It is not an
966    // R formal: the C wrapper binds it from the hidden `__miniextendr_call`
967    // slot, so every R-side consumer below sees `inputs` with the marker
968    // removed while the Rust call site substitutes the slot.
969    let mut call_marker: Option<(syn::Ident, r_wrapper_builder::CallAttribution)> = None;
970    for arg in all_inputs.iter() {
971        let syn::FnArg::Typed(pt) = arg else {
972            continue;
973        };
974        let Some(kind) = crate::type_inspect::call_marker(&pt.ty) else {
975            continue;
976        };
977        let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
978            continue;
979        };
980        let marker = kind
981            .marker_name()
982            .expect("a marker type selects an attribution that has a marker");
983        if let Some((first, _)) = &call_marker {
984            return syn::Error::new_spanned(
985                pt,
986                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a `#[miniextendr]` function takes at most one `Call` / `CallerCall` parameter (`{0}` already receives the condition call); the call slot is a single value",
                first))
    })format!(
987                    "a `#[miniextendr]` function takes at most one `Call` / `CallerCall` \
988                     parameter (`{first}` already receives the condition call); the call \
989                     slot is a single value"
990                ),
991            )
992            .into_compile_error()
993            .into();
994        }
995        if parsed.has_param_attrs(&crate::naming::ident_name(&pat_ident.ident)) {
996            return syn::Error::new_spanned(
997                pt,
998                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("per-parameter options (`coerce`, `match_arg`, `choices`, `default`, `several_ok`, `formal`) do not apply to a `{0}` parameter: it is bound from the call slot, not from an R argument",
                marker))
    })format!(
999                    "per-parameter options (`coerce`, `match_arg`, `choices`, `default`, \
1000                     `several_ok`, `formal`) do not apply to a `{marker}` parameter: it is \
1001                     bound from the call slot, not from an R argument"
1002                ),
1003            )
1004            .into_compile_error()
1005            .into();
1006        }
1007        if kind == r_wrapper_builder::CallAttribution::Caller && !(noexport || internal) {
1008            return syn::Error::new_spanned(
1009                pt,
1010                "a `CallerCall` parameter attributes conditions to the wrapper's caller, which \
1011                 is only meaningful for a package-internal entry point; add `noexport` or \
1012                 `internal`.",
1013            )
1014            .into_compile_error()
1015            .into();
1016        }
1017        if kind == r_wrapper_builder::CallAttribution::Caller && call_arg {
1018            return syn::Error::new_spanned(
1019                pt,
1020                "a `CallerCall` parameter cannot be combined with `call_arg`: a `caller` wrapper \
1021                 already takes `.call`, where NULL means the caller's call. Keep the \
1022                 `CallerCall` parameter, or make it `Call` so that NULL means this function's \
1023                 own call.",
1024            )
1025            .into_compile_error()
1026            .into();
1027        }
1028        if call_attribution_attr == Some(r_wrapper_builder::CallAttribution::NoCall) {
1029            return syn::Error::new_spanned(
1030                pt,
1031                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`call = none` passes no call, so a `{0}` parameter has nothing to receive; drop the parameter or the option",
                marker))
    })format!(
1032                    "`call = none` passes no call, so a `{marker}` parameter has nothing to \
1033                     receive; drop the parameter or the option"
1034                ),
1035            )
1036            .into_compile_error()
1037            .into();
1038        }
1039        if let Some(attr) = call_attribution_attr
1040            && attr != kind
1041        {
1042            return syn::Error::new_spanned(
1043                pt,
1044                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the `{3}` parameter selects `{0}` attribution but the attribute selects `{1}` (`call = {2}`); keep one of them (or make them agree)",
                kind.name(), attr.name(), attr.name(), marker))
    })format!(
1045                    "the `{marker}` parameter selects `{}` attribution but the attribute \
1046                     selects `{}` (`call = {}`); keep one of them (or make them agree)",
1047                    kind.name(),
1048                    attr.name(),
1049                    attr.name(),
1050                ),
1051            )
1052            .into_compile_error()
1053            .into();
1054        }
1055        call_marker = Some((pat_ident.ident.clone(), kind));
1056    }
1057    // Unevaluated-argument markers (#1835): a `Quoted` / `Quosure` parameter
1058    // stays an R formal, which the wrapper passes unevaluated
1059    // (`RArgumentBuilder::build_call_args_vec`). Every per-parameter option
1060    // would force it (a check, a coercion, a default evaluated in the wrapper's
1061    // frame), and a marker in any other position than the whole type or
1062    // `Missing<..>` would be converted as a forced value: all compile errors.
1063    // One exception: `default` alone on `Missing<..>` only writes the formal
1064    // (`x = NULL` in the usage). An omitted argument is still `missing()`, so
1065    // the wrapper passes the missing-argument sentinel and never evaluates the
1066    // default.
1067    let mut unevaluated_r_names: Vec<String> = Vec::new();
1068    for arg in all_inputs.iter() {
1069        let syn::FnArg::Typed(pt) = arg else {
1070            continue;
1071        };
1072        let Some(param) = crate::type_inspect::unevaluated_param(&pt.ty) else {
1073            if crate::type_inspect::mentions_unevaluated_marker(&pt.ty) {
1074                return syn::Error::new_spanned(
1075                    &pt.ty,
1076                    "`Quoted` / `Quosure` must be the parameter's whole type, or the type \
1077                     argument of `Missing<..>`: the wrapper passes the argument unevaluated \
1078                     only for those shapes",
1079                )
1080                .into_compile_error()
1081                .into();
1082            }
1083            continue;
1084        };
1085        let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
1086            continue;
1087        };
1088        let marker = param.kind.name();
1089        let rust_name = crate::naming::ident_name(&pat_ident.ident);
1090        // `formal` only names the argument (#1842), so it applies.
1091        if parsed
1092            .param_attrs(&rust_name)
1093            .is_some_and(|attrs| !attrs.leaves_argument_unforced(param.optional))
1094        {
1095            let hint = if param.optional {
1096                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`Missing<{0}>` takes `default` alone, which only writes the formal and is never evaluated",
                marker))
    })format!(
1097                    "`Missing<{marker}>` takes `default` alone, which only writes the \
1098                     formal and is never evaluated"
1099                )
1100            } else {
1101                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Use `Missing<{0}>` for an optional argument",
                marker))
    })format!("Use `Missing<{marker}>` for an optional argument")
1102            };
1103            return syn::Error::new_spanned(
1104                pt,
1105                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("per-parameter options (`coerce`, `match_arg`, `choices`, `several_ok`, `default`, `no_na`, `inherits`, `not_inherits`, `preconditions`) do not apply to a `{0}` parameter: the wrapper passes the argument unevaluated, and each of them would force it (`formal`, which only names it, does apply). {1}",
                marker, hint))
    })format!(
1106                    "per-parameter options (`coerce`, `match_arg`, `choices`, `several_ok`, \
1107                     `default`, `no_na`, `inherits`, `not_inherits`, `preconditions`) do not \
1108                     apply to a `{marker}` parameter: the wrapper passes the argument \
1109                     unevaluated, and each of them would force it (`formal`, which only \
1110                     names it, does apply). {hint}"
1111                ),
1112            )
1113            .into_compile_error()
1114            .into();
1115        }
1116        // `Checked<Quoted>` / `Unchecked<..>` is refused at parse time
1117        // (`MiniextendrFunctionParsed::parse`): no R-side type check to select.
1118        unevaluated_r_names.push(formals.of(&rust_name));
1119    }
1120    // The argument-count marker (#1860): an `NArgs` parameter is no R formal;
1121    // the wrapper passes `nargs()` at its position and the C wrapper converts
1122    // it like any argument, so it stays in `inputs`. `RArgumentBuilder`,
1123    // `r_formal_names`, the preconditions, the `@param` fillers and the
1124    // replacement-generic check each skip it.
1125    if let Err(err) =
1126        miniextendr_fn::check_nargs_params(all_inputs, |name| parsed.has_param_attrs(name))
1127    {
1128        return err.into_compile_error().into();
1129    }
1130    // The unforced dots (#1892): a `LazyDots` parameter is R's `...`, which
1131    // the wrapper passes as its frame; it takes no per-parameter option, and
1132    // any other shape (`&LazyDots`, `Option<..>`) is refused.
1133    if let Err(err) =
1134        miniextendr_fn::check_lazy_dots_params(all_inputs, |name| parsed.has_param_attrs(name))
1135    {
1136        return err.into_compile_error().into();
1137    }
1138    // The RNG guard (#2002): a `&RngGuard` parameter needs `rng`, whose
1139    // wrapper passes the guard it holds; it is no R formal either.
1140    if let Err(err) =
1141        miniextendr_fn::check_rng_guard_params(all_inputs, rng, |name| parsed.has_param_attrs(name))
1142    {
1143        return err.into_compile_error().into();
1144    }
1145    let r_inputs: syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]> = all_inputs
1146        .iter()
1147        .filter(|arg| match arg {
1148            syn::FnArg::Typed(pt) => {
1149                crate::type_inspect::call_marker(&pt.ty).is_none()
1150                    && !crate::type_inspect::is_rng_guard_param(&pt.ty)
1151            }
1152            syn::FnArg::Receiver(_) => true,
1153        })
1154        .cloned()
1155        .collect();
1156    let inputs = &r_inputs;
1157
1158    // A method for a replacement generic (`s3(generic = "$<-", ...)`) takes
1159    // the new value last, as `value` (#1853). Checked on the R formals, so a
1160    // trailing condition-call marker doesn't hide the parameter before it.
1161    if let Some(generic) = &s3_generic
1162        && let Err(err) = miniextendr_fn::check_replacement_value_param(
1163            crate::naming::split_generic(generic).1,
1164            inputs,
1165            &formals,
1166            rust_ident.span(),
1167        )
1168    {
1169        return err.into_compile_error().into();
1170    }
1171
1172    // Check for @title/@description conflicts with implicit values (doc-lint feature)
1173    // Skip when `doc` attribute overrides the roxygen — implicit docs are irrelevant then.
1174    let doc_lint_warnings = if doc.is_some() {
1175        proc_macro2::TokenStream::new()
1176    } else {
1177        crate::roxygen::doc_conflict_warnings(attrs, rust_ident.span())
1178    };
1179
1180    // Calling the Rust function: each R-backed parameter by name, a `Call` /
1181    // `CallerCall` marker from the C wrapper's `__miniextendr_call` slot (the
1182    // R wrapper's `.call = ...` argument, so a `CallerCall` sees `.mx_call`),
1183    // the RNG guard from the `rng` wrapper.
1184    let rust_inputs: Vec<proc_macro2::TokenStream> = all_inputs
1185        .iter()
1186        .filter_map(|arg| {
1187            if let syn::FnArg::Typed(pt) = arg
1188                && let syn::Pat::Ident(p) = pt.pat.as_ref()
1189            {
1190                let ident = &p.ident;
1191                if crate::type_inspect::is_rng_guard_param(&pt.ty) {
1192                    return Some(crate::type_inspect::rng_guard_arg());
1193                }
1194                return Some(match crate::type_inspect::call_marker(&pt.ty) {
1195                    Some(r_wrapper_builder::CallAttribution::Caller) => {
    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, "CallerCall");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "from_sexp");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "__miniextendr_call");
            _s
        });
    _s
}quote::quote! {
1196                        ::miniextendr_api::CallerCall::from_sexp(__miniextendr_call)
1197                    },
1198                    Some(_) => {
    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, "Call");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "from_sexp");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "__miniextendr_call");
            _s
        });
    _s
}quote::quote! {
1199                        ::miniextendr_api::Call::from_sexp(__miniextendr_call)
1200                    },
1201                    None => {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&ident, &mut _s);
    _s
}quote::quote! { #ident },
1202                });
1203            }
1204            None
1205        })
1206        .collect();
1207
1208    // Validate dots_spec usage (actual injection happens later in the function body)
1209    if dots_spec.is_some() && !has_dots {
1210        let err = syn::Error::new(
1211            dots_span.unwrap_or_else(proc_macro2::Span::call_site),
1212            "#[miniextendr(dots = typed_list!(...))] requires a `...` or `&Dots` parameter in the function signature",
1213        );
1214        return err.into_compile_error().into();
1215    }
1216    if dots_spec.is_some()
1217        && let Some(err) = miniextendr_fn::typed_list_on_lazy_dots(all_inputs, dots_span)
1218    {
1219        return err.into_compile_error().into();
1220    }
1221    // `dots = empty | forward(..) | data` (#2157): a standalone wrapper's
1222    // `...` is the function's own dots parameter.
1223    if let Some(policy) = &dots_policy
1224        && let Err(err) = policy.check_signature(has_dots, has_dots)
1225    {
1226        return err.into_compile_error().into();
1227    }
1228
1229    // `serde_error` only has an `Err` arm to act on when the fn returns `Result`.
1230    if serde_error.is_some() && !return_type_analysis::output_is_result(output) {
1231        return syn::Error::new_spanned(
1232            output,
1233            "`#[miniextendr(serde_error(..))]` requires a `Result<T, E>` return type: it classes \
1234             the condition raised from the `Err` arm",
1235        )
1236        .into_compile_error()
1237        .into();
1238    }
1239    let err_parts = c_wrapper_builder::ErrPartsMode::from_spec(serde_error.as_ref());
1240
1241    // Crate-level defaults (#1454, #1566): `[package.metadata.miniextendr]` in
1242    // the crate's Cargo.toml. Read once per expansion; a malformed table is
1243    // reported here, on the first `#[miniextendr]` function, for every key it
1244    // may carry.
1245    let crate_config = match crate::crate_config::crate_config() {
1246        Ok(config) => config,
1247        Err(err) => {
1248            return syn::Error::new(proc_macro2::Span::call_site(), err.to_string())
1249                .into_compile_error()
1250                .into();
1251        }
1252    };
1253
1254    // Resolve the R name once for both wrapper definitions and Rust-side errors.
1255    let is_s3_method = s3_generic.is_some() || s3_class.is_some();
1256    // Crate-level default for internal entry points (#1454):
1257    // `[package.metadata.miniextendr] noexport_postfix = "..."` applies to
1258    // every `noexport` / `internal` free function that names itself neither
1259    // via `r_name` nor via its own `postfix`. Exported functions and S3
1260    // methods keep their names. Precedence:
1261    // `r_name` > `postfix` > crate default > Rust name.
1262    let effective_postfix = match &fn_postfix {
1263        Some(postfix) => Some(postfix.clone()),
1264        None if (noexport || internal) && fn_r_name.is_none() && !is_s3_method => {
1265            crate_config.noexport_postfix.clone()
1266        }
1267        None => None,
1268    };
1269    let r_wrapper_ident_str: String;
1270    let s3_method_comment: String;
1271    // The registration tag of a method on a package-qualified generic (#2154).
1272    let mut s3_qualified_registration: Option<String> = None;
1273
1274    if is_s3_method {
1275        // For S3 methods, function name is generic.class
1276        // generic defaults to Rust function name if not specified
1277        let generic = s3_generic
1278            .clone()
1279            .unwrap_or_else(|| crate::naming::ident_name(rust_ident));
1280        let (package, generic) = crate::naming::split_generic(&generic);
1281        // s3_class is guaranteed to be Some here because MiniextendrFnAttrs::parse
1282        // validates that s3(...) always has class specified
1283        let class = s3_class.as_ref().expect("s3_class validated at parse time");
1284        r_wrapper_ident_str = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.{1}", generic, class))
    })format!("{}.{}", generic, class);
1285        // Add @importFrom for vctrs generics so roxygen registers the dependency.
1286        // A qualified `vctrs::` generic registers lazily instead, so vctrs may
1287        // stay in Suggests.
1288        let import_comment =
1289            if package.is_none() && crate::vctrs_generics::is_vctrs_generic(generic) {
1290                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @importFrom vctrs {0}\n",
                generic))
    })format!("#' @importFrom vctrs {}\n", generic)
1291            } else {
1292                String::new()
1293            };
1294        s3_method_comment = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}#\' @method {1} {2}\n",
                import_comment, generic, class))
    })format!("{}#' @method {} {}\n", import_comment, generic, class);
1295        s3_qualified_registration =
1296            package.map(|package| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @exportS3Method {0}::{1} {2}\n",
                package, generic, class))
    })format!("#' @exportS3Method {package}::{generic} {class}\n"));
1297    } else if let Some(ref custom_name) = fn_r_name {
1298        r_wrapper_ident_str = custom_name.clone();
1299        s3_method_comment = String::new();
1300    } else if let Some(ref postfix) = effective_postfix {
1301        // `postfix = "_impl"` (or the crate default): the R wrapper is
1302        // `<rust_name><postfix>`; the C symbol keeps the Rust name.
1303        r_wrapper_ident_str = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}",
                crate::naming::ident_name(rust_ident), postfix))
    })format!("{}{postfix}", crate::naming::ident_name(rust_ident));
1304        s3_method_comment = String::new();
1305    } else if abi.is_some() {
1306        r_wrapper_ident_str = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unsafe_{0}",
                crate::naming::ident_name(rust_ident)))
    })format!("unsafe_{}", crate::naming::ident_name(rust_ident));
1307        s3_method_comment = String::new();
1308    } else {
1309        r_wrapper_ident_str = crate::naming::ident_name(rust_ident);
1310        s3_method_comment = String::new();
1311    };
1312
1313    // Marker (`Invisible<T>` / `Visible<T>`) > attribute (`invisible` /
1314    // `visible`) > shape default (unit-`NULL` returns are invisible).
1315    let is_invisible_return_type = match crate::type_inspect::resolve_visibility(
1316        visibility_marker,
1317        force_invisible,
1318        return_type_analysis::returns_invisibly(output, unwrap_in_r),
1319        syn::spanned::Spanned::span(parsed.output()),
1320    ) {
1321        Ok(v) => v,
1322        Err(err) => return err.into_compile_error().into(),
1323    };
1324
1325    // Extract cfg attributes to apply to generated items (needed by CWrapperContext)
1326    let cfg_attrs = extract_cfg_attrs(parsed.attrs());
1327
1328    let source_loc_doc = source_location_doc(rust_ident.span());
1329
1330    // Build individual per-parameter coerce, match_arg_several_ok, layered
1331    // choice (a choice type wrapped in `Missing` / `Option`, #1473 / #1551) and
1332    // `no_na` lists (the value is checked after the conversion too)
1333    let mut coerce_params_list: Vec<String> = Vec::new();
1334    let mut match_arg_several_ok_params_list: Vec<String> = Vec::new();
1335    let mut layered_choice_params_list: Vec<(String, rust_conversion_builder::ChoiceLeaf)> =
1336        Vec::new();
1337    let mut no_na_params_list: Vec<(String, Option<String>)> = Vec::new();
1338    for input in inputs.iter() {
1339        if let syn::FnArg::Typed(pt) = input
1340            && let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
1341        {
1342            let param_name = crate::naming::ident_name(&pat_ident.ident);
1343            if parsed.has_coerce_attr(&param_name) {
1344                // A per-parameter `coerce` names this parameter, so a type it
1345                // cannot widen is an error rather than a silent no-op (#2274);
1346                // the function-wide and feature-default forms skip such types.
1347                // Checked here, after the marker parameters' own refusals.
1348                if miniextendr_fn::CoercionMapping::from_type(&pt.ty).is_none() {
1349                    return miniextendr_fn::unmapped_coerce_error(pt, &param_name)
1350                        .into_compile_error()
1351                        .into();
1352                }
1353                coerce_params_list.push(param_name.clone());
1354            }
1355            if let Some(attrs) = parsed.param_attrs(&param_name)
1356                && attrs.checks.no_na
1357            {
1358                no_na_params_list.push((param_name.clone(), attrs.checks.no_na_message.clone()));
1359            }
1360            if let Some(leaf) = parsed
1361                .param_attrs(&param_name)
1362                .and_then(miniextendr_fn::ParamAttrs::layered_leaf)
1363            {
1364                layered_choice_params_list.push((param_name, leaf));
1365            } else if parsed.has_match_arg_attr(&param_name) && parsed.has_several_ok(&param_name) {
1366                match_arg_several_ok_params_list.push(param_name);
1367            }
1368        }
1369    }
1370
1371    // Build the call expression: rust_ident(rust_input_1, rust_input_2, ...).
1372    // A visibility marker is a transparent newtype: unwrap it so the return
1373    // conversion works on the inner value (the analysis above saw the inner type).
1374    let fn_call_expr = crate::type_inspect::prepare_return_value(
1375        {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&rust_ident, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            {
                use ::quote::__private::ext::*;
                let mut _first = true;
                let has_iter = ::quote::__private::HasIterator::<false>;
                #[allow(unused_mut)]
                let (mut rust_inputs, i) = rust_inputs.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let rust_inputs =
                        match rust_inputs.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&rust_inputs, &mut _s);
                }
            }
            _s
        });
    _s
}quote::quote! { #rust_ident(#(#rust_inputs),*) },
1376        visibility_marker,
1377        serialize,
1378    );
1379    let fn_call_expr = match &return_wrap {
1380        Some(wrap) => wrap.prepare_value(fn_call_expr),
1381        None => fn_call_expr,
1382    };
1383
1384    // Determine return handling: the rule methods share (`detect_return_handling`),
1385    // and unwrap_in_r (Result<T, E> → IntoR to pass result list to R).
1386    let return_pref_is_set = !#[allow(non_exhaustive_omitted_patterns)] match return_pref {
    crate::miniextendr_fn::ReturnPref::Auto => true,
    _ => false,
}matches!(return_pref, crate::miniextendr_fn::ReturnPref::Auto);
1387    let fn_return_handling = if unwrap_in_r && crate::return_type_analysis::output_is_result(output)
1388    {
1389        // In unwrap_in_r mode the IntoR here operates on the whole Result<T,E> (the
1390        // framework's IntoR for Result encodes it as a tagged list for R to decode), NOT on
1391        // the inner T. prefer= always targets that inner T, so there is nothing for it to
1392        // wrap here — reject rather than silently drop it (see apply_return_pref docstring
1393        // and the BUG4 audit finding).
1394        if return_pref_is_set {
1395            let span = return_pref_span.unwrap_or_else(proc_macro2::Span::call_site);
1396            return syn::Error::new(
1397                span,
1398                "`prefer = ...` cannot be combined with `unwrap_in_r` on a function returning \
1399                 `Result<T, E>`: `unwrap_in_r` converts the whole `Result<T, E>` via a single \
1400                 `IntoR` impl (a tagged list for R to decode), not the inner `T` alone, so \
1401                 there is no plain `T` for `prefer=` to wrap. Remove `prefer=`.",
1402            )
1403            .into_compile_error()
1404            .into();
1405        }
1406        c_wrapper_builder::ReturnHandling::IntoR
1407    } else {
1408        let auto = c_wrapper_builder::detect_return_handling(output, return_wrap.as_ref());
1409        // Apply return_pref override: wraps the result in AsList/AsExternalPtr/AsRNative.
1410        // Only applies to the plain IntoR variant — Option*/Result*/Unit/RawSexp/ExternalPtr
1411        // variants have no bare T to wrap and now hard-error instead of silently ignoring
1412        // prefer= (see apply_return_pref docstring).
1413        match apply_return_pref(auto, return_pref, return_pref_span) {
1414            Ok(handling) => handling,
1415            Err(err) => return err.into_compile_error().into(),
1416        }
1417    };
1418
1419    // `rng(seed = <param>)` (#2198): the R formal the seed contract reads,
1420    // once the parameter and the return are known to suit it.
1421    let rng_seed_formal = match &rng_seed {
1422        Some(seed) => {
1423            use c_wrapper_builder::ReturnHandling;
1424            let unit_return = #[allow(non_exhaustive_omitted_patterns)] match fn_return_handling {
    ReturnHandling::Unit | ReturnHandling::ResultUnit |
        ReturnHandling::OptionUnit => true,
    _ => false,
}matches!(
1425                fn_return_handling,
1426                ReturnHandling::Unit | ReturnHandling::ResultUnit | ReturnHandling::OptionUnit
1427            );
1428            match miniextendr_fn::check_rng_seed(
1429                seed,
1430                all_inputs,
1431                inputs,
1432                &formals,
1433                &unevaluated_r_names,
1434                unit_return,
1435            ) {
1436                Ok(formal) => Some(formal),
1437                Err(err) => return err.into_compile_error().into(),
1438            }
1439        }
1440        None => None,
1441    };
1442
1443    // Build CWrapperContext for the standalone fn
1444    let mut c_wrapper_builder =
1445        c_wrapper_builder::CWrapperContext::builder(rust_ident.clone(), c_ident.clone())
1446            .r_name(r_wrapper_ident_str.clone())
1447            .r_wrapper_const(r_wrapper_generator.clone())
1448            .inputs(inputs.iter().cloned().collect())
1449            .output(output.clone())
1450            .call_expr(fn_call_expr)
1451            .return_handling(fn_return_handling)
1452            .err_parts(err_parts)
1453            .cfg_attrs(cfg_attrs.clone())
1454            .vis(vis.clone())
1455            .generics(generics.clone())
1456            .formals(formals.clone())
1457            .preserve_param_names();
1458
1459    if uses_internal_c_wrapper {
1460        // Normal Rust fn: generate full C wrapper
1461    } else {
1462        // extern "C-unwind" fn: user wrote the C symbol; only emit R_CallMethodDef
1463        c_wrapper_builder = c_wrapper_builder.skip_wrapper();
1464    }
1465
1466    if coerce_all {
1467        c_wrapper_builder = c_wrapper_builder.coerce_all();
1468    }
1469    for param in &coerce_params_list {
1470        c_wrapper_builder = c_wrapper_builder.with_coerce_param(param.clone());
1471    }
1472    for param in match_arg_several_ok_params_list {
1473        c_wrapper_builder = c_wrapper_builder.match_arg_several_ok(param);
1474    }
1475    for (param, leaf) in layered_choice_params_list {
1476        c_wrapper_builder = c_wrapper_builder.layered_choice(param, leaf);
1477    }
1478    for (param, message) in no_na_params_list {
1479        c_wrapper_builder = c_wrapper_builder.no_na(param, message);
1480    }
1481    for input in inputs.iter() {
1482        if let syn::FnArg::Typed(pt) = input
1483            && let syn::Pat::Ident(p) = pt.pat.as_ref()
1484        {
1485            let name = crate::naming::ident_name(&p.ident);
1486            if parsed.param_attrs(&name).is_some_and(|a| a.convert) {
1487                c_wrapper_builder = c_wrapper_builder.with_convert_param(name);
1488            }
1489        }
1490    }
1491    for (param, markers) in parsed.param_markers() {
1492        c_wrapper_builder = c_wrapper_builder.param_markers(param.clone(), markers.clone());
1493    }
1494    if check_interrupt {
1495        c_wrapper_builder = c_wrapper_builder.check_interrupt();
1496    }
1497    if rng {
1498        c_wrapper_builder = c_wrapper_builder.rng();
1499    }
1500    if strict {
1501        c_wrapper_builder = c_wrapper_builder.strict();
1502    }
1503
1504    let c_wrapper = c_wrapper_builder.build().generate();
1505
1506    // region: R wrappers generation in `fn`
1507    // Build R formal parameters and call arguments using shared builder
1508    let mut arg_builder = RArgumentBuilder::new(inputs).with_formals(formals.clone());
1509    // Add user-specified parameter defaults, keyed by R formal like the
1510    // builder's. A `Missing<T>` default only writes the formal (#2161): the
1511    // call argument tests `missing()` first.
1512    let mut merged_defaults = formals.rekey(parsed.param_defaults());
1513    // For match_arg params, always use the choices placeholder as the formal
1514    // default — the write-time pass replaces it with `c("a", "b", ...)`.
1515    // If the user supplied `default = "\"X\""`, capture X as `preferred_default`
1516    // so the write-time pass rotates X to position 1; the user's literal does
1517    // NOT become the formal (otherwise R's `match.arg` would only see one
1518    // choice).
1519    //
1520    // Tuple: (placeholder, aliases_placeholder, rust_param,
1521    // preferred_default_unquoted_or_empty)
1522    let mut match_arg_placeholders: Vec<(String, String, String, String)> = Vec::new();
1523    for match_arg_param in parsed.match_arg_params() {
1524        let r_name = formals.of(match_arg_param);
1525        let preferred = match merged_defaults.get(&r_name) {
1526            Some(raw) => crate::match_arg_keys::extract_match_arg_default(raw),
1527            None => String::new(),
1528        };
1529        // The placeholders are keyed by the Rust name, never the formal
1530        // (`match_arg_keys::param_key`).
1531        let key = crate::match_arg_keys::param_key(match_arg_param);
1532        let placeholder = crate::match_arg_keys::choices_placeholder(&c_ident.to_string(), &key);
1533        // `Option<T>` (#1473): the formal is `NULL` (no choice); `no_default`
1534        // (#1828, which `default` cannot join): no formal default. The prelude
1535        // spells the choices out through the same placeholder either way, so
1536        // its entry is emitted below in every case.
1537        let formal = match parsed.param_attrs(match_arg_param) {
1538            Some(attrs) => attrs.choice_formal(&placeholder),
1539            None => Some(placeholder.clone()),
1540        };
1541        if let Some(formal) = formal {
1542            merged_defaults.insert(r_name.clone(), formal);
1543        }
1544        let aliases_placeholder =
1545            crate::match_arg_keys::aliases_placeholder(&c_ident.to_string(), &key);
1546        match_arg_placeholders.push((
1547            placeholder,
1548            aliases_placeholder,
1549            match_arg_param.clone(),
1550            preferred,
1551        ));
1552    }
1553    // Add c("a", "b", "c") default for choices params (idiomatic R match.arg
1554    // pattern); an `Option<T>` choices param defaults to `NULL` instead
1555    // (#1473), and a `no_default` one gets none (#1828).
1556    for (param_name, choices) in parsed.choices_params() {
1557        let r_name = formals.of(param_name);
1558        let quoted: Vec<String> = choices.iter().map(|c| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"", c))
    })format!("\"{}\"", c)).collect();
1559        let choices_expr = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("c({0})", quoted.join(", ")))
    })format!("c({})", quoted.join(", "));
1560        let formal = match parsed.param_attrs(param_name) {
1561            Some(attrs) => attrs.choice_formal(&choices_expr),
1562            None => Some(choices_expr),
1563        };
1564        if let Some(formal) = formal {
1565            merged_defaults.entry(r_name).or_insert(formal);
1566        }
1567    }
1568    arg_builder = arg_builder
1569        .with_defaults(merged_defaults)
1570        .with_absent_formals(parsed.absent_formals());
1571
1572    let r_formals = arg_builder.build_formals();
1573    let mut r_call_args_strs = arg_builder.build_call_args_vec();
1574
1575    // Prepend the `.call` parameter if using the internal C wrapper. Marker
1576    // (`Call` / `CallerCall`) > attribute (`call = wrapper | caller | none`)
1577    // > crate default (`call_attribution = "..."`, where `caller` applies to
1578    // `noexport` / `internal` entry points only) > `wrapper` (#1566). Every
1579    // form passes the call as written: `sys.call()` for `wrapper`, the
1580    // caller's `sys.call()` for `caller`; `none` passes `FALSE`, the "no
1581    // call" marker, so every condition has a NULL call (#1851). `caller`
1582    // also gives the wrapper a trailing `.call = NULL` formal (#1613, S3
1583    // methods excluded; see `call_formal` below), as does `call_arg`.
1584    // Attribution is independent of the preconditions.
1585    //
1586    // `call_arg` (#1834) turns `wrapper` into `Argument`: the same trailing
1587    // formal, whose `NULL` is the wrapper's own call. It is an explicit
1588    // choice, so the crate default doesn't apply with it (the parser and the
1589    // marker loop above refuse it with `caller` and `none`).
1590    //
1591    // An S3 method's `wrapper` attribution is `Generic` (#1851): the slot
1592    // takes the method's frame, `environment()`, and the raise helper turns
1593    // it into the generic's call (`summary(x)` for `summary.cls(x)`, the
1594    // assignment for a replacement method) only when a condition is raised.
1595    // With a `Call` parameter the frame is resolved up front instead
1596    // (`GenericEager`), since the body receives the slot.
1597    let call_attribution = r_wrapper_builder::CallAttribution::resolve(
1598        call_marker.as_ref().map(|(_, kind)| *kind),
1599        call_attribution_attr,
1600        crate_config.call_attribution.filter(|_| !call_arg),
1601        noexport || internal,
1602    )
1603    .with_call_arg(call_arg);
1604    let call_attribution = if is_s3_method {
1605        call_attribution.for_s3_method(call_marker.is_some())
1606    } else {
1607        call_attribution
1608    };
1609    if uses_internal_c_wrapper {
1610        r_call_args_strs.insert(0, call_attribution.dot_call_arg().to_string());
1611    } else if #[allow(non_exhaustive_omitted_patterns)] match call_attribution_attr {
    Some(r_wrapper_builder::CallAttribution::Caller |
        r_wrapper_builder::CallAttribution::NoCall) => true,
    _ => false,
}matches!(
1612        call_attribution_attr,
1613        Some(
1614            r_wrapper_builder::CallAttribution::Caller | r_wrapper_builder::CallAttribution::NoCall
1615        )
1616    ) || call_arg
1617    {
1618        // `extern "C-unwind"` fns have no generated call slot to redirect (a
1619        // `CallerCall` parameter already fails the extern signature check).
1620        let option = if call_arg {
1621            "`call_arg`"
1622        } else if call_attribution_attr == Some(r_wrapper_builder::CallAttribution::NoCall) {
1623            "`call = none`"
1624        } else {
1625            "`call = caller`"
1626        };
1627        return syn::Error::new_spanned(
1628            &parsed.item().sig.ident,
1629            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} needs the generated call slot; an `extern \"C-unwind\"` function has no `.call` argument to attribute",
                option))
    })format!(
1630                "{option} needs the generated call slot; an `extern \"C-unwind\"` function \
1631                 has no `.call` argument to attribute"
1632            ),
1633        )
1634        .into_compile_error()
1635        .into();
1636    }
1637
1638    // Build the R body string consistently
1639    let c_ident_str = c_ident.to_string();
1640    let call_args_joined = r_call_args_strs.join(", ");
1641    let call_expr = if r_call_args_strs.is_empty() {
1642        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".Call({0})", c_ident_str))
    })format!(".Call({})", c_ident_str)
1643    } else {
1644        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".Call({0}, {1})", c_ident_str,
                call_args_joined))
    })format!(".Call({}, {})", c_ident_str, call_args_joined)
1645    };
1646    let r_wrapper_return_str = {
1647        // Capture result, check for tagged condition value, raise R condition if present.
1648        let final_return = return_wrap
1649            .as_ref()
1650            .map_or_else(|| ".val".to_owned(), |wrap| wrap.r_expression(".val", None));
1651        let final_return = if is_invisible_return_type {
1652            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("invisible({0})", final_return))
    })format!("invisible({final_return})")
1653        } else {
1654            final_return
1655        };
1656        // `rng(seed = ..)` (#2198): the result records the seed, after its
1657        // condition check and before any wrap.
1658        let final_return = if rng_seed_formal.is_some() {
1659            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\n  {1}",
                r_wrapper_builder::RngSeedContract::ATTRIBUTE, final_return))
    })format!(
1660                "{}\n  {final_return}",
1661                r_wrapper_builder::RngSeedContract::ATTRIBUTE
1662            )
1663        } else {
1664            final_return
1665        };
1666        // `call = caller` binds `.mx_call` at the head of the prelude (see
1667        // `combined_prelude` below), ahead of every R-side check.
1668        crate::method_return_builder::standalone_body_with_call_default(
1669            &call_expr,
1670            &final_return,
1671            "  ",
1672            call_attribution.raise_default(),
1673        )
1674    };
1675    // The trailing `.call = NULL` formal of a `caller` wrapper (#1613) or a
1676    // `call_arg` one (#1834): a hand-written helper between the public
1677    // function and the entry point, or an R function composing the function,
1678    // passes a frame there. S3 methods keep the zero-argument prelude: a
1679    // formal the generic lacks breaks generic/method consistency (`call_arg`
1680    // is refused on them).
1681    // `.call` joins the formals string only, never `inputs`, so the
1682    // precondition builder, the marker peels and the parameter fillers never
1683    // see it as a Rust parameter.
1684    let call_formal = call_attribution.formal().filter(|_| !is_s3_method);
1685    // Stable, consistent R formatting style: brace on same line, body indented, closing brace on its own line
1686    // r_formals is already a joined string from build_formals()
1687    let formals_joined = r_wrapper_builder::with_call_formal(&r_formals, call_formal);
1688    let mut roxygen_tags = if let Some(ref doc_text) = doc {
1689        // Custom doc override: each line becomes a separate roxygen tag entry
1690        doc_text.lines().map(|l| l.to_string()).collect()
1691    } else {
1692        // `noexport` renders no page (it appends `@noRd` below), so its docs
1693        // keep no links (#1818); the reader sees an explicit `@noRd` itself.
1694        crate::roxygen::roxygen_tags_from_attrs(
1695            attrs,
1696            crate::roxygen::RdPage::suppressed_if(noexport),
1697        )
1698    };
1699
1700    // Determine lifecycle: explicit attr > #[deprecated] extraction
1701    let lifecycle_spec = lifecycle.or_else(|| {
1702        attrs
1703            .iter()
1704            .find_map(crate::lifecycle::parse_rust_deprecated)
1705    });
1706
1707    // Inject lifecycle badge into roxygen tags if present
1708    if let Some(ref spec) = lifecycle_spec {
1709        crate::lifecycle::inject_lifecycle_badge(&mut roxygen_tags, spec);
1710    }
1711
1712    // Generated @param tags for the parameters the author left undocumented,
1713    // unless the block takes them from a `@describeIn` topic or
1714    // `@inheritParams` (#1590); the wrapper registry decides the rest per page
1715    // at write time. The match_arg placeholders feed the
1716    // MX_MATCH_ARG_PARAM_DOCS entries of the write-time resolver. The `.call`
1717    // formal gets its line after the parameters' (#1613, #1834), unless the
1718    // block renders no page (`noexport`, `@noRd`): it is no filler, so the
1719    // registry would not drop it there.
1720    let renders_no_page = noexport || crate::roxygen::has_roxygen_tag(&roxygen_tags, "noRd");
1721    let call_param_doc = call_formal
1722        .and(call_attribution.param_doc())
1723        .filter(|_| !renders_no_page);
1724    let match_arg_param_doc_placeholders = crate::roxygen::push_fn_param_tags(
1725        &mut roxygen_tags,
1726        inputs,
1727        &parsed,
1728        &c_ident_str,
1729        call_param_doc,
1730    );
1731
1732    // A standalone function's reference page is titled by its R wrapper name — never
1733    // the doc-comment prose. rustdoc summaries are markdown (intra-doc links, code
1734    // spans) that roxygen2 can't resolve as a `\title`; the prose is promoted to
1735    // `@description` by `roxygen_tags_from_attrs` instead. Without a `@title`, roxygen2
1736    // skips the `.Rd` entirely (#1054), so inject the wrapper name when none exists.
1737    // A block that renders no page (`@noRd`, or `noexport` which appends it below)
1738    // needs no title (#1552).
1739    let has_no_rd_tag = crate::roxygen::has_roxygen_tag(&roxygen_tags, "noRd");
1740    if !roxygen_tags.is_empty()
1741        && !has_no_rd_tag
1742        && !noexport
1743        && !crate::roxygen::has_roxygen_tag(&roxygen_tags, "title")
1744    {
1745        roxygen_tags.insert(0, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("@title {0}", r_wrapper_ident_str))
    })format!("@title {}", r_wrapper_ident_str));
1746    }
1747
1748    let roxygen_tags_str = crate::roxygen::format_roxygen_tags(&roxygen_tags);
1749    let has_export_tag = crate::roxygen::has_export_tag(&roxygen_tags);
1750    let has_internal_tag = crate::roxygen::has_roxygen_tag(&roxygen_tags, "keywords internal");
1751    // `@source` provenance is opt-in per crate (#1552); the `# Generated from
1752    // Rust fn … (file:line:col)` comment below stays the navigation pointer.
1753    let source_comment = crate::roxygen::source_tag_with(
1754        crate_config.source_tags,
1755        &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated by miniextendr from Rust fn `{0}`",
                rust_ident))
    })format!("Generated by miniextendr from Rust fn `{rust_ident}`"),
1756    )
1757    .map(|line| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\n", line))
    })format!("{line}\n"))
1758    .unwrap_or_default();
1759    // Inject @keywords internal if #[miniextendr(internal)] and not already present
1760    let internal_comment = if internal && !has_internal_tag {
1761        "#' @keywords internal\n"
1762    } else {
1763        ""
1764    };
1765    // S3 methods need both @method (for registration) AND @export (for NAMESPACE)
1766    // Don't auto-export functions marked with @noRd, @keywords internal, or attr flags
1767    // #[miniextendr(export)] forces @export even on non-pub functions
1768    let export_comment = if (#[allow(non_exhaustive_omitted_patterns)] match vis {
    syn::Visibility::Public(_) => true,
    _ => false,
}matches!(vis, syn::Visibility::Public(_)) || export)
1769        && !has_export_tag
1770        && !has_no_rd_tag
1771        && !has_internal_tag
1772        && !internal
1773        && !noexport
1774    {
1775        // A method on `pkg::generic` registers through `@exportS3Method
1776        // pkg::generic class`: roxygen2 writes `S3method(pkg::generic, class)`,
1777        // which R applies once `pkg`'s namespace loads, so `pkg` may stay in
1778        // Suggests (#2154).
1779        s3_qualified_registration.unwrap_or_else(|| "#' @export\n".to_string())
1780    } else {
1781        String::new()
1782    };
1783    // `noexport` means no man page at all (docs/CLASS_SYSTEMS.md export-control
1784    // table): inject @noRd so roxygen2 skips the Rd and the write-time page
1785    // pass (registry.rs) gives the fn no default title. Without this, an
1786    // unexported fn keeps a \usage entry in man/, which R CMD check flags as a
1787    // code/documentation mismatch.
1788    let no_rd_comment = if noexport && !has_no_rd_tag {
1789        "#' @noRd\n"
1790    } else {
1791        ""
1792    };
1793    // Generate match.arg prelude for parameters with #[miniextendr(match_arg)]
1794    // Collect (r_param_name, rust_name, rust_type) for each match_arg param
1795    let match_arg_param_info: Vec<(String, String, &syn::Type)> = inputs
1796        .iter()
1797        .filter_map(|arg| {
1798            if let syn::FnArg::Typed(pt) = arg
1799                && let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
1800            {
1801                let rust_name = crate::naming::ident_name(&pat_ident.ident);
1802                if parsed.has_match_arg_attr(&rust_name) {
1803                    let r_name = formals.of(&rust_name);
1804                    return Some((r_name, rust_name, pt.ty.as_ref()));
1805                }
1806            }
1807            None
1808        })
1809        .collect();
1810
1811    let match_arg_prelude = if match_arg_param_info.is_empty() {
1812        String::new()
1813    } else {
1814        let mut lines = Vec::new();
1815        for (r_param, rust_name, _) in &match_arg_param_info {
1816            // Every form names the choice list through the same placeholder the
1817            // formal default carries (populated by the write-time pass as
1818            // `c("a", "b", ...)`; it substitutes every occurrence). Strict
1819            // several_ok (#1472): every element must match; NULL selects every
1820            // choice. `Option<T>` (#1473): NULL means no choice and skips the
1821            // check; `Missing<T>` (#1551) skips it for an omitted argument and,
1822            // for a single choice, for the formal passed whole (#2152), as the
1823            // `.mx_absent_<p>` flag bound in front of it says (#2182). The
1824            // helpers read a factor as its labels (#1552). Under `call = caller`
1825            // every form raises with `.mx_call` (#1548).
1826            let key = crate::match_arg_keys::param_key(rust_name);
1827            let placeholder =
1828                crate::match_arg_keys::choices_placeholder(&c_ident.to_string(), &key);
1829            let aliases = crate::match_arg_keys::aliases_placeholder(&c_ident.to_string(), &key);
1830            if let Some(attrs) = parsed.param_attrs(rust_name) {
1831                lines.extend(call_attribution.match_arg_lines(
1832                    r_param,
1833                    &placeholder,
1834                    Some(&aliases),
1835                    attrs,
1836                ));
1837            }
1838        }
1839        lines.join("\n  ")
1840    };
1841
1842    // Generate the match.arg prelude for choices params: the same three forms
1843    // as `match_arg`, with the literal choice list known here.
1844    let choices_prelude = {
1845        let mut lines = Vec::new();
1846        for arg in inputs.iter() {
1847            if let syn::FnArg::Typed(pt) = arg
1848                && let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
1849            {
1850                let rust_name = crate::naming::ident_name(&pat_ident.ident);
1851                if let Some(attrs) = parsed.param_attrs(&rust_name)
1852                    && let Some(choices) = attrs.choices.as_ref()
1853                {
1854                    let r_name = formals.of(&rust_name);
1855                    let quoted: Vec<String> =
1856                        choices.iter().map(|c| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"", c))
    })format!("\"{}\"", c)).collect();
1857                    let choices_expr = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("c({0})", quoted.join(", ")))
    })format!("c({})", quoted.join(", "));
1858                    lines.extend(call_attribution.match_arg_lines(
1859                        &r_name,
1860                        &choices_expr,
1861                        None,
1862                        attrs,
1863                    ));
1864                }
1865            }
1866        }
1867        if lines.is_empty() {
1868            String::new()
1869        } else {
1870            lines.join("\n  ")
1871        }
1872    };
1873
1874    // Generate lifecycle prelude if needed
1875    let lifecycle_prelude = lifecycle_spec
1876        .as_ref()
1877        .and_then(|spec| spec.r_prelude(&r_wrapper_ident_str));
1878
1879    // Generate R-side precondition checks (one `isTRUE()` guard per check)
1880    // Skip both match_arg and choices params (already validated by match.arg)
1881    // and `Quoted` / `Quosure` params, which no check may force (#1835).
1882    let mut skip_params = parsed.precondition_skip_params();
1883    skip_params.extend(unevaluated_r_names.iter().cloned());
1884    // A parameter drops its type-derived checks when its own spelling
1885    // (`Unchecked<T>`, `#[miniextendr(no_preconditions)]` on it), else the
1886    // function's `no_preconditions`, else the crate's `preconditions = false`,
1887    // else the `no-preconditions-default` feature says so (#1566,
1888    // `r_preconditions::resolve_type_checks`). TryFromSexp still raises a
1889    // typed Rust error on mismatched input. The savings were measured against
1890    // the former `stopifnot()` block (~1230 ns / 1-arg or ~3900 ns / 5-arg);
1891    // the guards cost about half. The per-parameter `inherits` /
1892    // `not_inherits` / `no_na` checks stay: the Rust conversion does not
1893    // repeat them. (The C wrapper's
1894    // post-conversion `no_na` check covers only what a type reads as `NA`
1895    // beyond `anyNA()`, such as `"NA"` for `AsNumeric`, except on an
1896    // `Either`, which has no R guard and is checked only in Rust.)
1897    let precondition_prelude = {
1898        // `set.seed()` validates the seed of `rng(seed = ..)` (#2198), so
1899        // its parameter has no type-derived check.
1900        let mut unchecked = r_preconditions::unchecked_params(
1901            inputs,
1902            &formals,
1903            |name| parsed.param_attrs(name).and_then(|a| a.preconditions),
1904            preconditions,
1905            None,
1906            crate_config.preconditions,
1907        );
1908        unchecked.extend(rng_seed_formal.iter().cloned());
1909        // A coerced integer-element vector reads via `&[i32]` (INTSXP-only), so its
1910        // precondition tightens to `is.integer` (issue #616). `coerce_params_list`
1911        // holds Rust names; the options are keyed by R formal.
1912        let precondition_opts = r_preconditions::PreconditionOptions {
1913            coerce_all,
1914            coerce_params: coerce_params_list.iter().map(|p| formals.of(p)).collect(),
1915            explicit: parsed.explicit_checks(),
1916            unchecked,
1917            formals: formals.clone(),
1918        };
1919        let precondition_output =
1920            r_preconditions::build_precondition_checks(inputs, &skip_params, &precondition_opts);
1921        // One guard per check, raising the shared argument error (#1591):
1922        // attributed to the wrapper's own call, or under `call = caller` to
1923        // `.mx_call` (#1548).
1924        precondition_output
1925            .guards(call_attribution.r_check_call())
1926            .join("\n  ")
1927    };
1928
1929    // `dots = empty | forward(..)` (#2157): refuse what `...` doesn't take,
1930    // ahead of the argument checks, so a misspelt argument is reported before
1931    // the missing one it was meant to be.
1932    let dots_check = dots_policy
1933        .as_ref()
1934        .and_then(|policy| policy.r_check(&formals_joined, call_attribution.r_check_call()));
1935
1936    // Combine all preludes: call attribution (`.mx_call` under `call = caller`,
1937    // first so the R-side checks below can raise with it, #1548), r_entry,
1938    // on.exit, lifecycle, the `...` check, static preconditions, match.arg,
1939    // choices, r_post_checks, and last the seed contract of `rng(seed = ..)`
1940    // (#2198), so that a refused argument changes no RNG state. (Missing<T>
1941    // forwarding lives inline in the `.Call()` args — see
1942    // `build_call_args_vec` — because a prelude binding of the missing
1943    // sentinel errors on lookup. What the match.arg and choices parts bind
1944    // for it is a flag: `.mx_absent_<p>` of a single-choice parameter, #2182.)
1945    let on_exit_str = r_on_exit.as_ref().map(|oe| oe.to_r_code());
1946    let rng_seed_prelude = rng_seed_formal
1947        .as_deref()
1948        .map(|formal| r_wrapper_builder::RngSeedContract { formal }.prelude("  "));
1949    let attribution_prelude = call_attribution.prelude(call_formal.is_some());
1950    let combined_prelude = {
1951        let mut parts = Vec::new();
1952        if !attribution_prelude.is_empty() {
1953            parts.push(attribution_prelude.as_str());
1954        }
1955        if let Some(ref entry) = r_entry {
1956            parts.push(entry.as_str());
1957        }
1958        if let Some(ref s) = on_exit_str {
1959            parts.push(s.as_str());
1960        }
1961        if let Some(ref lc) = lifecycle_prelude {
1962            parts.push(lc.as_str());
1963        }
1964        if let Some(ref check) = dots_check {
1965            parts.push(check.as_str());
1966        }
1967        if !precondition_prelude.is_empty() {
1968            parts.push(&precondition_prelude);
1969        }
1970        if !match_arg_prelude.is_empty() {
1971            parts.push(&match_arg_prelude);
1972        }
1973        if !choices_prelude.is_empty() {
1974            parts.push(&choices_prelude);
1975        }
1976        if let Some(ref post) = r_post_checks {
1977            parts.push(post.as_str());
1978        }
1979        if let Some(ref seed) = rng_seed_prelude {
1980            parts.push(seed.as_str());
1981        }
1982        if parts.is_empty() {
1983            None
1984        } else {
1985            Some(parts.join("\n  "))
1986        }
1987    };
1988
1989    let r_wrapper_string = if let Some(prelude) = combined_prelude {
1990        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}{3}{4}{5}{6} <- function({7}) {{\n  {8}\n  {9}\n}}",
                roxygen_tags_str, source_comment, s3_method_comment,
                internal_comment, no_rd_comment, export_comment,
                crate::naming::r_def_name(&r_wrapper_ident_str),
                formals_joined, prelude, r_wrapper_return_str))
    })format!(
1991            "{}{}{}{}{}{}{} <- function({}) {{\n  {}\n  {}\n}}",
1992            roxygen_tags_str,
1993            source_comment,
1994            s3_method_comment,
1995            internal_comment,
1996            no_rd_comment,
1997            export_comment,
1998            crate::naming::r_def_name(&r_wrapper_ident_str),
1999            formals_joined,
2000            prelude,
2001            r_wrapper_return_str
2002        )
2003    } else {
2004        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}{3}{4}{5}{6} <- function({7}) {{\n  {8}\n}}",
                roxygen_tags_str, source_comment, s3_method_comment,
                internal_comment, no_rd_comment, export_comment,
                crate::naming::r_def_name(&r_wrapper_ident_str),
                formals_joined, r_wrapper_return_str))
    })format!(
2005            "{}{}{}{}{}{}{} <- function({}) {{\n  {}\n}}",
2006            roxygen_tags_str,
2007            source_comment,
2008            s3_method_comment,
2009            internal_comment,
2010            no_rd_comment,
2011            export_comment,
2012            crate::naming::r_def_name(&r_wrapper_ident_str),
2013            formals_joined,
2014            r_wrapper_return_str
2015        )
2016    };
2017    // Use a raw string literal for better readability in macro expansion
2018    let r_wrapper_str = r_wrapper_raw_literal(
2019        &r_wrapper_string,
2020        &r_shadowing::formal_names([(inputs, formals.clone())]),
2021    );
2022
2023    // endregion
2024
2025    // Generate doc strings with links
2026    let r_wrapper_doc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("R wrapper code for [`{0}`], calls [`{1}`].",
                rust_ident, c_ident))
    })format!(
2027        "R wrapper code for [`{}`], calls [`{}`].",
2028        rust_ident, c_ident
2029    );
2030    let source_start = rust_ident.span().start();
2031    let source_line_lit = syn::LitInt::new(&source_start.line.to_string(), rust_ident.span());
2032    let source_col_lit =
2033        syn::LitInt::new(&(source_start.column + 1).to_string(), rust_ident.span());
2034
2035    // Get the normalized item for output, with roxygen tags stripped from docs.
2036    // Roxygen tags are for R documentation and shouldn't appear in rustdoc.
2037    let mut original_item = parsed.item_without_roxygen();
2038    // Strip only the miniextendr attributes; keep everything else.
2039    original_item
2040        .attrs
2041        .retain(|attr| !attr.path().is_ident("miniextendr"));
2042
2043    // Inject dots_typed binding into function body if dots = typed_list!(...) was specified
2044    // (the gate above guarantees the dots parameter exists).
2045    if let (Some(spec_tokens), Some(dots_param)) = (&dots_spec, &dots_ident) {
2046        let validation_stmt = build_dots_validation_stmt(dots_param, spec_tokens);
2047        original_item.block.stmts.insert(0, validation_stmt);
2048    }
2049
2050    let original_item = original_item;
2051
2052    // Generate MX_MATCH_ARG_CHOICES entries for placeholder → choices replacement
2053    // Resolve the `MatchArg`-bound type used in the choices_str closure: for
2054    // `several_ok` params that's the inner element of the container, otherwise
2055    // it's the param type directly.
2056    let choices_ty_for = |rust_param: &str| -> Option<&syn::Type> {
2057        let (_, _, param_ty) = match_arg_param_info
2058            .iter()
2059            .find(|(_, rn, _)| rn == rust_param)?;
2060        Some(match_arg_choices_ty(
2061            param_ty,
2062            parsed.has_several_ok(rust_param),
2063        ))
2064    };
2065
2066    let match_arg_choices_entries: Vec<proc_macro2::TokenStream> = match_arg_placeholders
2067        .iter()
2068        .filter_map(
2069            |(placeholder, aliases_placeholder, rust_param, preferred_default)| {
2070                let choices_ty = choices_ty_for(rust_param)?;
2071                let entry_ident = syn::Ident::new(
2072                    &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("match_arg_choices_entry_{0}",
                crate::match_arg_keys::placeholder_ident_suffix(placeholder)))
    })format!(
2073                        "match_arg_choices_entry_{}",
2074                        crate::match_arg_keys::placeholder_ident_suffix(placeholder)
2075                    ),
2076                    proc_macro2::Span::call_site(),
2077                );
2078                Some(crate::match_arg_keys::choices_entry_tokens(
2079                    &cfg_attrs,
2080                    &entry_ident,
2081                    placeholder,
2082                    aliases_placeholder,
2083                    choices_ty,
2084                    preferred_default,
2085                ))
2086            },
2087        )
2088        .collect();
2089
2090    // Generate MX_MATCH_ARG_PARAM_DOCS entries for @param doc placeholder → choice description
2091    let match_arg_param_doc_entries: Vec<proc_macro2::TokenStream> =
2092        match_arg_param_doc_placeholders
2093            .iter()
2094            .filter_map(|(doc_placeholder, rust_param)| {
2095                let choices_ty = choices_ty_for(rust_param)?;
2096                let attrs = parsed.param_attrs(rust_param)?;
2097                let entry_ident = syn::Ident::new(
2098                    &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("match_arg_param_doc_entry_{0}",
                crate::match_arg_keys::placeholder_ident_suffix(doc_placeholder)))
    })format!(
2099                        "match_arg_param_doc_entry_{}",
2100                        crate::match_arg_keys::placeholder_ident_suffix(doc_placeholder)
2101                    ),
2102                    proc_macro2::Span::call_site(),
2103                );
2104                Some(crate::match_arg_keys::param_doc_entry_tokens(
2105                    &cfg_attrs,
2106                    &entry_ident,
2107                    doc_placeholder,
2108                    attrs.several_ok,
2109                    &attrs.choice_doc_suffix(),
2110                    choices_ty,
2111                ))
2112            })
2113            .collect();
2114
2115    // Generate doc comment linking to C wrapper and R wrapper constant
2116    let fn_r_wrapper_doc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("See [`{0}`] for C wrapper, [`{1}`] for R wrapper.",
                c_ident, r_wrapper_generator))
    })format!(
2117        "See [`{}`] for C wrapper, [`{}`] for R wrapper.",
2118        c_ident, r_wrapper_generator
2119    );
2120
2121    let expanded: T = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&fn_r_wrapper_doc, &mut _s);
            _s
        });
    ::quote::ToTokens::to_tokens(&original_item, &mut _s);
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut cfg_attrs, i) = cfg_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let cfg_attrs =
                match cfg_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&cfg_attrs, &mut _s);
        }
    }
    ::quote::ToTokens::to_tokens(&c_wrapper, &mut _s);
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut cfg_attrs, i) = cfg_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let cfg_attrs =
                match cfg_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&cfg_attrs, &mut _s);
        }
    }
    ::quote::__private::push_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(&r_wrapper_doc, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"Wraps Rust function `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "stringify");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&rust_ident, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&source_loc_doc, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"Generated from source file `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "file");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "cfg_attr");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "not");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "target_arch");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::parse(&mut _s, "\"wasm32\"");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "distributed_slice");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "registry");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "MX_R_WRAPPERS");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "crate");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "linkme");
                            _s
                        });
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "non_upper_case_globals");
                    _s
                });
            _s
        });
    ::quote::__private::push_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, "static");
    ::quote::ToTokens::to_tokens(&r_wrapper_generator, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "RWrapperEntry");
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "RWrapperEntry");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "priority");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "registry");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "RWrapperPriority");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Function");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "source_file");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "file");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "source_line");
            ::quote::__private::push_colon(&mut _s);
            ::quote::ToTokens::to_tokens(&source_line_lit, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_ident(&mut _s, "content");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"# Generated from Rust fn `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "stringify");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&rust_ident, &mut _s);
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"` (\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "file");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\":\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&source_line_lit, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\":\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&source_col_lit, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\")\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&r_wrapper_str, &mut _s);
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut match_arg_choices_entries, i) =
            match_arg_choices_entries.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let match_arg_choices_entries =
                match match_arg_choices_entries.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&match_arg_choices_entries, &mut _s);
        }
    }
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut match_arg_param_doc_entries, i) =
            match_arg_param_doc_entries.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let match_arg_param_doc_entries =
                match match_arg_param_doc_entries.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&match_arg_param_doc_entries,
                &mut _s);
        }
    }
    ::quote::ToTokens::to_tokens(&doc_lint_warnings, &mut _s);
    _s
}quote::quote! {
2122        // rust function with doc link to R wrapper
2123        #[doc = #fn_r_wrapper_doc]
2124        #original_item
2125
2126        // C wrapper
2127        #(#cfg_attrs)*
2128        #c_wrapper
2129
2130        // R wrapper (self-registers via distributed_slice)
2131        #(#cfg_attrs)*
2132        #[doc = #r_wrapper_doc]
2133        #[doc = ::core::concat!("Wraps Rust function `", ::core::stringify!(#rust_ident), "`.")]
2134        #[doc = #source_loc_doc]
2135        #[doc = ::core::concat!("Generated from source file `", ::core::file!(), "`.")]
2136        #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_R_WRAPPERS), linkme(crate = ::miniextendr_api::linkme))]
2137        #[allow(non_upper_case_globals)]
2138        #[allow(non_snake_case)]
2139        static #r_wrapper_generator: ::miniextendr_api::registry::RWrapperEntry =
2140            ::miniextendr_api::registry::RWrapperEntry {
2141                priority: ::miniextendr_api::registry::RWrapperPriority::Function,
2142                source_file: ::core::file!(),
2143                source_line: #source_line_lit,
2144                content: ::core::concat!(
2145                    "# Generated from Rust fn `",
2146                    ::core::stringify!(#rust_ident),
2147                    "` (",
2148                    ::core::file!(),
2149                    ":",
2150                    #source_line_lit,
2151                    ":",
2152                    #source_col_lit,
2153                    ")",
2154                    #r_wrapper_str
2155                ),
2156            };
2157
2158        // match_arg choices entries for R wrapper default replacement
2159        #(#match_arg_choices_entries)*
2160
2161        // match_arg @param doc entries for R wrapper roxygen doc replacement
2162        #(#match_arg_param_doc_entries)*
2163
2164        // doc-lint warnings (if any)
2165        #doc_lint_warnings
2166    }
2167    .into();
2168
2169    expanded
2170}
2171
2172/// Maps a `ReturnPref` attribute value onto an auto-detected `ReturnHandling`.
2173///
2174/// Only the plain `IntoR` variant has a bare `T` for `prefer=` to wrap, so it is the
2175/// only variant substituted with its pref-specific counterpart
2176/// (`AsListOf`/`AsExternalPtrOf`/`AsNativeOf`). Every other variant (`Unit`, `RawSexp`,
2177/// `ExternalPtr`, `Option*`, `Result*`) has its own fixed SEXP-shape rule that
2178/// `prefer=` cannot compose with — returning a compile error for those is better than
2179/// silently dropping the attribute (see the BUG4 audit finding: `prefer = "list"` on an
2180/// `Option<T>` return used to be accepted and silently ignored).
2181fn apply_return_pref(
2182    auto: c_wrapper_builder::ReturnHandling,
2183    pref: crate::miniextendr_fn::ReturnPref,
2184    pref_span: Option<proc_macro2::Span>,
2185) -> syn::Result<c_wrapper_builder::ReturnHandling> {
2186    use crate::miniextendr_fn::ReturnPref;
2187    use c_wrapper_builder::ReturnHandling;
2188
2189    let wrapped = match pref {
2190        ReturnPref::Auto => return Ok(auto),
2191        ReturnPref::List => match auto {
2192            ReturnHandling::IntoR => Some(ReturnHandling::AsListOf),
2193            _ => None,
2194        },
2195        ReturnPref::ExternalPtr => match auto {
2196            ReturnHandling::IntoR => Some(ReturnHandling::AsExternalPtrOf),
2197            _ => None,
2198        },
2199        ReturnPref::Native => match auto {
2200            ReturnHandling::IntoR => Some(ReturnHandling::AsNativeOf),
2201            _ => None,
2202        },
2203    };
2204
2205    wrapped.ok_or_else(|| {
2206        let (pref_name, wrapper_name) = return_pref_names(pref);
2207        let span = pref_span.unwrap_or_else(proc_macro2::Span::call_site);
2208        syn::Error::new(
2209            span,
2210            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`prefer = \"{1}\"` cannot be honored on this return type. `prefer=` only applies to a function returning a plain `T: IntoR` value, which it wraps in `{2}` before conversion. This function\'s return type falls into a different codegen category ({0}) with its own fixed SEXP-shape rule, so there is no plain `T` for `prefer=` to wrap. Remove `prefer=`, or change the return type to a plain `T`.",
                return_handling_category_description(&auto), pref_name,
                wrapper_name))
    })format!(
2211                "`prefer = \"{pref_name}\"` cannot be honored on this return type. \
2212                 `prefer=` only applies to a function returning a plain `T: IntoR` value, \
2213                 which it wraps in `{wrapper_name}` before conversion. This function's return \
2214                 type falls into a different codegen category ({}) with its own fixed \
2215                 SEXP-shape rule, so there is no plain `T` for `prefer=` to wrap. Remove \
2216                 `prefer=`, or change the return type to a plain `T`.",
2217                return_handling_category_description(&auto),
2218            ),
2219        )
2220    })
2221}
2222
2223/// Human-readable `(attribute value, wrapper type)` pair for a [`ReturnPref`](crate::miniextendr_fn::ReturnPref),
2224/// used to phrase the `apply_return_pref` compile error.
2225fn return_pref_names(pref: crate::miniextendr_fn::ReturnPref) -> (&'static str, &'static str) {
2226    use crate::miniextendr_fn::ReturnPref;
2227    match pref {
2228        ReturnPref::Auto => ("auto", ""),
2229        ReturnPref::List => ("list", "AsList"),
2230        ReturnPref::ExternalPtr => ("externalptr", "AsExternalPtr"),
2231        ReturnPref::Native => ("native", "AsRNative"),
2232    }
2233}
2234
2235/// Human-readable description of a [`ReturnHandling`](c_wrapper_builder::ReturnHandling)
2236/// category, for the `apply_return_pref` compile error. Only describes the categories
2237/// [`c_wrapper_builder::detect_return_handling`] can actually produce;
2238/// the wildcard arm covers variants that never reach `apply_return_pref` as `auto`
2239/// (`IntoR` itself, method-only `SelfHandle`, and the `As*Of` variants `apply_return_pref`
2240/// produces as *output*, never takes as input).
2241fn return_handling_category_description(rh: &c_wrapper_builder::ReturnHandling) -> &'static str {
2242    use c_wrapper_builder::ReturnHandling;
2243    match rh {
2244        ReturnHandling::Unit => "the unit return type `()`",
2245        ReturnHandling::RawSexp => "a raw `SEXP` return type",
2246        ReturnHandling::ExternalPtr => {
2247            "a `Self`-returning constructor, already converted via `ExternalPtr::new`"
2248        }
2249        ReturnHandling::OptionUnit => "`Option<()>`",
2250        ReturnHandling::OptionSexp => "`Option<SEXP>`",
2251        ReturnHandling::OptionIntoR | ReturnHandling::OptionClassPayload => "`Option<T>`",
2252        ReturnHandling::ResultUnit => "`Result<(), E>`",
2253        ReturnHandling::ResultSexp => "`Result<SEXP, E>`",
2254        ReturnHandling::ResultIntoR => "`Result<T, E>`",
2255        ReturnHandling::ResultNullOnErr => "`Result<T, ()>`",
2256        _ => "this return type",
2257    }
2258}
2259
2260/// Generate main-thread-checked wrappers for R FFI functions.
2261///
2262/// Apply this to an `extern "C-unwind"` block to generate, **for each
2263/// non-variadic function**, a pair of entry points:
2264///
2265/// - The original name (e.g. `Rf_allocVector`) — a wrapper that runs the call
2266///   through `miniextendr_api::with_r_thread`: directly on R's main thread,
2267///   and a panic on any other thread.
2268/// - A `*_unchecked` sibling (`Rf_allocVector_unchecked`) — the raw
2269///   `extern "C-unwind"` declaration with no main-thread assertion.
2270///
2271/// User code should reach for the checked variant by default; the unchecked
2272/// sibling exists for three known-safe contexts:
2273///
2274/// 1. **Inside ALTREP callbacks** — R is already calling us on the main
2275///    thread, so the assertion would always pass.
2276/// 2. **Inside a `with_r_unwind_protect` body** — the guard runs on R's main
2277///    thread, so the assertion is redundant.
2278/// 3. **Inside a `with_r_thread` body** — the assertion is redundant; you
2279///    are already where you needed to be.
2280///
2281/// The build-time lint **MXL301** enforces this: calling `*_unchecked`
2282/// outside one of those three contexts is a compile-time error.
2283///
2284/// # Tradeoffs at a glance
2285///
2286/// | Variant | Asserts main thread | When to use |
2287/// |---|---|---|
2288/// | `Rf_foo` (checked) | yes | default |
2289/// | `Rf_foo_unchecked` | no | ALTREP callbacks, `with_r_unwind_protect`, `with_r_thread` |
2290///
2291/// # Behavior
2292///
2293/// Every non-variadic function calls its `*_unchecked` sibling inside
2294/// `with_r_thread`, which panics off R's main thread before the call reaches
2295/// R. This applies to value-returning functions (SEXP, i32, etc.),
2296/// pointer-returning functions (`*const T`, `*mut T`), and never-returning
2297/// ones (`Rf_error`).
2298///
2299/// # Initialization Requirement
2300///
2301/// `miniextendr_runtime_init()` must be called before using any wrapped function.
2302/// Calling before initialization will panic with a descriptive error message.
2303///
2304/// # Limitations
2305///
2306/// - Variadic functions are passed through unchanged (no wrapper)
2307/// - Statics are passed through unchanged
2308/// - Functions with `#[link_name]` are passed through unchanged
2309///
2310/// # Example
2311///
2312/// ```ignore
2313/// #[r_ffi_checked]
2314/// unsafe extern "C-unwind" {
2315///     // Panics off R's main thread
2316///     pub fn Rf_ScalarInteger(arg1: i32) -> SEXP;
2317///     pub fn INTEGER(x: SEXP) -> *mut i32;
2318/// }
2319/// ```
2320#[proc_macro_attribute]
2321pub fn r_ffi_checked(
2322    _attr: proc_macro::TokenStream,
2323    item: proc_macro::TokenStream,
2324) -> proc_macro::TokenStream {
2325    let foreign_mod = match ::syn::parse::<syn::ItemForeignMod>(item) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(item as syn::ItemForeignMod);
2326
2327    let foreign_mod_attrs = &foreign_mod.attrs;
2328    let abi = &foreign_mod.abi;
2329    let mut unchecked_items = Vec::new();
2330    let mut checked_wrappers = Vec::new();
2331
2332    for item in &foreign_mod.items {
2333        match item {
2334            syn::ForeignItem::Fn(fn_item) => {
2335                let is_variadic = fn_item.sig.variadic.is_some();
2336
2337                // Check if function already has #[link_name] - if so, pass through unchanged
2338                let has_link_name = fn_item
2339                    .attrs
2340                    .iter()
2341                    .any(|attr| attr.path().is_ident("link_name"));
2342
2343                if is_variadic || has_link_name {
2344                    // Pass through variadic functions and functions with explicit link_name unchanged
2345                    unchecked_items.push(item.clone());
2346                } else {
2347                    // Generate checked wrapper for non-variadic functions
2348                    let vis = &fn_item.vis;
2349                    let fn_name = &fn_item.sig.ident;
2350                    let fn_name_str = fn_name.to_string();
2351                    let unchecked_name = match ::quote::__private::IdentFragmentAdapter(&fn_name) {
    arg =>
        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("{0}_unchecked", arg))
                    }), ::quote::__private::Option::None.or(arg.span())),
}quote::format_ident!("{}_unchecked", fn_name);
2352                    let unchecked_name_str = unchecked_name.to_string();
2353                    let inputs = &fn_item.sig.inputs;
2354                    let output = &fn_item.sig.output;
2355                    // Filter out link_name attributes (already checked above, but be safe)
2356                    let attrs: Vec<_> = fn_item
2357                        .attrs
2358                        .iter()
2359                        .filter(|attr| !attr.path().is_ident("link_name"))
2360                        .collect();
2361                    let checked_doc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Checked wrapper for `{0}`. Calls `{1}` inside `with_r_thread`, which panics off R\'s main thread.",
                fn_name_str, unchecked_name_str))
    })format!(
2362                        "Checked wrapper for `{}`. Calls `{}` inside `with_r_thread`, which panics off R's main thread.",
2363                        fn_name_str, unchecked_name_str
2364                    );
2365                    let checked_doc_lit = syn::LitStr::new(&checked_doc, fn_name.span());
2366                    let source_loc_doc = crate::source_location_doc(fn_name.span());
2367                    let source_loc_doc_lit = syn::LitStr::new(&source_loc_doc, fn_name.span());
2368
2369                    // Generate the unchecked FFI binding with #[link_name]
2370                    // Same visibility as the checked variant
2371                    let link_name = syn::LitStr::new(&fn_name_str, fn_name.span());
2372                    let unchecked_fn: syn::ForeignItem = ::syn::__private::parse_quote({
        let mut _s = ::quote::__private::TokenStream::new();
        {
            use ::quote::__private::ext::*;
            let has_iter = ::quote::__private::HasIterator::<false>;
            #[allow(unused_mut)]
            let (mut attrs, i) = attrs.quote_into_iter();
            let has_iter = has_iter | i;
            <_ as
                    ::quote::__private::CheckHasIterator<true>>::check(has_iter);
            while true {
                let attrs =
                    match attrs.next() {
                        Some(_x) => ::quote::__private::RepInterp(_x),
                        None => break,
                    };
                ::quote::ToTokens::to_tokens(&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::__private::push_colon2(&mut _s);
                ::quote::__private::push_ident(&mut _s, "core");
                ::quote::__private::push_colon2(&mut _s);
                ::quote::__private::push_ident(&mut _s, "concat");
                ::quote::__private::push_bang(&mut _s);
                ::quote::__private::push_group(&mut _s,
                    ::quote::__private::Delimiter::Parenthesis,
                    {
                        let mut _s = ::quote::__private::TokenStream::new();
                        ::quote::__private::parse(&mut _s,
                            "\"Unchecked FFI binding for `\"");
                        ::quote::__private::push_comma(&mut _s);
                        ::quote::__private::push_colon2(&mut _s);
                        ::quote::__private::push_ident(&mut _s, "core");
                        ::quote::__private::push_colon2(&mut _s);
                        ::quote::__private::push_ident(&mut _s, "stringify");
                        ::quote::__private::push_bang(&mut _s);
                        ::quote::__private::push_group(&mut _s,
                            ::quote::__private::Delimiter::Parenthesis,
                            {
                                let mut _s = ::quote::__private::TokenStream::new();
                                ::quote::ToTokens::to_tokens(&fn_name, &mut _s);
                                _s
                            });
                        ::quote::__private::push_comma(&mut _s);
                        ::quote::__private::parse(&mut _s, "\"`.\"");
                        _s
                    });
                _s
            });
        ::quote::__private::push_pound(&mut _s);
        ::quote::__private::push_group(&mut _s,
            ::quote::__private::Delimiter::Bracket,
            {
                let mut _s = ::quote::__private::TokenStream::new();
                ::quote::__private::push_ident(&mut _s, "doc");
                ::quote::__private::push_eq(&mut _s);
                ::quote::ToTokens::to_tokens(&source_loc_doc_lit, &mut _s);
                _s
            });
        ::quote::__private::push_pound(&mut _s);
        ::quote::__private::push_group(&mut _s,
            ::quote::__private::Delimiter::Bracket,
            {
                let mut _s = ::quote::__private::TokenStream::new();
                ::quote::__private::push_ident(&mut _s, "doc");
                ::quote::__private::push_eq(&mut _s);
                ::quote::__private::push_colon2(&mut _s);
                ::quote::__private::push_ident(&mut _s, "core");
                ::quote::__private::push_colon2(&mut _s);
                ::quote::__private::push_ident(&mut _s, "concat");
                ::quote::__private::push_bang(&mut _s);
                ::quote::__private::push_group(&mut _s,
                    ::quote::__private::Delimiter::Parenthesis,
                    {
                        let mut _s = ::quote::__private::TokenStream::new();
                        ::quote::__private::parse(&mut _s,
                            "\"Generated from source file `\"");
                        ::quote::__private::push_comma(&mut _s);
                        ::quote::__private::push_colon2(&mut _s);
                        ::quote::__private::push_ident(&mut _s, "core");
                        ::quote::__private::push_colon2(&mut _s);
                        ::quote::__private::push_ident(&mut _s, "file");
                        ::quote::__private::push_bang(&mut _s);
                        ::quote::__private::push_group(&mut _s,
                            ::quote::__private::Delimiter::Parenthesis,
                            ::quote::__private::TokenStream::new());
                        ::quote::__private::push_comma(&mut _s);
                        ::quote::__private::parse(&mut _s, "\"`.\"");
                        _s
                    });
                _s
            });
        ::quote::__private::push_pound(&mut _s);
        ::quote::__private::push_group(&mut _s,
            ::quote::__private::Delimiter::Bracket,
            {
                let mut _s = ::quote::__private::TokenStream::new();
                ::quote::__private::push_ident(&mut _s, "link_name");
                ::quote::__private::push_eq(&mut _s);
                ::quote::ToTokens::to_tokens(&link_name, &mut _s);
                _s
            });
        ::quote::ToTokens::to_tokens(&vis, &mut _s);
        ::quote::__private::push_ident(&mut _s, "fn");
        ::quote::ToTokens::to_tokens(&unchecked_name, &mut _s);
        ::quote::__private::push_group(&mut _s,
            ::quote::__private::Delimiter::Parenthesis,
            {
                let mut _s = ::quote::__private::TokenStream::new();
                ::quote::ToTokens::to_tokens(&inputs, &mut _s);
                _s
            });
        ::quote::ToTokens::to_tokens(&output, &mut _s);
        ::quote::__private::push_semi(&mut _s);
        _s
    })syn::parse_quote! {
2373                        #(#attrs)*
2374                        #[doc = ::core::concat!("Unchecked FFI binding for `", ::core::stringify!(#fn_name), "`.")]
2375                        #[doc = #source_loc_doc_lit]
2376                        #[doc = ::core::concat!("Generated from source file `", ::core::file!(), "`.")]
2377                        #[link_name = #link_name]
2378                        #vis fn #unchecked_name(#inputs) #output;
2379                    };
2380                    unchecked_items.push(unchecked_fn);
2381
2382                    // Generate a checked wrapper function
2383                    let arg_names: Vec<_> = inputs
2384                        .iter()
2385                        .filter_map(|arg| {
2386                            if let syn::FnArg::Typed(pat_type) = arg
2387                                && let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref()
2388                            {
2389                                Some(pat_ident.ident.clone())
2390                            } else {
2391                                None
2392                            }
2393                        })
2394                        .collect();
2395
2396                    let wrapper = {
    let mut _s = ::quote::__private::TokenStream::new();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut attrs, i) = attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let attrs =
                match attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&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(&checked_doc_lit, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&source_loc_doc_lit, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"Generated from source file `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "file");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "inline");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "always");
                    _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::ToTokens::to_tokens(&vis, &mut _s);
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::ToTokens::to_tokens(&fn_name, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&inputs, &mut _s);
            _s
        });
    ::quote::ToTokens::to_tokens(&output, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "with_r_thread");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "move");
                    ::quote::__private::push_or_or(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "unsafe");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&unchecked_name, &mut _s);
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    {
                                        use ::quote::__private::ext::*;
                                        let mut _first = true;
                                        let has_iter = ::quote::__private::HasIterator::<false>;
                                        #[allow(unused_mut)]
                                        let (mut arg_names, i) = arg_names.quote_into_iter();
                                        let has_iter = has_iter | i;
                                        <_ as
                                                ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                                        while true {
                                            let arg_names =
                                                match arg_names.next() {
                                                    Some(_x) => ::quote::__private::RepInterp(_x),
                                                    None => break,
                                                };
                                            if !_first { ::quote::__private::push_comma(&mut _s); }
                                            _first = false;
                                            ::quote::ToTokens::to_tokens(&arg_names, &mut _s);
                                        }
                                    }
                                    _s
                                });
                            _s
                        });
                    _s
                });
            _s
        });
    _s
}quote::quote! {
2397                        #(#attrs)*
2398                        #[doc = #checked_doc_lit]
2399                        #[doc = #source_loc_doc_lit]
2400                        #[doc = ::core::concat!("Generated from source file `", ::core::file!(), "`.")]
2401                        #[inline(always)]
2402                        #[allow(non_snake_case)]
2403                        #vis unsafe fn #fn_name(#inputs) #output {
2404                            ::miniextendr_api::with_r_thread(move || unsafe {
2405                                #unchecked_name(#(#arg_names),*)
2406                            })
2407                        }
2408                    };
2409                    checked_wrappers.push(wrapper);
2410                }
2411            }
2412            _ => {
2413                // Pass through statics and other items unchanged
2414                unchecked_items.push(item.clone());
2415            }
2416        }
2417    }
2418
2419    let expanded = {
    let mut _s = ::quote::__private::TokenStream::new();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut foreign_mod_attrs, i) = foreign_mod_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let foreign_mod_attrs =
                match foreign_mod_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&foreign_mod_attrs, &mut _s);
        }
    }
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::ToTokens::to_tokens(&abi, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            {
                use ::quote::__private::ext::*;
                let has_iter = ::quote::__private::HasIterator::<false>;
                #[allow(unused_mut)]
                let (mut unchecked_items, i) =
                    unchecked_items.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let unchecked_items =
                        match unchecked_items.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    ::quote::ToTokens::to_tokens(&unchecked_items, &mut _s);
                }
            }
            _s
        });
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut checked_wrappers, i) = checked_wrappers.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let checked_wrappers =
                match checked_wrappers.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&checked_wrappers, &mut _s);
        }
    }
    _s
}quote::quote! {
2420        #(#foreign_mod_attrs)*
2421        unsafe #abi {
2422            #(#unchecked_items)*
2423        }
2424
2425        #(#checked_wrappers)*
2426    };
2427
2428    expanded.into()
2429}
2430
2431/// Derive macro for implementing `RNativeType` on a newtype wrapper.
2432///
2433/// This gives newtypes native buffer access, borrowed `&[T]` conversions, and
2434/// participation in the `Coerce<R>` traits. Add `#[derive(IntoR)]` to return
2435/// owned values: `T`, `Vec<T>`, `Box<[T]>`, and their supported nested containers.
2436/// `RNativeType` describes storage; `IntoR` selects the output representation.
2437/// Keeping them separate also permits an `ExternalPtr` representation.
2438/// The inner type must implement `RNativeType`. Add `#[derive(IsNA)]`
2439/// to forward missing-value detection when the inner type supports NA.
2440///
2441/// # Supported Struct Forms
2442///
2443/// Both tuple structs and single-field named structs are supported:
2444///
2445/// ```ignore
2446/// use miniextendr_api::RNativeType;
2447///
2448/// // Tuple struct (most common)
2449/// #[repr(transparent)]
2450/// #[derive(Clone, Copy, RNativeType)]
2451/// struct UserId(i32);
2452///
2453/// // Named single-field struct
2454/// #[repr(transparent)]
2455/// #[derive(Clone, Copy, RNativeType)]
2456/// struct Temperature { celsius: f64 }
2457/// ```
2458///
2459/// # Generated Code
2460///
2461/// For `struct UserId(i32)`, this generates:
2462///
2463/// ```ignore
2464/// impl RNativeType for UserId {
2465///     const SEXP_TYPE: SEXPTYPE = <i32 as RNativeType>::SEXP_TYPE;
2466///     const R_NA: Self = UserId(<i32 as RNativeType>::R_NA);
2467///
2468///     unsafe fn dataptr_mut(sexp: SEXP) -> *mut Self {
2469///         <i32 as RNativeType>::dataptr_mut(sexp).cast()
2470///     }
2471/// }
2472/// ```
2473///
2474/// # Using the Newtype with Coerce
2475///
2476/// Once `RNativeType` is derived, you can implement `Coerce` to/from the newtype:
2477///
2478/// ```ignore
2479/// impl Coerce<UserId> for i32 {
2480///     fn coerce(self) -> UserId { UserId(self) }
2481/// }
2482///
2483/// let id: UserId = 42.coerce();
2484/// ```
2485///
2486/// # Requirements
2487///
2488/// - Must be a newtype struct (exactly one field, tuple or named)
2489/// - Must use `#[repr(transparent)]` so native R buffers have the same layout
2490/// - The inner type must implement `RNativeType` (`i32`, `f64`, `RLogical`, `u8`, `Rcomplex`)
2491/// - Must also be `Copy` (`RNativeType: Copy`): derive `Clone, Copy` with it
2492#[proc_macro_derive(RNativeType)]
2493pub fn derive_rnative_type(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2494    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2495    let name = &input.ident;
2496    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
2497
2498    // Extract inner type and constructor — must be a newtype (single field)
2499    let (inner_ty, elt_ctor): (syn::Type, proc_macro2::TokenStream) = match &input.data {
2500        syn::Data::Struct(data) => match &data.fields {
2501            syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
2502                let ty = fields.unnamed.first().unwrap().ty.clone();
2503                let ctor = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "Self");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "val");
            _s
        });
    _s
}quote::quote! { Self(val) };
2504                (ty, ctor)
2505            }
2506            syn::Fields::Named(fields) if fields.named.len() == 1 => {
2507                let field = fields.named.first().unwrap();
2508                let ty = field.ty.clone();
2509                let field_name = field.ident.as_ref().unwrap();
2510                let ctor = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "Self");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&field_name, &mut _s);
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_ident(&mut _s, "val");
            _s
        });
    _s
}quote::quote! { Self { #field_name: val } };
2511                (ty, ctor)
2512            }
2513            _ => {
2514                return syn::Error::new_spanned(
2515                    name,
2516                    "#[derive(RNativeType)] requires a newtype struct with exactly one field",
2517                )
2518                .into_compile_error()
2519                .into();
2520            }
2521        },
2522        _ => {
2523            return syn::Error::new_spanned(name, "#[derive(RNativeType)] only works on structs")
2524                .into_compile_error()
2525                .into();
2526        }
2527    };
2528
2529    // RNativeType exposes slices of Self over the inner type's R allocation.
2530    // A one-field Rust struct alone does not guarantee the required layout.
2531    let transparent = input
2532        .attrs
2533        .iter()
2534        .filter(|attr| attr.path().is_ident("repr"))
2535        .any(|attr| {
2536            attr.parse_args_with(
2537                syn::punctuated::Punctuated::<syn::Meta, ::syn::token::Commasyn::Token![,]>::parse_terminated,
2538            )
2539            .is_ok_and(|reprs| reprs.iter().any(|repr| repr.path().is_ident("transparent")))
2540        });
2541    if !transparent {
2542        return syn::Error::new_spanned(
2543            name,
2544            "#[derive(RNativeType)] requires #[repr(transparent)] for native R buffer access",
2545        )
2546        .into_compile_error()
2547        .into();
2548    }
2549
2550    let expanded = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "impl");
    ::quote::ToTokens::to_tokens(&impl_generics, &mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "RNativeType");
    ::quote::__private::push_ident(&mut _s, "for");
    ::quote::ToTokens::to_tokens(&name, &mut _s);
    ::quote::ToTokens::to_tokens(&ty_generics, &mut _s);
    ::quote::ToTokens::to_tokens(&where_clause, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "const");
            ::quote::__private::push_ident(&mut _s, "SEXP_TYPE");
            ::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, "SEXPTYPE");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_lt(&mut _s);
            ::quote::ToTokens::to_tokens(&inner_ty, &mut _s);
            ::quote::__private::push_ident(&mut _s, "as");
            ::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, "RNativeType");
            ::quote::__private::push_gt(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP_TYPE");
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "const");
            ::quote::__private::push_ident(&mut _s, "R_NA");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Self");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "let");
                    ::quote::__private::push_ident(&mut _s, "val");
                    ::quote::__private::push_eq(&mut _s);
                    ::quote::__private::push_lt(&mut _s);
                    ::quote::ToTokens::to_tokens(&inner_ty, &mut _s);
                    ::quote::__private::push_ident(&mut _s, "as");
                    ::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, "RNativeType");
                    ::quote::__private::push_gt(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "R_NA");
                    ::quote::__private::push_semi(&mut _s);
                    ::quote::ToTokens::to_tokens(&elt_ctor, &mut _s);
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_pound(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "inline");
                    _s
                });
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_ident(&mut _s, "fn");
            ::quote::__private::push_ident(&mut _s, "dataptr_mut");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "sexp");
                    ::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");
                    _s
                });
            ::quote::__private::push_rarrow(&mut _s);
            ::quote::__private::push_star(&mut _s);
            ::quote::__private::push_ident(&mut _s, "mut");
            ::quote::__private::push_ident(&mut _s, "Self");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "unsafe");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_lt(&mut _s);
                            ::quote::ToTokens::to_tokens(&inner_ty, &mut _s);
                            ::quote::__private::push_ident(&mut _s, "as");
                            ::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, "RNativeType");
                            ::quote::__private::push_gt(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "dataptr_mut");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s, "sexp");
                                    _s
                                });
                            ::quote::__private::push_dot(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "cast");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                ::quote::__private::TokenStream::new());
                            _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, "inline");
                    _s
                });
            ::quote::__private::push_ident(&mut _s, "fn");
            ::quote::__private::push_ident(&mut _s, "elt");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "sexp");
                    ::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, "i");
                    ::quote::__private::push_colon(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "isize");
                    _s
                });
            ::quote::__private::push_rarrow(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Self");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "let");
                    ::quote::__private::push_ident(&mut _s, "val");
                    ::quote::__private::push_eq(&mut _s);
                    ::quote::__private::push_lt(&mut _s);
                    ::quote::ToTokens::to_tokens(&inner_ty, &mut _s);
                    ::quote::__private::push_ident(&mut _s, "as");
                    ::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, "RNativeType");
                    ::quote::__private::push_gt(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "elt");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "sexp");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "i");
                            _s
                        });
                    ::quote::__private::push_semi(&mut _s);
                    ::quote::ToTokens::to_tokens(&elt_ctor, &mut _s);
                    _s
                });
            _s
        });
    _s
}quote::quote! {
2551        impl #impl_generics ::miniextendr_api::RNativeType for #name #ty_generics #where_clause {
2552            const SEXP_TYPE: ::miniextendr_api::SEXPTYPE =
2553                <#inner_ty as ::miniextendr_api::RNativeType>::SEXP_TYPE;
2554
2555            const R_NA: Self = {
2556                let val = <#inner_ty as ::miniextendr_api::RNativeType>::R_NA;
2557                #elt_ctor
2558            };
2559
2560            #[inline]
2561            unsafe fn dataptr_mut(sexp: ::miniextendr_api::SEXP) -> *mut Self {
2562                // Newtype is repr(transparent), so we can cast the pointer
2563                unsafe {
2564                    <#inner_ty as ::miniextendr_api::RNativeType>::dataptr_mut(sexp).cast()
2565                }
2566            }
2567
2568            #[inline]
2569            fn elt(sexp: ::miniextendr_api::SEXP, i: isize) -> Self {
2570                let val = <#inner_ty as ::miniextendr_api::RNativeType>::elt(sexp, i);
2571                #elt_ctor
2572            }
2573        }
2574
2575    };
2576
2577    expanded.into()
2578}
2579
2580/// Derive `IsNA` for a native newtype by forwarding to its single field.
2581///
2582/// Supports tuple, named and generic newtypes that also implement
2583/// `RNativeType`. The inner field must implement `IsNA`; existing where
2584/// clauses are preserved. This derive is separate from `RNativeType`
2585/// because raw `u8` storage has no NA representation.
2586///
2587/// ```
2588/// use miniextendr_api::{IsNA, RNativeType};
2589///
2590/// #[repr(transparent)]
2591/// #[derive(Clone, Copy, RNativeType, IsNA)]
2592/// struct Temperature { celsius: f64 }
2593///
2594/// assert!(Temperature::R_NA.is_na());
2595/// assert!(!Temperature { celsius: f64::NAN }.is_na());
2596/// ```
2597///
2598/// A generic native wrapper supports raw bytes too, but its `IsNA` impl is
2599/// available only when the inner type has NA:
2600///
2601/// ```compile_fail
2602/// use miniextendr_api::{IsNA, RNativeType};
2603///
2604/// #[repr(transparent)]
2605/// #[derive(Clone, Copy, RNativeType, IsNA)]
2606/// struct Native<T: RNativeType>(T);
2607///
2608/// fn requires_na<T: IsNA>() {}
2609/// requires_na::<Native<u8>>();
2610/// ```
2611#[proc_macro_derive(IsNA)]
2612pub fn derive_is_na(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2613    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2614    newtype_derive::derive_is_na(input)
2615        .unwrap_or_else(|e| e.into_compile_error())
2616        .into()
2617}
2618
2619/// Derive macro for implementing `TypedExternal` on a type.
2620///
2621/// This makes the type compatible with `ExternalPtr<T>` for storing in R's external pointers.
2622///
2623/// # Basic Usage
2624///
2625/// ```ignore
2626/// use miniextendr_api::TypedExternal;
2627///
2628/// #[derive(ExternalPtr)]
2629/// struct MyData {
2630///     value: i32,
2631/// }
2632///
2633/// // Now you can use ExternalPtr<MyData>
2634/// let ptr = ExternalPtr::new(MyData { value: 42 });
2635/// ```
2636///
2637/// # Trait ABI
2638///
2639/// Trait dispatch wrappers are automatically generated:
2640///
2641/// ```ignore
2642/// use miniextendr_api::miniextendr;
2643///
2644/// #[derive(ExternalPtr)]
2645/// struct MyCounter {
2646///     value: i32,
2647/// }
2648///
2649/// #[miniextendr]
2650/// impl Counter for MyCounter {
2651///     fn value(&self) -> i32 { self.value }
2652///     fn increment(&mut self) { self.value += 1; }
2653/// }
2654/// ```
2655///
2656/// This generates additional infrastructure for type-erased trait dispatch:
2657/// - Shared runtime `ErasedObject<MyCounter>` storage and destructor
2658/// - `__MX_BASE_VTABLE_MyCounter` - Base vtable with drop/query
2659/// - `__mx_wrap_MyCounter()` - Constructor returning `*mut mx_erased`
2660///
2661/// # Generated Code (Basic)
2662///
2663/// For a type `MyData` without traits:
2664///
2665/// ```ignore
2666/// impl TypedExternal for MyData {
2667///     const TYPE_NAME: &'static str = "MyData";
2668///     const TYPE_NAME_CSTR: &'static [u8] = b"MyData\0";
2669/// }
2670/// ```
2671#[proc_macro_derive(ExternalPtr, attributes(externalptr, r_data))]
2672pub fn derive_external_ptr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2673    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2674
2675    // Standalone `#[derive(ExternalPtr)]` always emits the `IntoExternalPtr`
2676    // marker (enabling the blanket `IntoR`); only the struct-level
2677    // `prefer = "native"` dispatch path suppresses it (#1283).
2678    externalptr_derive::derive_external_ptr(input, true)
2679        .unwrap_or_else(|e| e.into_compile_error())
2680        .into()
2681}
2682
2683/// Derive an `all.equal()` method for the R class of an `ExternalPtr` type,
2684/// comparing the struct field by field (#2149).
2685///
2686/// Without it, `all.equal()` on two objects of a pointer-backed class
2687/// returns `TRUE` whatever they hold: base R compares an external pointer
2688/// only by its `data.class()`. The derived method compares each field with
2689/// base `all.equal()` on the field's R value, so each field keeps its own
2690/// method: numbers keep R's tolerance, lists and data frames use base's
2691/// methods, and a field holding another pointer class `T` uses `T`'s own
2692/// `all.equal()` method (another `AllEqual` type).
2693///
2694/// ```ignore
2695/// #[derive(ExternalPtr, AllEqual)]
2696/// #[all_equal(tolerance = 1e-6)]
2697/// pub struct Fit {
2698///     #[all_equal(label = "Estimates")]
2699///     estimates: Vec<f64>,
2700///     #[all_equal(tolerance = 0)]
2701///     iterations: i32,
2702///     model: ExternalPtr<Model>,
2703///     #[all_equal(skip)]
2704///     cache: RefCell<Option<Vec<f64>>>,
2705/// }
2706///
2707/// #[miniextendr(s3)]
2708/// impl Fit { /* ... */ }
2709/// ```
2710///
2711/// ```r
2712/// all.equal(fit_a, fit_b)                    # TRUE, or c("Estimates: Mean relative difference: 2e-05", ...)
2713/// all.equal(fit_a, fit_b, tolerance = 1e-3)  # the call's tolerance replaces the struct's default
2714/// ```
2715///
2716/// The type also needs `#[derive(ExternalPtr)]` and an impl block with a
2717/// class system (`env`, `r6`, `s3`, `s4` or `s7`): the method is
2718/// `all.equal.<Class>`, registered with `S3method()`, and for S7 also with
2719/// `S7::method(all.equal, Class)`. Installing a package with the derive on a
2720/// type without a class, or with a vctrs class (whose objects are R vectors
2721/// that `all.equal()` already compares), fails with a message naming it.
2722///
2723/// # The comparison
2724///
2725/// The method is `all.equal.<Class>(target, current, tolerance, scale, ...,
2726/// check.attributes, check.names)`, in `all.equal.numeric()`'s argument
2727/// order. A `current` of another class gives base's
2728/// `"target is <class>, current is <class>"`. Otherwise each compared field
2729/// is compared with `all.equal(target_field, current_field, ...)`, and the
2730/// result is `TRUE` or the messages of every differing field, in field
2731/// order, each prefixed as `all.equal.list()` does (`Component “estimates”:
2732/// ...`, `Component 1: ...` for a tuple field) or with the field's `label`.
2733/// An object restored from a saved session (`readRDS()`) is refused with
2734/// the usual `miniextendr_restored_*` error.
2735///
2736/// A field's R value is a clone converted with `IntoR`, or:
2737///
2738/// - `#[all_equal(with = "Self::f")]`: the value of a getter
2739///   `fn(&Self) -> impl IntoR`;
2740/// - a `Computed` field: the value of its `#[r_data(get = "...")]` getter;
2741/// - a `Sidecar<T>` field: its value in the pointer's protection list;
2742/// - an `ExternalPtr<T>` or `Option<ExternalPtr<T>>` field: the pointer
2743///   itself, not a clone.
2744///
2745/// The `RSidecar` selector is not compared.
2746///
2747/// A field whose type names a pointer class `T` of the package (`T`,
2748/// `ExternalPtr<T>`, `Option<ExternalPtr<T>>`, or a `Vec` of `T` or
2749/// `ExternalPtr<T>`) has its value given `T`'s R class, as a method returning that type does, so `T`'s own
2750/// method compares it: give `T` the derive too, since without a method of
2751/// its own `T` is compared by `all.equal.default()`, which finds any two
2752/// pointers equal. The derive can't see a getter's type, so a pointer a
2753/// `with` getter or a `Computed` field returns stays bare, as does a class
2754/// of another package (#2191).
2755///
2756/// # Settings
2757///
2758/// `tolerance`, `scale`, `check_attributes` and `check_names` (the R
2759/// arguments `check.attributes` / `check.names`) are formals of the method.
2760/// Each is passed to a field's `all.equal()` only when something sets it, so
2761/// a field's own method otherwise keeps its default (a nested `AllEqual`
2762/// type its own struct-level settings). Precedence: the field's
2763/// `#[all_equal(...)]`, then the call, then the struct's `#[all_equal(...)]`
2764/// (the formal's default), then the field's own method's default. Other
2765/// arguments of the call are passed on to every field through `...`.
2766///
2767/// On the struct, `#[all_equal(...)]` takes the settings. On a field it
2768/// takes the settings, which the call can't override, and:
2769///
2770/// - `skip`: the field is not compared (alone: it takes no other option);
2771/// - `label = "..."`: the field's messages start with `"<label>: "`;
2772/// - `with = "Self::f"`: the getter whose value is compared.
2773#[proc_macro_derive(AllEqual, attributes(all_equal))]
2774pub fn derive_all_equal(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2775    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2776    all_equal_derive::derive_all_equal(input)
2777        .unwrap_or_else(|e| e.into_compile_error())
2778        .into()
2779}
2780
2781/// Derive macro for ALTREP integer vector data types.
2782///
2783/// Auto-implements `AltrepLen`, `AltIntegerData`, and the low-level ALTREP
2784/// trait impls (`Altrep`, `AltVec`, `AltInteger`, `InferBase`).
2785///
2786/// # Attributes
2787///
2788/// - `#[altrep(len = "field_name")]` - Specify length field (auto-detects "len" or "length")
2789/// - `#[altrep(elt = "field_name")]` - For constant vectors, specify which field provides elements
2790/// - `#[altrep(dataptr)]` - Enable direct data-pointer access
2791/// - `#[altrep(serialize)]` - Enable ALTREP serialization support
2792/// - `#[altrep(subset)]` - Enable `Extract_subset` optimization
2793/// - `#[altrep(no_lowlevel)]` - Skip the automatic low-level trait impls
2794///
2795/// # Example (Constant Vector - Zero Boilerplate!)
2796///
2797/// ```ignore
2798/// #[derive(ExternalPtr, AltrepInteger)]
2799/// #[altrep(elt = "value")]  // All elements return this field
2800/// pub struct ConstantIntData {
2801///     value: i32,
2802///     len: usize,
2803/// }
2804///
2805/// // That's it! 3 lines instead of 30!
2806/// // AltrepLen, AltIntegerData, and low-level impls are auto-generated
2807///
2808/// #[miniextendr(class = "ConstantInt")]
2809/// pub struct ConstantIntClass(pub ConstantIntData);
2810/// ```
2811///
2812/// # Example (Custom elt() - Override One Method)
2813///
2814/// ```ignore
2815/// #[derive(ExternalPtr, AltrepInteger)]
2816/// pub struct ArithSeqData {
2817///     start: i32,
2818///     step: i32,
2819///     len: usize,
2820/// }
2821///
2822/// // Auto-generates AltrepLen and stub AltIntegerData
2823/// // Just override elt() for custom logic:
2824/// impl AltIntegerData for ArithSeqData {
2825///     fn elt(&self, i: usize) -> i32 {
2826///         self.start + (i as i32) * self.step
2827///     }
2828/// }
2829/// ```
2830#[proc_macro_derive(AltrepInteger, attributes(altrep, r_data))]
2831pub fn derive_altrep_integer(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2832    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2833    altrep_derive::derive_altrep_integer(input)
2834        .unwrap_or_else(|e| e.into_compile_error())
2835        .into()
2836}
2837
2838/// Derive macro for ALTREP real vector data types.
2839///
2840/// Auto-implements `AltrepLen` and `AltRealData` traits.
2841/// Supports the same `#[altrep(...)]` attributes as [`AltrepInteger`](derive@AltrepInteger).
2842#[proc_macro_derive(AltrepReal, attributes(altrep, r_data))]
2843pub fn derive_altrep_real(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2844    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2845    altrep_derive::derive_altrep_real(input)
2846        .unwrap_or_else(|e| e.into_compile_error())
2847        .into()
2848}
2849
2850/// Derive macro for ALTREP logical vector data types.
2851///
2852/// Auto-implements `AltrepLen` and `AltLogicalData` traits.
2853/// Supports the same `#[altrep(...)]` attributes as [`AltrepInteger`](derive@AltrepInteger).
2854#[proc_macro_derive(AltrepLogical, attributes(altrep, r_data))]
2855pub fn derive_altrep_logical(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2856    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2857    altrep_derive::derive_altrep_logical(input)
2858        .unwrap_or_else(|e| e.into_compile_error())
2859        .into()
2860}
2861
2862/// Derive macro for ALTREP raw vector data types.
2863///
2864/// Auto-implements `AltrepLen` and `AltRawData` traits.
2865/// Supports the same `#[altrep(...)]` attributes as [`AltrepInteger`](derive@AltrepInteger).
2866#[proc_macro_derive(AltrepRaw, attributes(altrep, r_data))]
2867pub fn derive_altrep_raw(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2868    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2869    altrep_derive::derive_altrep_raw(input)
2870        .unwrap_or_else(|e| e.into_compile_error())
2871        .into()
2872}
2873
2874/// Derive macro for ALTREP string vector data types.
2875///
2876/// Auto-implements `AltrepLen` and `AltStringData` traits.
2877/// Supports the same `#[altrep(...)]` attributes as [`AltrepInteger`](derive@AltrepInteger).
2878#[proc_macro_derive(AltrepString, attributes(altrep, r_data))]
2879pub fn derive_altrep_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2880    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2881    altrep_derive::derive_altrep_string(input)
2882        .unwrap_or_else(|e| e.into_compile_error())
2883        .into()
2884}
2885
2886/// Derive macro for ALTREP complex vector data types.
2887///
2888/// Auto-implements `AltrepLen` and `AltComplexData` traits.
2889/// Supports the same `#[altrep(...)]` attributes as [`AltrepInteger`](derive@AltrepInteger).
2890#[proc_macro_derive(AltrepComplex, attributes(altrep, r_data))]
2891pub fn derive_altrep_complex(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2892    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2893    altrep_derive::derive_altrep_complex(input)
2894        .unwrap_or_else(|e| e.into_compile_error())
2895        .into()
2896}
2897
2898/// Derive macro for ALTREP list vector data types.
2899///
2900/// Auto-implements `AltrepLen` and `AltListData` traits.
2901/// Supports the same `#[altrep(...)]` attributes as [`AltrepInteger`](derive@AltrepInteger),
2902/// except `dataptr` and `subset` which are not supported for list ALTREP.
2903///
2904/// The generated class accepts R's writes (`x[[i]] <- v`): the first one copies
2905/// the elements into a plain list in data2, which element reads use from then on.
2906#[proc_macro_derive(AltrepList, attributes(altrep, r_data))]
2907pub fn derive_altrep_list(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2908    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2909    altrep_derive::derive_altrep_list(input)
2910        .unwrap_or_else(|e| e.into_compile_error())
2911        .into()
2912}
2913
2914/// Derive ALTREP registration for a data struct.
2915///
2916/// Generates `TypedExternal`, `AltrepClass`, `RegisterAltrep`, `IntoR`,
2917/// linkme registration entry, and `Ref`/`Mut` accessor types.
2918///
2919/// The struct must already have low-level ALTREP traits implemented.
2920/// For most use cases, prefer a family-specific derive:
2921/// `#[derive(AltrepInteger)]`, `#[derive(AltrepReal)]`, etc.
2922/// Use `#[altrep(manual)]` on a family derive to skip data trait generation
2923/// when you provide your own `AltrepLen` + `Alt*Data` impls.
2924///
2925/// # Attributes
2926///
2927/// - `#[altrep(class = "Name")]` — custom ALTREP class name (defaults to struct name)
2928///
2929/// # Example
2930///
2931/// ```ignore
2932/// // Prefer family derives with manual:
2933/// #[derive(AltrepInteger)]
2934/// #[altrep(manual, class = "MyCustom", serialize)]
2935/// struct MyData { ... }
2936///
2937/// impl AltrepLen for MyData { ... }
2938/// impl AltIntegerData for MyData { ... }
2939/// ```
2940#[proc_macro_derive(Altrep, attributes(altrep, r_data))]
2941pub fn derive_altrep(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2942    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2943    altrep::derive_altrep(input)
2944        .unwrap_or_else(|e| e.into_compile_error())
2945        .into()
2946}
2947
2948/// Derive `IntoList` for a struct (Rust → R list).
2949///
2950/// - Named structs → named R list: `list(x = 1L, y = 2L)`
2951/// - Tuple structs → unnamed R list: `list(1L, 2L)`
2952/// - Fields annotated `#[into_list(ignore)]` are skipped
2953/// - `#[into_list(class = "a")]` / `#[into_list(class = ["a", "b"])]` on the
2954///   struct sets the list's `class` attribute to exactly those classes
2955#[proc_macro_derive(IntoList, attributes(into_list))]
2956pub fn derive_into_list(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2957    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2958    list_derive::derive_into_list(input)
2959        .unwrap_or_else(|e| e.into_compile_error())
2960        .into()
2961}
2962
2963/// Derive `TryFromList` for a struct (R list → Rust).
2964///
2965/// - Named structs: extract by field name. A field whose name appears more
2966///   than once in the list is an error (`SexpError::DuplicateName`), since the
2967///   struct could keep only one of the values; other names, repeated or not,
2968///   are ignored.
2969/// - Tuple structs: extract by position (0, 1, 2, ...)
2970/// - Fields annotated `#[into_list(ignore)]` are not read and are initialized with
2971///   `Default::default()`, so their types must be `Default`
2972/// - The list's class is not checked, `#[into_list(class = ...)]` included
2973#[proc_macro_derive(TryFromList, attributes(into_list))]
2974pub fn derive_try_from_list(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2975    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
2976    list_derive::derive_try_from_list(input)
2977        .unwrap_or_else(|e| e.into_compile_error())
2978        .into()
2979}
2980
2981/// Derive `PreferList`: emits an `IntoR` impl selecting list as the type's default
2982/// Rust→R conversion (via `IntoList::into_list`).
2983///
2984/// A type carries exactly one representation default: stacking two `Prefer*`
2985/// derives is a compile error. Each `Prefer*` derive emits a fixed-name marker
2986/// const, so a second one triggers a guided `duplicate definitions with name
2987/// __miniextendr_conflicting_Prefer_derives__keep_ONE_or_use_call_site_As_wrappers`
2988/// error (alongside the raw conflicting-`IntoR`-impl error) — keep one `Prefer*`,
2989/// or drop them all and choose a representation per return value at the call site
2990/// with an `As*` wrapper (`AsList`, `AsExternalPtr`, `AsDataFrame`, ...).
2991///
2992/// # Example
2993///
2994/// ```ignore
2995/// #[derive(IntoList, PreferList)]
2996/// struct Config { verbose: bool, threads: i32 }
2997/// // IntoR produces list(verbose = TRUE, threads = 4L)
2998/// ```
2999#[proc_macro_derive(PreferList)]
3000pub fn derive_prefer_list(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3001    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
3002    list_derive::derive_prefer_list(input)
3003        .unwrap_or_else(|e| e.into_compile_error())
3004        .into()
3005}
3006
3007/// Derive `PreferExternalPtr`: return a type with a hand-written `TypedExternal`
3008/// implementation as an R external pointer. `#[derive(ExternalPtr)]` already
3009/// supplies `IntoR`; adding this derive to it creates conflicting implementations.
3010///
3011/// # Example
3012///
3013/// ```ignore
3014/// #[derive(PreferExternalPtr)]
3015/// struct Model { weights: Vec<f64> }
3016///
3017/// impl miniextendr_api::TypedExternal for Model {
3018///     const TYPE_NAME: &'static str = "Model";
3019///     const TYPE_NAME_CSTR: &'static [u8] = b"Model\0";
3020///     const TYPE_ID_CSTR: &'static [u8] = concat!(module_path!(), "::Model\0").as_bytes();
3021/// }
3022/// ```
3023#[proc_macro_derive(PreferExternalPtr)]
3024pub fn derive_prefer_externalptr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3025    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
3026    list_derive::derive_prefer_externalptr(input)
3027        .unwrap_or_else(|e| e.into_compile_error())
3028        .into()
3029}
3030
3031/// Derive `PreferRNativeType`: when a newtype wraps an `RNativeType` and also
3032/// implements other conversions, this selects the native R vector conversion
3033/// as the default `IntoR` path.
3034///
3035/// # Example
3036///
3037/// ```ignore
3038/// #[repr(transparent)]
3039/// #[derive(Copy, Clone, RNativeType, PreferRNativeType)]
3040/// struct Meters(f64);
3041/// // IntoR produces a numeric scalar, not an ExternalPtr
3042/// ```
3043#[proc_macro_derive(PreferRNativeType)]
3044pub fn derive_prefer_rnative(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3045    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
3046    list_derive::derive_prefer_rnative(input)
3047        .unwrap_or_else(|e| e.into_compile_error())
3048        .into()
3049}
3050
3051/// Derive `PreferVctrs`: emits an `IntoR` impl converting the type to its R vctrs object via
3052/// `IntoVctrs::into_vctrs`.
3053///
3054/// Pair with `#[derive(Vctrs)]` (which supplies `IntoVctrs`) so the type can be returned
3055/// directly from `#[miniextendr]` functions instead of `value.into_vctrs().map_err(...)`.
3056///
3057/// # Example
3058///
3059/// ```ignore
3060/// #[derive(Vctrs, PreferVctrs)]
3061/// #[vctrs(class = "percent", base = "double")]
3062/// struct Percent { #[vctrs(data)] values: Vec<f64> }
3063/// // IntoR builds the `percent` vctrs vector; a build failure becomes an R error.
3064/// ```
3065#[cfg(feature = "vctrs")]
3066#[proc_macro_derive(PreferVctrs)]
3067pub fn derive_prefer_vctrs(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3068    let input = syn::parse_macro_input!(input as syn::DeriveInput);
3069    list_derive::derive_prefer_vctrs(input)
3070        .unwrap_or_else(|e| e.into_compile_error())
3071        .into()
3072}
3073
3074/// Derive `DataFrameRow`: generates a companion `*DataFrame` type with collection fields,
3075/// plus `IntoR` / `TryFromSexp` / `IntoDataFrame` impls for seamless R data.frame conversion.
3076///
3077/// # Example
3078///
3079/// ```ignore
3080/// #[derive(DataFrameRow)]
3081/// struct Measurement {
3082///     time: f64,
3083///     value: f64,
3084/// }
3085///
3086/// // Generates MeasurementDataFrame { time: Vec<f64>, value: Vec<f64> }
3087/// // plus conversion impls
3088/// ```
3089///
3090/// # Struct-level attributes
3091///
3092/// - `#[dataframe(name = "CustomDf")]` — custom name for the generated DataFrame type
3093/// - `#[dataframe(align)]` — pad shorter columns with NA to match longest
3094/// - `#[dataframe(tag = "my_tag")]` — attach a tag attribute to the data.frame
3095/// - `#[dataframe(conflicts = "string")]` — resolve conflicting column types as strings
3096///
3097/// # Field-level attributes
3098///
3099/// - `#[dataframe(skip)]` — omit this field from the DataFrame
3100/// - `#[dataframe(rename = "col")]` — custom column name
3101/// - `#[dataframe(as_list)]` — keep collection as single list column (no expansion)
3102/// - `#[dataframe(expand)]` / `#[dataframe(unnest)]` — expand collection into suffixed columns
3103/// - `#[dataframe(width = N)]` — pin expansion width (shorter rows get NA)
3104///
3105/// # Requirements
3106///
3107/// Of each field type the derive asks only what turning that field into
3108/// columns needs, and a missing impl is reported at the field:
3109///
3110/// - a scalar or opaque column: its column converts to R (`Vec<T>: IntoR`;
3111///   in an enum, `Vec<Option<T>>`);
3112/// - `[T; N]`, or `width` / `expand` over an owned `Vec<T>` / `Box<[T]>`:
3113///   `T`'s columns convert to R; the elements are moved, so `T` needs no
3114///   `Clone` or `Copy`. Over a borrowed `&[T; N]` / `&[T]`, `T` must also be
3115///   `Clone`;
3116/// - a flattened struct or nested enum: `#[derive(DataFrameRow)]`;
3117/// - `as_factor`: `UnitEnumFactor`, which `#[derive(DataFrameRow)]` on a
3118///   unit-only enum and `#[derive(RFactor)]` both provide;
3119/// - `as_list`: `IntoList`;
3120/// - `skip`: nothing.
3121///
3122/// Everything else is generated only where the field types allow it. The
3123/// companion is `Debug` / `Clone` when every column type is. A struct
3124/// companion iterates its rows when every `skip` field's type is `Default`
3125/// (they are rebuilt with `Default::default()`). With `rayon`,
3126/// `from_rows_par` fills the columns in parallel when the rows and column
3127/// values are `Send`, placeholder-filled struct columns are `Default`, and
3128/// flattened / `as_list` values are `Clone`; otherwise it fills them
3129/// sequentially.
3130///
3131/// # Public surface (which verbs to call)
3132///
3133/// Every capability the derive provides has a documented, trait-based (or `std`)
3134/// verb — reach for these, not any incidental inherent plumbing:
3135///
3136/// - **Rows → R `data.frame`**: `rows.into_dataframe()?` (owned, GC-rooted
3137///   `BuiltDataFrame`) or `rows.wrap_data_frame()` (deferred `IntoR` wrapper);
3138///   parallel variant `rows.into_dataframe_par()?`. From the `IntoDataFrame` /
3139///   `AsDataFrameExt` traits (both re-exported from `miniextendr_api::prelude`).
3140/// - **R `data.frame` → rows**: `Vec::<Row>::from_dataframe(&df)?` (parallel:
3141///   `Vec::<Row>::from_dataframe_par(&df)?`), from the `FromDataFrame` trait — or
3142///   the one-call `Row::try_from_dataframe(sexp)` reader on the row type.
3143/// - **Rows ↔ the pure-Rust columnar companion** (`<Row>DataFrame`, `Vec`-columns,
3144///   no R involved): the `ColumnarFrame` trait (in the prelude) —
3145///   `<Row>DataFrame::from_rows(rows)` / `from_rows_par(rows)` (parallel build of
3146///   the *companion*, which `into_dataframe_par` does not give you) and, for
3147///   row-iterable companions, `companion.into_rows()`. `Vec<Row>: Into<companion>`
3148///   and the companion's `IntoIterator` are the equivalent `std` verbs.
3149/// - **Enum split representation**: `rows.into_dataframe_split()` returns one
3150///   `data.frame` per variant (only that variant's columns — no NA fill) as a
3151///   GC-rooted `DataFrameShape` — `Bare` for a single-variant enum,
3152///   `PerVariantList` (an R named list) otherwise — from the
3153///   `IntoDataFrameSplit` trait (in the prelude). Enum rows only; struct
3154///   derives don't partition.
3155///
3156/// The generated `<Row>DataFrame` / `<Row>DataFrameIter` types are intermediate
3157/// column-oriented companions; you rarely name them directly.
3158#[proc_macro_derive(DataFrameRow, attributes(dataframe))]
3159pub fn derive_dataframe_row(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3160    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
3161    dataframe_derive::derive_dataframe_row(input)
3162        .unwrap_or_else(|e| e.into_compile_error())
3163        .into()
3164}
3165
3166/// Derive `RFactor`: enables conversion between Rust enums and R factors.
3167///
3168/// # Usage
3169///
3170/// ```ignore
3171/// #[derive(Copy, Clone, RFactor)]
3172/// enum Color {
3173///     Red,
3174///     Green,
3175///     Blue,
3176/// }
3177/// ```
3178///
3179/// # Attributes
3180///
3181/// - `#[r_factor(rename = "name")]` - Rename a variant's level string
3182/// - `#[r_factor(rename_all = "snake_case")]` - Rename all variants (snake_case, kebab-case, lower, upper)
3183///
3184/// # Requirements
3185///
3186/// The enum must be `Copy` (`RFactor` and its supertrait `MatchArg` require it):
3187/// derive `Copy, Clone` with it.
3188#[proc_macro_derive(RFactor, attributes(r_factor))]
3189pub fn derive_r_factor(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3190    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
3191    factor_derive::derive_r_factor(input)
3192        .unwrap_or_else(|e| e.into_compile_error())
3193        .into()
3194}
3195
3196/// Derive `MatchArg`: enables conversion between Rust enums and R character strings
3197/// with `match.arg` semantics (partial matching, informative errors).
3198///
3199/// # Usage
3200///
3201/// ```ignore
3202/// #[derive(Copy, Clone, MatchArg)]
3203/// enum Mode {
3204///     Fast,
3205///     Safe,
3206///     Debug,
3207/// }
3208/// ```
3209///
3210/// # Attributes
3211///
3212/// - `#[match_arg(rename = "name")]` - Rename a variant's choice string
3213/// - `#[match_arg(rename_all = "snake_case")]` - Rename all variants (snake_case, kebab-case, lower, upper)
3214/// - `#[match_arg(alias = "name")]` - Another spelling of a variant's choice, matched when typed
3215///   in full; the errors that list the choices name it after them (`(or "name" for "choice")`)
3216/// - `#[match_arg(alias = "name", listed = false)]` - The same, named by no error
3217///
3218/// # Requirements
3219///
3220/// The enum must be `Copy` (`MatchArg: Copy`): derive `Copy, Clone` with it.
3221///
3222/// # Generated Implementations
3223///
3224/// - `MatchArg` - Choice metadata and bidirectional conversion
3225/// - `TryFromSexp` - Convert R STRSXP/factor to enum (with partial matching)
3226/// - `IntoR` - Convert enum to R character scalar
3227#[proc_macro_derive(MatchArg, attributes(match_arg))]
3228pub fn derive_match_arg(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3229    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
3230    match_arg_derive::derive_match_arg(input)
3231        .unwrap_or_else(|e| e.into_compile_error())
3232        .into()
3233}
3234
3235/// Derive an R condition type for a struct or enum: `RConditionData` (the R
3236/// class vector, the message and the `data` fields handlers read as
3237/// `e$<name>`) and `From<Self>` for `miniextendr_api::RCondition`.
3238///
3239/// - `#[condition(class = "…")]` on the type sets the family class (default:
3240///   the type name in snake_case); on an enum variant it sets the member class
3241///   (default: `<family>_<variant in snake_case>`). Variants report
3242///   `c(<member>, <family>)`, structs `c(<family>)`.
3243/// - `#[condition(message = "…")]` on a struct or a variant is a `format!`
3244///   string over the fields (tuple fields are `_0`, `_1`, …). Without it the
3245///   message is the type's `Display` rendering.
3246/// - Every field becomes a `data` entry under its own name, converted with
3247///   `RValue::from(field.clone())`, so its type must be `Clone`.
3248///   `#[condition(rename = "…")]`,
3249///   `#[condition(skip)]` and `#[condition(debug)]` (attach the `Debug`
3250///   rendering instead) adjust that; tuple fields need `rename` or `skip`. The
3251///   reserved slots `message`, `call` and `kind` are rejected at compile time.
3252/// - `#[condition(kind = error | warning | message | condition)]` on the type
3253///   or a variant (the variant wins) is the kind `RCondition::from(value)`
3254///   gives it; the default is `error`. Then `.defer()` signals it after the
3255///   function returns its value, and `.raise()` signals it now.
3256///
3257/// The kind is read only through `RCondition::from`. Returned as `Err(value)`
3258/// from a `Result<T, E>`, the value is always an R error, and
3259/// [`defer_warning`](https://docs.rs/miniextendr-api) / `defer_message` signal
3260/// the kind they are named after. Generic types are not supported.
3261#[proc_macro_derive(RCondition, attributes(condition))]
3262pub fn derive_r_condition(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3263    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
3264    condition_derive::derive_r_condition(input)
3265        .unwrap_or_else(|e| e.into_compile_error())
3266        .into()
3267}
3268
3269/// Derive `TryFromSexp` for a single-field newtype: forward the R → Rust
3270/// conversion to the inner type.
3271///
3272/// Generates a scalar `TryFromSexp` impl that delegates to the inner type (so the
3273/// newtype inherits its exact SEXPTYPE checks, NA policy, and error text), plus a
3274/// `TryFromSexpElement` marker impl. The marker lets `miniextendr-api`'s container
3275/// blankets light up `Vec<T>` / `Option<T>` / `Vec<Option<T>>` automatically,
3276/// each one where the inner type's container converts.
3277///
3278/// Don't use it on a type that also gets `try_from_sexp_via_str_parse!`: both
3279/// implement `TryFromSexpElement`.
3280///
3281/// # Usage
3282///
3283/// ```ignore
3284/// use uuid::Uuid;
3285///
3286/// #[derive(TryFromSexp)]            // R -> Rust only
3287/// struct Pattern(regex::Regex);
3288///
3289/// #[derive(TryFromSexp, IntoR)]     // round-trip; Vec/Option containers work too
3290/// struct UserId(Uuid);
3291/// ```
3292///
3293/// Direction is chosen by which derive you list — derive only `TryFromSexp` for
3294/// inner types that read from R but cannot be written back (e.g. `regex::Regex`).
3295///
3296/// # Refusing values: `#[try_from_sexp(validate = path)]`
3297///
3298/// The containers read the inner type and wrap it; they never run the
3299/// newtype's own `try_from_sexp`. To refuse a value the inner type accepts,
3300/// name a check, `fn(SEXP) -> Result<(), E>` with `E: Into<SexpError>`. It
3301/// becomes `TryFromSexpElement::check_sexp`, which runs on the R value before
3302/// it is read, in every shape: the scalar, on any input but `NULL` for
3303/// `Option<T>`, and for `Vec<T>` and `Vec<Option<T>>` once on the whole vector
3304/// of an atomic inner type, or on each element (but `NULL`) of a list when the
3305/// inner type is `List` (a list of R objects, each with its own class).
3306///
3307/// ```ignore
3308/// use miniextendr_api::condition::RError;
3309/// use miniextendr_api::{SEXP, SexpExt, TryFromSexp};
3310///
3311/// fn plain_number(x: SEXP) -> Result<(), RError> {
3312///     if x.inherits_class(c"difftime") {
3313///         return Err(RError::new("give the duration as a plain number").class("pkg_unit_error"));
3314///     }
3315///     Ok(())
3316/// }
3317///
3318/// #[derive(TryFromSexp)]
3319/// #[try_from_sexp(validate = plain_number)]
3320/// struct Duration(f64);
3321/// ```
3322///
3323/// An `RError` refusal (or one of any `RConditionData` type) keeps its classes
3324/// and fields on the argument error, before the crate's
3325/// `conversion_error_class`, with `e$param` and the message
3326/// `'<p>' must be <expected>: <message>`. With `validate`, the newtype's
3327/// scalar error is `SexpError`, so the inner type's error must convert into it,
3328/// as every built-in conversion error and every `RConditionData` type does.
3329/// `validate` is the only key, and the attribute goes on the struct.
3330#[proc_macro_derive(TryFromSexp, attributes(try_from_sexp))]
3331pub fn derive_try_from_sexp(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3332    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
3333    newtype_derive::derive_try_from_sexp(input)
3334        .unwrap_or_else(|e| e.into_compile_error())
3335        .into()
3336}
3337
3338/// Derive `IntoR` for a single-field newtype: forward the Rust → R conversion to
3339/// the inner type.
3340///
3341/// Generates a scalar `IntoR` impl that delegates to the inner type, plus an
3342/// `IntoRNewtype` marker (powering the `Option<T>` / `Vec<Option<T>>` container
3343/// blankets) and a concrete `IntoRVecElement` impl (powering `Vec<T>`). See
3344/// `#[derive(TryFromSexp)]` for usage.
3345///
3346/// Do not derive both `IntoR` and `MatchArg` on the same type: both feed the
3347/// single `IntoR for Vec<T>` blanket slot and would collide (E0119).
3348#[proc_macro_derive(IntoR)]
3349pub fn derive_into_r(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3350    let input = match ::syn::parse::<syn::DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::DeriveInput);
3351    newtype_derive::derive_into_r(input)
3352        .unwrap_or_else(|e| e.into_compile_error())
3353        .into()
3354}
3355
3356/// Derive `Vctrs`: enables creating vctrs-compatible S3 vector classes from Rust structs.
3357///
3358/// # Usage
3359///
3360/// ```ignore
3361/// #[derive(Vctrs)]
3362/// #[vctrs(class = "percent", base = "double")]
3363/// pub struct Percent {
3364///     data: Vec<f64>,
3365/// }
3366/// ```
3367///
3368/// # Attributes
3369///
3370/// - `#[vctrs(class = "name")]` - R class name (required)
3371/// - `#[vctrs(base = "type")]` - Base type: double, integer, logical, character, raw, list, record
3372/// - `#[vctrs(abbr = "abbr")]` - Abbreviation for `vec_ptype_abbr`
3373/// - `#[vctrs(inherit_base = true|false)]` - Whether to include base type in class vector
3374///
3375/// # Generated Implementations
3376///
3377/// - `VctrsClass` - Metadata trait for vctrs class information
3378/// - `VctrsRecord` (for `base = "record"`) - Field names for record types
3379#[cfg(feature = "vctrs")]
3380#[proc_macro_derive(Vctrs, attributes(vctrs))]
3381pub fn derive_vctrs(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3382    let input = syn::parse_macro_input!(input as syn::DeriveInput);
3383    vctrs_derive::derive_vctrs(input)
3384        .unwrap_or_else(|e| e.into_compile_error())
3385        .into()
3386}
3387
3388/// Create a `TypedListSpec` for validating `...` arguments or lists.
3389///
3390/// This macro provides ergonomic syntax for defining typed list specifications
3391/// that can be used with `Dots::typed()` to validate the structure of
3392/// `...` arguments passed from R.
3393///
3394/// # Syntax
3395///
3396/// ```text
3397/// typed_list!(
3398///     name => type_spec,    // required field with type
3399///     name? => type_spec,   // optional field with type
3400///     name,                 // required field, any type
3401///     name?,                // optional field, any type
3402/// )
3403/// ```
3404///
3405/// For strict mode (no extra fields allowed):
3406/// ```text
3407/// typed_list!(@exact; name => type_spec, ...)
3408/// ```
3409///
3410/// # Type Specifications
3411///
3412/// ## Base types (with optional length)
3413/// - `numeric()` / `numeric(4)` - Real/double vector
3414/// - `integer()` / `integer(4)` - Integer vector
3415/// - `logical()` / `logical(4)` - Logical vector
3416/// - `character()` / `character(4)` - Character vector
3417/// - `raw()` / `raw(4)` - Raw vector
3418/// - `complex()` / `complex(4)` - Complex vector
3419/// - `list()` / `list(4)` - List (VECSXP)
3420///
3421/// ## Special types
3422/// - `data_frame()` - Data frame
3423/// - `factor()` - Factor
3424/// - `matrix()` - Matrix
3425/// - `array()` - Array
3426/// - `function()` - Function
3427/// - `environment()` - Environment
3428/// - `null()` - NULL only
3429/// - `any()` - Any type
3430///
3431/// ## String literals
3432/// - `"numeric"`, `"integer"`, etc. - Same as call syntax
3433/// - `"data.frame"` - Data frame (alias)
3434/// - `"MyClass"` - Any other string is treated as a class name (uses `Rf_inherits`)
3435///
3436/// # Examples
3437///
3438/// ## Basic usage
3439///
3440/// ```ignore
3441/// use miniextendr_api::{miniextendr, typed_list, Dots};
3442///
3443/// #[miniextendr]
3444/// pub fn process_args(dots: ...) -> Result<i32, String> {
3445///     let args = dots.typed(typed_list!(
3446///         alpha => numeric(4),
3447///         beta => list(),
3448///         gamma? => "character",
3449///     )).map_err(|e| e.to_string())?;
3450///
3451///     let alpha: Vec<f64> = args.get("alpha").map_err(|e| e.to_string())?;
3452///     Ok(alpha.len() as i32)
3453/// }
3454/// ```
3455///
3456/// ## Strict mode
3457///
3458/// ```ignore
3459/// // Reject any extra named fields
3460/// let args = dots.typed(typed_list!(@exact;
3461///     x => numeric(),
3462///     y => numeric(),
3463/// ))?;
3464/// ```
3465///
3466/// ## Class checking
3467///
3468/// ```ignore
3469/// // Check for specific R class (uses Rf_inherits semantics)
3470/// let args = dots.typed(typed_list!(
3471///     data => "data.frame",
3472///     model => "lm",
3473/// ))?;
3474/// ```
3475///
3476/// ## Attribute sugar
3477///
3478/// Instead of calling `.typed()` manually, you can use `typed_list!` directly in the
3479/// `#[miniextendr]` attribute for automatic validation:
3480///
3481/// ```ignore
3482/// #[miniextendr(dots = typed_list!(x => numeric(), y => numeric()))]
3483/// pub fn my_func(_: ...) -> String {
3484///     // `dots_typed` is automatically created and validated
3485///     let x: f64 = dots_typed.get("x").expect("x");
3486///     let y: f64 = dots_typed.get("y").expect("y");
3487///     format!("x={}, y={}", x, y)
3488/// }
3489/// ```
3490///
3491/// This injects validation at the start of the function body, reading the
3492/// dots binding (`__miniextendr_dots` for `_: ...`, otherwise the name of the
3493/// `name: ...` / `name: &Dots` parameter):
3494/// ```ignore
3495/// let dots_typed = __miniextendr_dots.typed(typed_list!(...))
3496///     .unwrap_or_else(|e| miniextendr_api::arg_error!(
3497///         param = "...", "dots validation failed: {e}"
3498///     ));
3499/// ```
3500///
3501/// See the [`#[miniextendr]`](macro@miniextendr) attribute documentation for more details.
3502///
3503#[proc_macro]
3504pub fn typed_list(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3505    let parsed = match ::syn::parse::<typed_list::TypedListInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as typed_list::TypedListInput);
3506    typed_list::expand_typed_list(parsed).into()
3507}
3508
3509/// Define a compile-time-validated wrapper for an R `data.frame` input.
3510///
3511/// `typed_dataframe!` mirrors [`typed_list!`] for the data.frame shape:
3512/// declare the columns once, get a struct that implements `TryFromSexp`
3513/// (validating both the `data.frame` class and per-column SEXPTYPE) plus
3514/// per-column borrowed accessors that return `&[T]`.
3515///
3516/// # Syntax
3517///
3518/// ```ignore
3519/// typed_dataframe! {
3520///     /// The shape we accept for the Theoph PK dataset.
3521///     pub TheophDf {
3522///         subject: i32,
3523///         weight: f64,
3524///         dose: f64,
3525///         flag: Option<i32>,   // optional column
3526///     }
3527/// }
3528/// ```
3529///
3530/// For strict mode (reject any column not declared):
3531/// ```ignore
3532/// typed_dataframe! {
3533///     @exact;
3534///     pub Strict { x: i32 }
3535/// }
3536/// ```
3537///
3538/// # Supported element types
3539///
3540/// v1 supports column element types that implement
3541/// `miniextendr_api::RNativeType`:
3542///
3543/// - `i32` — `INTSXP`
3544/// - `f64` — `REALSXP`
3545/// - `u8` — `RAWSXP`
3546/// - `miniextendr_api::RLogical` — `LGLSXP`
3547/// - `miniextendr_api::Rcomplex` — `CPLXSXP`
3548///
3549/// `String`/`&str` column types are not yet supported (character vectors
3550/// don't expose a contiguous slice). `bool` is also not yet supported as
3551/// a direct field type — use `RLogical` and convert per-element, or
3552/// follow the open follow-up issues from PR #698.
3553///
3554/// # Generated API
3555///
3556/// For each `name: T` column the macro emits:
3557/// - `pub fn name(&self) -> &[T]` (required)
3558/// - `pub fn name(&self) -> Option<&[T]>` (optional, `Option<T>`)
3559///
3560/// Plus housekeeping:
3561/// - `pub fn nrow(&self) -> usize`
3562/// - `pub fn ncol(&self) -> usize` (count of *declared* columns)
3563/// - `pub fn as_sexp(&self) -> SEXP`
3564///
3565/// All borrowed accessors are bound to `&self`; the SEXP is protected
3566/// by the surrounding `#[miniextendr]` call wrapper while the struct is
3567/// alive.
3568///
3569/// # Error reporting
3570///
3571/// `TryFromSexp::try_from_sexp` batches every per-column error into a
3572/// single `SexpError::InvalidValue`, so the R user sees one diagnostic
3573/// covering all missing or wrong-typed columns rather than a sequence of
3574/// stop-on-first-failure messages.
3575///
3576/// # Example
3577///
3578/// ```ignore
3579/// use miniextendr_api::{miniextendr, typed_dataframe};
3580///
3581/// typed_dataframe! {
3582///     pub TheophDf {
3583///         subject: i32,
3584///         weight: f64,
3585///         dose: f64,
3586///     }
3587/// }
3588///
3589/// #[miniextendr]
3590/// pub fn theoph_nrow(df: TheophDf) -> i32 {
3591///     // df.subject() -> &[i32], df.weight() -> &[f64]
3592///     // Lengths are guaranteed equal across columns (data.frame invariant).
3593///     df.nrow() as i32
3594/// }
3595/// ```
3596///
3597/// [`typed_list!`]: macro@typed_list
3598#[proc_macro]
3599pub fn typed_dataframe(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3600    let parsed = match ::syn::parse::<typed_dataframe::TypedDataframeInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as typed_dataframe::TypedDataframeInput);
3601    typed_dataframe::expand_typed_dataframe(parsed).into()
3602}
3603
3604/// Construct an R list from Rust values.
3605///
3606/// This macro provides a convenient way to create R lists in Rust code,
3607/// using R-like syntax. Values are converted to R objects via the [`IntoR`] trait.
3608///
3609/// # Syntax
3610///
3611/// ```ignore
3612/// // Named entries (like R's list())
3613/// list!(
3614///     alpha = 1,
3615///     beta = "hello",
3616///     "my-name" = vec![1, 2, 3],
3617/// )
3618///
3619/// // Unnamed entries
3620/// list!(1, "hello", vec![1, 2, 3])
3621///
3622/// // Mixed (unnamed entries get empty string names)
3623/// list!(alpha = 1, 2, beta = "hello")
3624///
3625/// // Empty list
3626/// list!()
3627/// ```
3628///
3629/// # Examples
3630///
3631/// ```ignore
3632/// use miniextendr_api::{list, IntoR};
3633///
3634/// // Create a named list
3635/// let my_list = list!(
3636///     x = 42,
3637///     y = "hello world",
3638///     z = vec![1.0, 2.0, 3.0],
3639/// );
3640///
3641/// // In R this is equivalent to:
3642/// // list(x = 42L, y = "hello world", z = c(1, 2, 3))
3643/// ```
3644///
3645/// [`IntoR`]: https://docs.rs/miniextendr-api/latest/miniextendr_api/into_r/trait.IntoR.html
3646#[proc_macro]
3647pub fn list(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3648    let parsed = match ::syn::parse::<list_macro::ListInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as list_macro::ListInput);
3649    list_macro::expand_list(parsed).into()
3650}
3651
3652/// Evaluate R code written as **Rust tokens**, validated at compile time.
3653///
3654/// `r!` takes a single R expression as a token stream, `stringify!`s it into a
3655/// static R source string at build time, and evaluates it via
3656/// `miniextendr_api::expression::r_eval_str` (the same protect-safe parse + eval
3657/// path as `r_str!`).
3658///
3659/// # What you get today
3660///
3661/// Because the argument is a Rust token tree, the Rust front-end already
3662/// rejects **unbalanced delimiters** (`r!(f(1, 2)` won't compile) and
3663/// lexically invalid tokens before R ever sees the string — a cheap
3664/// compile-time guard over the pure-runtime `r_str!`. The source is lowered to
3665/// a `&'static str` (`stringify!`), so there is no `format!` allocation at the
3666/// call site.
3667///
3668/// This proc-macro additionally validates a conservative subset of known-bad
3669/// R syntax constructs (trailing binary operators, consecutive non-unary
3670/// binary operators, bare `if`/`while`/`for` without a body, etc.) and emits
3671/// a precise compile error pointing at the offending token. Empty (missing)
3672/// call arguments — `f(, x)`, `matrix(, 2, 2)` — are valid R and pass.
3673///
3674/// # What is deferred
3675///
3676/// Direct `Rf_lang*` call-tree lowering (skipping the runtime parser entirely)
3677/// is tracked as a follow-up in issue #938 (item 2). Until then `r!` parses
3678/// its static string at first evaluation, exactly like `r_str!`.
3679///
3680/// # Non-goals
3681///
3682/// A complete R grammar validator is not achievable over Rust tokens:
3683/// - Single-quoted strings (`'hello'`) and backtick-quoted names (`` `foo` ``)
3684///   already die at the Rust lexer — nothing to validate.
3685/// - `%op%` tokenises as `%`, ident, `%` and is accepted without analysis.
3686/// - Anything the validator cannot confidently classify as wrong passes through
3687///   unvalidated (conservative reject-only-known-bad design).
3688///
3689/// # Forms
3690///
3691/// - `r!(R tokens…)` — evaluate in `R_GlobalEnv`.
3692/// - `r!(env: e; R tokens…)` — evaluate in the environment SEXP `e`. The
3693///   leading `env: <expr> ;` is consumed as Rust, the rest is R source.
3694///
3695/// Both evaluate to `Result<SEXP, REvalError>`; the `SEXP` is **unprotected**.
3696///
3697/// # Safety
3698///
3699/// Expands to an `unsafe` block; the underlying FFI is `#[r_ffi_checked]`, so
3700/// a call off R's main thread panics before it reaches R.
3701///
3702/// # Example
3703///
3704/// ```ignore
3705/// let three = r!(1L + 2L)?;
3706/// let rows = r!(getFromNamespace(".theoph_rows", "dataframeflows")())?;
3707/// let in_env = r!(env: my_env; x + 1)?;
3708/// ```
3709#[proc_macro]
3710pub fn r(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3711    r_macro::expand(input)
3712}
3713
3714/// Re-export other packages' R functions from this package.
3715///
3716/// Each item names a package and one of its exports. The generated R
3717/// wrappers get roxygen2's re-export block for it, so `devtools::document()`
3718/// writes `importFrom(pkg, name)` and `export(name)` to `NAMESPACE` and lists
3719/// `name` on `man/reexports.Rd`:
3720///
3721/// ```r
3722/// #' @importFrom generics tidy
3723/// #' @export
3724/// generics::tidy
3725/// ```
3726///
3727/// The usual reason is a generic the package registers S3 methods for, such
3728/// as `generics::tidy()` for `#[miniextendr(s3(generic = "tidy", class =
3729/// "my_fit"))]`: with only the package attached, a bare `tidy(fit)` then finds
3730/// the generic and dispatches to the method.
3731///
3732/// ```ignore
3733/// use miniextendr_api::reexport;
3734///
3735/// reexport!(generics::tidy, generics::glance, generics::augment);
3736/// reexport!(data.table::fread, stats::na.omit, magrittr::"%>%");
3737/// ```
3738///
3739/// - The package and the name are identifiers joined by `.`. A name that is
3740///   not a syntactic R name is a string literal (`magrittr::"%>%"`); the R
3741///   code backticks it.
3742/// - The package has to be in the `Imports` field of `DESCRIPTION`, which the
3743///   `importFrom()` needs; `R CMD check` reports a missing one.
3744/// - Any number of invocations may name the same `pkg::name`, so each module
3745///   can re-export the generics its methods are for; the wrappers get one
3746///   block per `pkg::name`.
3747/// - The wrapper writer refuses, at install time, a name re-exported from two
3748///   packages, and a name the package also defines or exports, in its
3749///   generated wrappers (an S3 generic of an impl block, a function, an
3750///   `@rawNamespace export(...)`) or a hand-written file in `R/` (a top-level
3751///   `name <- function(...)`, an `@export name`).
3752/// - A package name that is not an R package name, a name that is not an R
3753///   name, and two packages for one name in one invocation are compile
3754///   errors, all reported at once.
3755#[proc_macro]
3756pub fn reexport(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3757    reexport::expand(input.into()).into()
3758}
3759
3760/// Internal proc macro used by TPIE (Trait-Provided Impl Expansion).
3761///
3762/// Called by the metadata macro re-exported alongside each `#[miniextendr]` trait.
3763/// Do not call directly.
3764#[proc_macro]
3765#[doc(hidden)]
3766pub fn __mx_trait_impl_expand(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3767    miniextendr_impl_trait::expand_tpie(input)
3768}
3769
3770/// Generate `TypedExternal` and `IntoExternalPtr` impls for a concrete monomorphization
3771/// of a generic type.
3772///
3773/// Since `#[derive(ExternalPtr)]` rejects generic types, use this macro to generate
3774/// the necessary impls for a specific type instantiation.
3775///
3776/// # Example
3777///
3778/// ```ignore
3779/// struct Wrapper<T> { inner: T }
3780///
3781/// impl_typed_external!(Wrapper<i32>);
3782/// impl_typed_external!(Wrapper<String>);
3783/// ```
3784#[proc_macro]
3785pub fn impl_typed_external(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3786    match typed_external_macro::impl_typed_external(input.into()) {
3787        Ok(tokens) => tokens.into(),
3788        Err(err) => err.into_compile_error().into(),
3789    }
3790}
3791
3792/// Generate the `R_init_*` entry point for a miniextendr R package.
3793///
3794/// This macro consolidates all package initialization into a single line.
3795/// It generates an `extern "C-unwind"` function that R calls when loading
3796/// the shared library.
3797///
3798/// # Usage
3799///
3800/// ```ignore
3801/// // Auto-detects package name from CARGO_CRATE_NAME (recommended):
3802/// miniextendr_api::miniextendr_init!();
3803///
3804/// // Or specify explicitly (for edge cases):
3805/// miniextendr_api::miniextendr_init!(mypkg);
3806/// ```
3807///
3808/// The generated function calls `miniextendr_api::init::package_init` which
3809/// handles panic hooks, runtime init, locale assertion, ALTREP setup, trait ABI
3810/// registration, routine registration, and symbol locking.
3811///
3812/// Call it at the crate root: it also defines the crate's marker type, under
3813/// which `serde_error_shape!` declarations are keyed and which, with the API's
3814/// `serde` feature, every `#[miniextendr]` function or method returning a
3815/// `Result` names.
3816#[proc_macro]
3817pub fn miniextendr_init(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3818    let pkg_name: syn::Ident = if input.is_empty() {
3819        // Auto-detect from CARGO_CRATE_NAME (set by cargo during compilation).
3820        // Cargo normalizes hyphens → underscores, so this is almost always a
3821        // valid Rust/C identifier. Still parse through syn so malformed values
3822        // surface as a compile error rather than an ICE.
3823        let name = match std::env::var("CARGO_CRATE_NAME") {
3824            Ok(n) => n,
3825            Err(_) => {
3826                return syn::Error::new(
3827                    proc_macro2::Span::call_site(),
3828                    "CARGO_CRATE_NAME not set. Either pass the package name explicitly: \
3829                     miniextendr_init!(mypkg), or ensure you're building with cargo.",
3830                )
3831                .into_compile_error()
3832                .into();
3833            }
3834        };
3835        match syn::parse_str::<syn::Ident>(&name) {
3836            Ok(id) => id,
3837            Err(_) => {
3838                return syn::Error::new(
3839                    proc_macro2::Span::call_site(),
3840                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("CARGO_CRATE_NAME `{0}` is not a valid C identifier; R_init_<pkg> must match `[A-Za-z_][A-Za-z0-9_]*`. Pass the name explicitly: miniextendr_init!(my_pkg).",
                name))
    })format!(
3841                        "CARGO_CRATE_NAME `{name}` is not a valid C identifier; \
3842                         R_init_<pkg> must match `[A-Za-z_][A-Za-z0-9_]*`. \
3843                         Pass the name explicitly: miniextendr_init!(my_pkg)."
3844                    ),
3845                )
3846                .into_compile_error()
3847                .into();
3848            }
3849        }
3850    } else {
3851        match ::syn::parse::<syn::Ident>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}syn::parse_macro_input!(input as syn::Ident)
3852    };
3853    let fn_name = syn::Ident::new(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("R_init_{0}", pkg_name))
    })format!("R_init_{}", pkg_name), pkg_name.span());
3854    let unload_name = syn::Ident::new(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("R_unload_{0}", pkg_name))
    })format!("R_unload_{}", pkg_name), pkg_name.span());
3855
3856    // Build a byte string literal with NUL terminator for the package name.
3857    let mut name_bytes = pkg_name.to_string().into_bytes();
3858    name_bytes.push(0);
3859    let byte_lit = syn::LitByteStr::new(&name_bytes, pkg_name.span());
3860
3861    // The crate's `conversion_error_class`, for the wrappers preamble's
3862    // `.miniextendr_conversion_error_class`: the R-side argument checks raise
3863    // with the classes the conversion arms of this crate carry (#1591).
3864    let conversion_error_class = crate::crate_config::conversion_error_class();
3865    let init_marker = crate::miniextendr_fn::init_marker_ident();
3866
3867    let expanded = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" The crate\'s marker type. A `serde_error_shape!` declaration is an\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" impl keyed by it, and the generated `Err` arms look the declaration\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" up under it, so the macro must be called at the crate root.\"");
            _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_ident(&mut _s, "pub");
    ::quote::__private::push_ident(&mut _s, "enum");
    ::quote::ToTokens::to_tokens(&init_marker, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" The package crate\'s `conversion_error_class`, read by the\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" wrapper-generation pass and the raising guards (host-only; the\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" `wasm_registry.rs` snapshot carries it to wasm32).\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "cfg");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "not");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "target_arch");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::__private::parse(&mut _s, "\"wasm32\"");
                            _s
                        });
                    _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_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "linkme");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "distributed_slice");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "registry");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "MX_CONVERSION_ERROR_CLASS");
                    _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, "linkme");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "crate");
                    ::quote::__private::push_eq(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "linkme");
                    _s
                });
            _s
        });
    ::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_ident(&mut _s, "static");
    ::quote::__private::push_ident(&mut _s, "__MX_CONVERSION_ERROR_CLASS");
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "ConversionErrorClassEntry");
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "registry");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "ConversionErrorClassEntry");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "classes");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    {
                        use ::quote::__private::ext::*;
                        let mut _first = true;
                        let has_iter = ::quote::__private::HasIterator::<false>;
                        #[allow(unused_mut)]
                        let (mut conversion_error_class, i) =
                            conversion_error_class.quote_into_iter();
                        let has_iter = has_iter | i;
                        <_ as
                                ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                        while true {
                            let conversion_error_class =
                                match conversion_error_class.next() {
                                    Some(_x) => ::quote::__private::RepInterp(_x),
                                    None => break,
                                };
                            if !_first { ::quote::__private::push_comma(&mut _s); }
                            _first = false;
                            ::quote::ToTokens::to_tokens(&conversion_error_class,
                                &mut _s);
                        }
                    }
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "cfg");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "target_arch");
                    ::quote::__private::push_eq(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"wasm32\"");
                    _s
                });
            _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, "path");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s, "\"wasm_registry.rs\"");
            _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_ident(&mut _s, "mod");
    ::quote::__private::push_ident(&mut _s, "__miniextendr_wasm_registry");
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "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_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(&fn_name, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "dll");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_star(&mut _s);
            ::quote::__private::push_ident(&mut _s, "mut");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "sys");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "DllInfo");
            ::quote::__private::push_comma(&mut _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, "let");
            ::quote::__private::push_ident(&mut _s,
                "__miniextendr_init_result");
            ::quote::__private::push_eq(&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, "panic");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "catch_unwind");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "std");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "panic");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "AssertUnwindSafe");
                    ::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_pound(&mut _s);
                                    ::quote::__private::push_group(&mut _s,
                                        ::quote::__private::Delimiter::Bracket,
                                        {
                                            let mut _s = ::quote::__private::TokenStream::new();
                                            ::quote::__private::push_ident(&mut _s, "cfg");
                                            ::quote::__private::push_group(&mut _s,
                                                ::quote::__private::Delimiter::Parenthesis,
                                                {
                                                    let mut _s = ::quote::__private::TokenStream::new();
                                                    ::quote::__private::push_ident(&mut _s, "target_arch");
                                                    ::quote::__private::push_eq(&mut _s);
                                                    ::quote::__private::parse(&mut _s, "\"wasm32\"");
                                                    _s
                                                });
                                            _s
                                        });
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "registry");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s,
                                        "install_wasm_runtime_slices");
                                    ::quote::__private::push_group(&mut _s,
                                        ::quote::__private::Delimiter::Parenthesis,
                                        {
                                            let mut _s = ::quote::__private::TokenStream::new();
                                            ::quote::__private::push_ident(&mut _s,
                                                "__miniextendr_wasm_registry");
                                            ::quote::__private::push_colon2(&mut _s);
                                            ::quote::__private::push_ident(&mut _s,
                                                "MX_CALL_DEFS_WASM");
                                            ::quote::__private::push_comma(&mut _s);
                                            ::quote::__private::push_ident(&mut _s,
                                                "__miniextendr_wasm_registry");
                                            ::quote::__private::push_colon2(&mut _s);
                                            ::quote::__private::push_ident(&mut _s,
                                                "MX_ALTREP_REGISTRATIONS_WASM");
                                            ::quote::__private::push_comma(&mut _s);
                                            ::quote::__private::push_ident(&mut _s,
                                                "__miniextendr_wasm_registry");
                                            ::quote::__private::push_colon2(&mut _s);
                                            ::quote::__private::push_ident(&mut _s,
                                                "MX_TRAIT_DISPATCH_WASM");
                                            ::quote::__private::push_comma(&mut _s);
                                            ::quote::__private::push_ident(&mut _s,
                                                "__miniextendr_wasm_registry");
                                            ::quote::__private::push_colon2(&mut _s);
                                            ::quote::__private::push_ident(&mut _s,
                                                "MX_CONVERSION_ERROR_CLASS_WASM");
                                            ::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_ident(&mut _s, "let");
                                            ::quote::__private::push_ident(&mut _s, "pkg_name");
                                            ::quote::__private::push_eq(&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, "ffi");
                                            ::quote::__private::push_colon2(&mut _s);
                                            ::quote::__private::push_ident(&mut _s, "CStr");
                                            ::quote::__private::push_colon2(&mut _s);
                                            ::quote::__private::push_ident(&mut _s,
                                                "from_bytes_with_nul_unchecked");
                                            ::quote::__private::push_group(&mut _s,
                                                ::quote::__private::Delimiter::Parenthesis,
                                                {
                                                    let mut _s = ::quote::__private::TokenStream::new();
                                                    ::quote::ToTokens::to_tokens(&byte_lit, &mut _s);
                                                    _s
                                                });
                                            ::quote::__private::push_semi(&mut _s);
                                            ::quote::__private::push_colon2(&mut _s);
                                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                                            ::quote::__private::push_colon2(&mut _s);
                                            ::quote::__private::push_ident(&mut _s, "init");
                                            ::quote::__private::push_colon2(&mut _s);
                                            ::quote::__private::push_ident(&mut _s, "package_init");
                                            ::quote::__private::push_group(&mut _s,
                                                ::quote::__private::Delimiter::Parenthesis,
                                                {
                                                    let mut _s = ::quote::__private::TokenStream::new();
                                                    ::quote::__private::push_ident(&mut _s, "dll");
                                                    ::quote::__private::push_comma(&mut _s);
                                                    ::quote::__private::push_ident(&mut _s, "pkg_name");
                                                    _s
                                                });
                                            ::quote::__private::push_semi(&mut _s);
                                            _s
                                        });
                                    _s
                                });
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "if");
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Err");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "payload");
                    _s
                });
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_ident(&mut _s,
                "__miniextendr_init_result");
            ::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, "mem");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "drop");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "payload");
                            _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, "sys");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s,
                                "Rf_error_unchecked");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::parse(&mut _s,
                                        "c\"miniextendr package initialization panicked before completing\"");
                                    ::quote::__private::push_dot(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "as_ptr");
                                    ::quote::__private::push_group(&mut _s,
                                        ::quote::__private::Delimiter::Parenthesis,
                                        ::quote::__private::TokenStream::new());
                                    ::quote::__private::push_comma(&mut _s);
                                    _s
                                });
                            ::quote::__private::push_semi(&mut _s);
                            _s
                        });
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" R_unload_<pkg> entry point \u{2014} R calls this on `detach(unload=TRUE)` /\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" `dyn.unload()`. Uninstalls the miniextendr panic hook before R\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" unmaps the library\'s code.\"");
            _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_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(&unload_name, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "_dll");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_star(&mut _s);
            ::quote::__private::push_ident(&mut _s, "mut");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "sys");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "DllInfo");
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "thread");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s,
                "miniextendr_runtime_shutdown");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_semi(&mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" Linker anchor: stub.c takes the address of this symbol to force the\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" linker to pull in the user crate\'s archive member from the staticlib.\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" With codegen-units = 1, this single member contains all linkme\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" distributed_slice entries. The name is package-independent so stub.c\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" doesn\'t need configure substitution.\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s, "r\"\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" Defined as a function rather than a static so it stays exported under\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" the webR wasm RUSTFLAG -Zdefault-visibility=hidden, which keeps\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" no_mangle functions exported (like the R_init entry point) but hides\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" no_mangle statics. A hidden anchor breaks wasm side-module dlopen\"");
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::parse(&mut _s,
                "r\" (bad export type, undefined). See miniextendr webR notes (#494).\"");
            _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_ident(&mut _s, "pub");
    ::quote::__private::push_ident(&mut _s, "extern");
    ::quote::__private::parse(&mut _s, "\"C\"");
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::__private::push_ident(&mut _s, "miniextendr_force_link");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        ::quote::__private::TokenStream::new());
    _s
}quote::quote! {
3868        /// The crate's marker type. A `serde_error_shape!` declaration is an
3869        /// impl keyed by it, and the generated `Err` arms look the declaration
3870        /// up under it, so the macro must be called at the crate root.
3871        #[doc(hidden)]
3872        pub enum #init_marker {}
3873
3874        /// The package crate's `conversion_error_class`, read by the
3875        /// wrapper-generation pass and the raising guards (host-only; the
3876        /// `wasm_registry.rs` snapshot carries it to wasm32).
3877        #[cfg(not(target_arch = "wasm32"))]
3878        #[::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_CONVERSION_ERROR_CLASS)]
3879        #[linkme(crate = ::miniextendr_api::linkme)]
3880        #[doc(hidden)]
3881        static __MX_CONVERSION_ERROR_CLASS: ::miniextendr_api::registry::ConversionErrorClassEntry =
3882            ::miniextendr_api::registry::ConversionErrorClassEntry {
3883                classes: &[#(#conversion_error_class),*],
3884            };
3885
3886        // wasm32: pull in the host-generated `wasm_registry.rs` snapshot
3887        // (committed by the user crate, regenerated by `just wasm-prepare`).
3888        // The path is relative to the file invoking `miniextendr_init!()` —
3889        // by convention `<crate>/src/rust/lib.rs`, so the snapshot sits at
3890        // `<crate>/src/rust/wasm_registry.rs`. Module is `#[doc(hidden)]`
3891        // because it's purely an internal bridge between the user crate's
3892        // wrapper / vtable / register-fn `#[no_mangle]` exports and
3893        // `miniextendr_api::registry::install_wasm_runtime_slices`.
3894        #[cfg(target_arch = "wasm32")]
3895        #[path = "wasm_registry.rs"]
3896        #[doc(hidden)]
3897        mod __miniextendr_wasm_registry;
3898
3899        #[unsafe(no_mangle)]
3900        pub unsafe extern "C-unwind" fn #fn_name(
3901            dll: *mut ::miniextendr_api::sys::DllInfo,
3902        ) {
3903            let __miniextendr_init_result = ::std::panic::catch_unwind(
3904                ::std::panic::AssertUnwindSafe(|| {
3905                    // wasm32: install the pre-generated runtime tables before
3906                    // package_init runs. linkme didn't gather anything (the slices
3907                    // are OnceLock-backed on wasm32), so register_routines /
3908                    // universal_query would otherwise see empty slices, and the
3909                    // raising guards no crate conversion classes (#1768).
3910                    #[cfg(target_arch = "wasm32")]
3911                    ::miniextendr_api::registry::install_wasm_runtime_slices(
3912                        __miniextendr_wasm_registry::MX_CALL_DEFS_WASM,
3913                        __miniextendr_wasm_registry::MX_ALTREP_REGISTRATIONS_WASM,
3914                        __miniextendr_wasm_registry::MX_TRAIT_DISPATCH_WASM,
3915                        __miniextendr_wasm_registry::MX_CONVERSION_ERROR_CLASS_WASM,
3916                    );
3917
3918                    unsafe {
3919                        // SAFETY: byte literal is a valid NUL-terminated string produced by the macro.
3920                        let pkg_name = ::std::ffi::CStr::from_bytes_with_nul_unchecked(#byte_lit);
3921                        ::miniextendr_api::init::package_init(dll, pkg_name);
3922                    }
3923                }),
3924            );
3925            if let ::core::result::Result::Err(payload) = __miniextendr_init_result {
3926                // package_init normally raises through its R guard. This is
3927                // the last-resort boundary for runtime/guard initialization:
3928                // no Rust-owned message or payload may survive Rf_error.
3929                ::core::mem::drop(payload);
3930                unsafe {
3931                    ::miniextendr_api::sys::Rf_error_unchecked(
3932                        c"miniextendr package initialization panicked before completing".as_ptr(),
3933                    );
3934                }
3935            }
3936        }
3937
3938        /// R_unload_<pkg> entry point — R calls this on `detach(unload=TRUE)` /
3939        /// `dyn.unload()`. Uninstalls the miniextendr panic hook before R
3940        /// unmaps the library's code.
3941        #[unsafe(no_mangle)]
3942        pub unsafe extern "C-unwind" fn #unload_name(
3943            _dll: *mut ::miniextendr_api::sys::DllInfo,
3944        ) {
3945            ::miniextendr_api::thread::miniextendr_runtime_shutdown();
3946        }
3947
3948        /// Linker anchor: stub.c takes the address of this symbol to force the
3949        /// linker to pull in the user crate's archive member from the staticlib.
3950        /// With codegen-units = 1, this single member contains all linkme
3951        /// distributed_slice entries. The name is package-independent so stub.c
3952        /// doesn't need configure substitution.
3953        ///
3954        /// Defined as a function rather than a static so it stays exported under
3955        /// the webR wasm RUSTFLAG -Zdefault-visibility=hidden, which keeps
3956        /// no_mangle functions exported (like the R_init entry point) but hides
3957        /// no_mangle statics. A hidden anchor breaks wasm side-module dlopen
3958        /// (bad export type, undefined). See miniextendr webR notes (#494).
3959        #[unsafe(no_mangle)]
3960        pub extern "C" fn miniextendr_force_link() {}
3961    };
3962
3963    expanded.into()
3964}
3965
3966#[cfg(test)]
3967mod tests;