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: const R_WRAPPER_<NAME>: &str = "..."                  │
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//! │     ├── Wrapper struct: struct __MxWrapper<Type> { erased, data }        │
81//! │     ├── Query function: fn __mx_query_<type>(tag) → vtable ptr           │
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 const: `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//! - Wrapper: `__MxWrapperMyType`
117//! - Query: `__mx_query_mytype`
118//!
119//! ## Return Type Handling
120//!
121//! The `return_type_analysis` module determines how to convert Rust returns to SEXP:
122//!
123//! | Rust Type | Strategy | R Result |
124//! |-----------|----------|----------|
125//! | `T: IntoR` | `.into_sexp()` | Converted value |
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//! ## Thread Strategy
134//!
135//! By default, `#[miniextendr]` functions run on R's main thread. Opt into
136//! worker-thread execution with `#[miniextendr(worker)]` (requires the
137//! `worker-thread` feature on `miniextendr-api`). A worker opt-in is ignored
138//! when the signature requires main-thread execution (returns/takes `SEXP`,
139//! uses variadic dots, or sets `check_interrupt`).
140//!
141//! **Note**: `ExternalPtr<T>` is `Send` — it can be returned from worker
142//! thread functions. All R API operations on `ExternalPtr` are serialized
143//! through `with_r_thread`.
144//!
145//! ## Class Systems
146//!
147//! The `r_class_formatter` module generates R code for different class systems:
148//!
149//! | System | Generated R Code | Self Parameter |
150//! |--------|------------------|----------------|
151//! | `env` | `new.env()` with methods | `self` environment |
152//! | `r6` | `R6Class()` | `self` environment |
153//! | `s3` | `structure()` + generics | First argument |
154//! | `s4` | `setClass()` + `setMethod()` | First argument |
155//! | `s7` | `new_class()` | `self` property |
156
157// miniextendr-macros procedural macros
158
159mod altrep;
160mod c_wrapper_builder;
161mod list_macro;
162mod match_arg_keys;
163mod miniextendr_fn;
164mod type_inspect;
165mod typed_dataframe;
166mod typed_list;
167mod util;
168use crate::miniextendr_fn::{MiniextendrFnAttrs, MiniextendrFunctionParsed};
169mod miniextendr_impl;
170mod r_wrapper_builder;
171/// Builder utilities for formatting R wrapper arguments and calls.
172pub(crate) use r_wrapper_builder::RArgumentBuilder;
173mod rust_conversion_builder;
174/// Helper for generating Rust→R conversion code for return values.
175pub(crate) use rust_conversion_builder::RustConversionBuilder;
176mod method_return_builder;
177/// Helpers for shaping method return handling (R vs Rust wrapper code).
178pub(crate) use method_return_builder::{MethodReturnBuilder, ReturnStrategy};
179mod altrep_derive;
180mod dataframe_derive;
181mod lifecycle;
182mod list_derive;
183mod r_class_formatter;
184mod r_preconditions;
185mod return_type_analysis;
186mod roxygen;
187
188// Trait ABI support modules
189mod externalptr_derive;
190mod miniextendr_impl_trait;
191mod miniextendr_trait;
192mod typed_external_macro;
193
194// Factor support
195mod factor_derive;
196mod match_arg_derive;
197mod newtype_derive;
198
199// Struct/enum dispatch for #[miniextendr] on structs and enums
200mod struct_enum_dispatch;
201
202// r! proc-macro implementation
203mod r_macro;
204
205// vctrs support
206#[cfg(feature = "vctrs")]
207mod vctrs_derive;
208mod vctrs_generics;
209
210mod naming;
211pub(crate) use naming::r_wrapper_const_ident_for;
212
213// Feature default mutual exclusivity guards
214#[cfg(all(feature = "r6-default", feature = "s7-default"))]
215compile_error!(
216    "features \"r6-default\" and \"s7-default\" are mutually exclusive — \
217     enable exactly one, or omit both to fall back to the unspecified default"
218);
219// Note: default-main-thread was removed — main thread is now the hardcoded default.
220// worker-default still opts into worker thread execution.
221
222pub(crate) use type_inspect::{
223    SeveralOkContainer, classify_several_ok_container, first_type_argument,
224    is_main_thread_bound_input, is_sexp_type, second_type_argument,
225};
226pub(crate) use util::{extract_cfg_attrs, r_wrapper_raw_literal, source_location_doc};
227
228/// Validate the signature of an `extern "C-unwind"` fn exported via `#[miniextendr]`.
229///
230/// R's `.Call` interface passes all arguments as `SEXP` and expects a `SEXP`
231/// return value. For `extern "C-unwind"` functions the user writes the C symbol
232/// directly, so the signature must satisfy those invariants statically —
233/// otherwise the generated registration produces UB at runtime.
234///
235/// Called before any codegen so we fail fast on an invalid extern signature
236/// rather than emitting a wrapper that would only matter after the error.
237fn validate_extern_signature(
238    abi: &syn::Abi,
239    attrs: &[syn::Attribute],
240    inputs: &syn::punctuated::Punctuated<syn::FnArg, syn::Token![,]>,
241    output: &syn::ReturnType,
242) -> syn::Result<()> {
243    use syn::spanned::Spanned;
244
245    // Reject `self` receivers up front — they are never valid for `.Call`
246    // exports, and a missing-return-type error would only hide the real
247    // problem (users write `fn foo(self)` to ask "can I export a method?").
248    for input in inputs.iter() {
249        if let syn::FnArg::Receiver(recv) = input {
250            return Err(syn::Error::new_spanned(
251                recv,
252                "self parameter not allowed in standalone functions; \
253                 use #[miniextendr(env|r6|s3|s4|s7)] on impl blocks instead",
254            ));
255        }
256    }
257
258    // Require one of #[no_mangle] / #[unsafe(no_mangle)] / #[export_name].
259    let has_no_mangle = attrs.iter().any(|attr| {
260        attr.path().is_ident("no_mangle")
261            || attr
262                .parse_nested_meta(|meta| {
263                    if meta.path.is_ident("no_mangle") {
264                        Err(meta.error("found #[no_mangle]"))
265                    } else {
266                        Ok(())
267                    }
268                })
269                .is_err()
270    });
271    let has_export_name = attrs.iter().any(|attr| attr.path().is_ident("export_name"));
272    if !has_no_mangle && !has_export_name {
273        return Err(syn::Error::new(
274            attrs
275                .first()
276                .map(|attr| attr.span())
277                .unwrap_or_else(|| abi.span()),
278            "extern \"C-unwind\" functions need a visible C symbol for R's .Call interface. \
279             Add one of:\n  \
280             - `#[unsafe(no_mangle)]` (Rust 2024 edition)\n  \
281             - `#[no_mangle]` (Rust 2021 edition)\n  \
282             - `#[export_name = \"my_symbol\"]` (custom symbol name)",
283        ));
284    }
285
286    // Return type must be SEXP.
287    match output {
288        non_return_type @ syn::ReturnType::Default => {
289            return Err(syn::Error::new(
290                non_return_type.span(),
291                "extern \"C-unwind\" functions used with #[miniextendr] must return SEXP. \
292                 Add `-> miniextendr_api::SEXP` as the return type. \
293                 If you want automatic type conversion, remove `extern \"C-unwind\"` and let \
294                 the macro generate the C wrapper.",
295            ));
296        }
297        syn::ReturnType::Type(_rarrow, output_type) => match output_type.as_ref() {
298            syn::Type::Path(type_path) => {
299                if let Some(path_to_sexp) = type_path.path.segments.last().map(|x| &x.ident)
300                    && path_to_sexp != "SEXP"
301                {
302                    return Err(syn::Error::new(
303                        path_to_sexp.span(),
304                        format!(
305                            "extern \"C-unwind\" functions must return SEXP, found `{path_to_sexp}`. \
306                             R's .Call interface expects SEXP return values. \
307                             Change the return type to `miniextendr_api::SEXP`, or remove \
308                             `extern \"C-unwind\"` to let the macro handle type conversion.",
309                        ),
310                    ));
311                }
312            }
313            _ => {
314                return Err(syn::Error::new(
315                    output_type.span(),
316                    "extern \"C-unwind\" functions must return SEXP. \
317                     R's .Call interface expects SEXP return values. \
318                     Change the return type to `miniextendr_api::SEXP`, or remove \
319                     `extern \"C-unwind\"` to let the macro handle type conversion.",
320                ));
321            }
322        },
323    }
324
325    // Every input must be SEXP. Reject variadics and receivers.
326    for input in inputs.iter() {
327        match input {
328            syn::FnArg::Receiver(recv) => {
329                return Err(syn::Error::new_spanned(
330                    recv,
331                    "extern \"C-unwind\" functions cannot have a `self` parameter. \
332                     R's .Call interface only accepts SEXP arguments. \
333                     Use `#[miniextendr(env|r6|s3|s4|s7)]` on an impl block for methods.",
334                ));
335            }
336            syn::FnArg::Typed(pat_type) => {
337                if let syn::Pat::Rest(_) = pat_type.pat.as_ref() {
338                    return Err(syn::Error::new_spanned(
339                        pat_type,
340                        "extern functions cannot use variadic (...) - .Call passes fixed arguments",
341                    ));
342                }
343                let is_sexp = match pat_type.ty.as_ref() {
344                    syn::Type::Path(type_path) => type_path
345                        .path
346                        .segments
347                        .last()
348                        .is_some_and(|seg| seg.ident == "SEXP"),
349                    _ => false,
350                };
351                if !is_sexp {
352                    let is_dots_type = if let syn::Type::Reference(type_ref) = pat_type.ty.as_ref()
353                    {
354                        if let syn::Type::Path(inner) = type_ref.elem.as_ref() {
355                            inner
356                                .path
357                                .segments
358                                .last()
359                                .is_some_and(|seg| seg.ident == "Dots")
360                        } else {
361                            false
362                        }
363                    } else if let syn::Type::Path(type_path) = pat_type.ty.as_ref() {
364                        type_path
365                            .path
366                            .segments
367                            .last()
368                            .is_some_and(|seg| seg.ident == "Dots")
369                    } else {
370                        false
371                    };
372                    let msg = if is_dots_type {
373                        "extern functions cannot use Dots; use `...` syntax in non-extern #[miniextendr] functions instead"
374                    } else {
375                        "extern function parameters must be SEXP - .Call passes all arguments as SEXP"
376                    };
377                    return Err(syn::Error::new_spanned(&pat_type.ty, msg));
378                }
379            }
380        }
381    }
382
383    Ok(())
384}
385
386/// Builds the `let dots_typed = <dots>.typed(<spec>)...` statement injected
387/// at the start of a function body when `#[miniextendr(dots =
388/// typed_list!(...))]` is used.
389///
390/// Uses `unwrap_or_else(|e| panic!("...: {e}"))` rather than
391/// `Result::expect`, which formats the error with `Debug` instead of
392/// `Display` — for `TypedListError` that leaks PascalCase enum-variant names
393/// (`Missing { name: "x" }`) into the R-visible message instead of the
394/// human-phrased text (`missing required field: "x"`) that the direct
395/// `typed_list!` path already produces via `Display`. See audit A8.
396pub(crate) fn build_dots_validation_stmt(
397    dots_param: &syn::Ident,
398    spec_tokens: &proc_macro2::TokenStream,
399) -> syn::Stmt {
400    syn::parse_quote! {
401        let dots_typed = #dots_param.typed(#spec_tokens)
402            .unwrap_or_else(|e| panic!("dots validation failed: {e}"));
403    }
404}
405
406/// Emit the `extern "C-unwind"` helper + `R_CallMethodDef` registration for
407/// each standalone-fn `match_arg` param.
408///
409/// Each helper returns the enum's `CHOICES` wrapped in a STRSXP so the R
410/// wrapper's prelude can call `match.arg(x, .Call(helper, ...))`. Factored
411/// out of the `miniextendr` fn body so the entry point doesn't own the
412/// `quote!` scaffolding.
413fn build_match_arg_helpers(
414    match_arg_param_info: &[(String, String, &syn::Type)],
415    parsed: &miniextendr_fn::MiniextendrFunctionParsed,
416    c_ident_str: &str,
417    cfg_attrs: &[syn::Attribute],
418) -> Vec<proc_macro2::TokenStream> {
419    match_arg_param_info
420        .iter()
421        .map(|(r_param, rust_name, param_ty)| {
422            // For several_ok, the param type is e.g. Vec<Mode>/Box<[Mode]>/[Mode; N]/&[Mode]
423            // — extract inner Mode for choices_sexp.
424            let choices_ty: &syn::Type = if parsed.has_several_ok(rust_name) {
425                classify_several_ok_container(param_ty)
426                    .map(|(_, t)| t)
427                    .unwrap_or(param_ty)
428            } else {
429                param_ty
430            };
431            let helper_fn_name = crate::match_arg_keys::choices_helper_c_name(c_ident_str, r_param);
432            let helper_fn_ident = syn::Ident::new(&helper_fn_name, proc_macro2::Span::call_site());
433            let helper_def_ident =
434                crate::match_arg_keys::choices_helper_def_ident(c_ident_str, r_param);
435            let helper_c_name = syn::LitCStr::new(
436                std::ffi::CString::new(helper_fn_name.clone())
437                    .expect("valid C string")
438                    .as_c_str(),
439                proc_macro2::Span::call_site(),
440            );
441            quote::quote! {
442                #(#cfg_attrs)*
443                #[allow(non_snake_case)]
444                #[unsafe(no_mangle)]
445                pub extern "C-unwind" fn #helper_fn_ident(
446                    __miniextendr_call: ::miniextendr_api::SEXP,
447                ) -> ::miniextendr_api::SEXP {
448                    ::miniextendr_api::choices_sexp::<#choices_ty>()
449                }
450
451                #(#cfg_attrs)*
452                #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_CALL_DEFS), linkme(crate = ::miniextendr_api::linkme))]
453                #[allow(non_upper_case_globals)]
454                #[allow(non_snake_case)]
455                static #helper_def_ident: ::miniextendr_api::sys::R_CallMethodDef = unsafe {
456                    ::miniextendr_api::sys::R_CallMethodDef {
457                        name: #helper_c_name.as_ptr(),
458                        fun: Some(std::mem::transmute::<
459                            unsafe extern "C-unwind" fn(
460                                ::miniextendr_api::SEXP,
461                            ) -> ::miniextendr_api::SEXP,
462                            unsafe extern "C-unwind" fn() -> *mut ::std::os::raw::c_void,
463                        >(#helper_fn_ident)),
464                        numArgs: 1i32,
465                    }
466                };
467            }
468        })
469        .collect()
470}
471
472/// Export Rust items to R.
473///
474/// `#[miniextendr]` can be applied to:
475/// - `fn` items (generate C + R wrappers)
476/// - `impl` blocks (generate R class methods)
477/// - `trait` items (generate trait ABI metadata)
478/// - ALTREP wrapper structs (generate `RegisterAltrep` impls)
479///
480/// # Functions
481///
482/// ```ignore
483/// use miniextendr_api::miniextendr;
484///
485/// #[miniextendr]
486/// fn add(a: i32, b: i32) -> i32 { a + b }
487/// ```
488///
489/// This produces a C wrapper `C_<crate>_add` and an R wrapper `add()`.
490/// Registration is automatic via linkme distributed slices.
491///
492/// ## `extern "C-unwind"`
493///
494/// If the function is declared `extern "C-unwind"` and exported with
495/// `#[no_mangle]` (2021), `#[unsafe(no_mangle)]` (2024), or `#[export_name = "..."]`,
496/// the function itself is the C symbol and the R wrapper is prefixed with
497/// `unsafe_` to signal bypassed safety (no worker isolation or conversion).
498///
499/// ## Variadics (`...`)
500///
501/// Use `...` as the last argument. The Rust parameter becomes `_dots: &Dots`.
502/// Use `name: ...` to give it a custom name (e.g., `args: ...` → `args: &Dots`).
503///
504/// ### Typed Dots Validation
505///
506/// Use `#[miniextendr(dots = typed_list!(...))]` to automatically validate dots
507/// and create a `dots_typed` variable with typed accessors:
508///
509/// ```ignore
510/// #[miniextendr(dots = typed_list!(x => numeric(), y => integer(), z? => character()))]
511/// pub fn my_func(...) -> String {
512///     let x: f64 = dots_typed.get("x").expect("x");
513///     let y: i32 = dots_typed.get("y").expect("y");
514///     let z: Option<String> = dots_typed.get_opt("z").expect("z");
515///     format!("x={}, y={}", x, y)
516/// }
517/// ```
518///
519/// Type specs: `numeric()`, `integer()`, `logical()`, `character()`, `list()`,
520/// `raw()`, `complex()`, or `"class_name"` for class inheritance checks.
521/// Add `(n)` for exact length: `numeric(4)`. Use `?` suffix for optional fields.
522/// Use `@exact;` prefix for strict mode (reject extra fields).
523///
524/// ## Attributes
525///
526/// - `#[miniextendr(worker)]` — opt into worker-thread execution
527/// - `#[miniextendr(invisible)]` / `#[miniextendr(visible)]` — control return visibility
528/// - `#[miniextendr(check_interrupt)]` — check for user interrupt after call
529/// - `#[miniextendr(coerce)]` — coerce R type before conversion (also usable per-parameter)
530/// - `#[miniextendr(strict)]` — reject lossy conversions for i64/u64/isize/usize
531/// - `#[miniextendr(unwrap_in_r)]` — return `Result<T, E>` to R without unwrapping
532/// - `#[miniextendr(dots = typed_list!(...))]` — validate dots, create `dots_typed`
533/// - `#[miniextendr(internal)]` — adds `@keywords internal` to R wrapper
534/// - `#[miniextendr(noexport)]` — suppresses `@export` from R wrapper
535///
536/// # Impl blocks (class systems)
537///
538/// Apply `#[miniextendr(env|r6|s7|s3|s4)]` to an `impl Type` block.
539/// Use `#[miniextendr(label = "...")]` to disambiguate multiple impl blocks
540/// on the same type.
541/// Registration is automatic.
542///
543/// ## R6 Active Bindings
544///
545/// For R6 classes, use `#[miniextendr(r6(active))]` on methods to create
546/// active bindings (computed properties accessed without parentheses):
547///
548/// ```ignore
549/// use miniextendr_api::miniextendr;
550///
551/// pub struct Rectangle {
552///     width: f64,
553///     height: f64,
554/// }
555///
556/// #[miniextendr(r6)]
557/// impl Rectangle {
558///     pub fn new(width: f64, height: f64) -> Self {
559///         Self { width, height }
560///     }
561///
562///     /// Returns the area (width * height).
563///     #[miniextendr(r6(active))]
564///     pub fn area(&self) -> f64 {
565///         self.width * self.height
566///     }
567///
568///     /// Regular method (requires parentheses).
569///     pub fn scale(&mut self, factor: f64) {
570///         self.width *= factor;
571///         self.height *= factor;
572///     }
573/// }
574/// ```
575///
576/// In R:
577/// ```r
578/// r <- Rectangle$new(3, 4)
579/// r$area        # 12 (active binding - no parentheses!)
580/// r$scale(2)    # Regular method call
581/// r$area        # 24
582/// ```
583///
584/// Active bindings must be getter-only methods taking only `&self`.
585///
586/// ## S7 Properties
587///
588/// For S7 classes, use `#[miniextendr(s7(getter))]` and `#[miniextendr(s7(setter))]`
589/// to create computed properties accessed via `@`:
590///
591/// ```ignore
592/// use miniextendr_api::{miniextendr, ExternalPtr};
593///
594/// #[derive(ExternalPtr)]
595/// pub struct Range {
596///     start: f64,
597///     end: f64,
598/// }
599///
600/// #[miniextendr(s7)]
601/// impl Range {
602///     pub fn new(start: f64, end: f64) -> Self {
603///         Self { start, end }
604///     }
605///
606///     /// Computed property (read-only): length of the range.
607///     #[miniextendr(s7(getter))]
608///     pub fn length(&self) -> f64 {
609///         self.end - self.start
610///     }
611///
612///     /// Dynamic property getter.
613///     #[miniextendr(s7(getter, prop = "midpoint"))]
614///     pub fn get_midpoint(&self) -> f64 {
615///         (self.start + self.end) / 2.0
616///     }
617///
618///     /// Dynamic property setter.
619///     #[miniextendr(s7(setter, prop = "midpoint"))]
620///     pub fn set_midpoint(&mut self, value: f64) {
621///         let half = self.length() / 2.0;
622///         self.start = value - half;
623///         self.end = value + half;
624///     }
625/// }
626/// ```
627///
628/// In R:
629/// ```r
630/// r <- Range(0, 10)
631/// r@length     # 10 (computed, read-only)
632/// r@midpoint   # 5 (dynamic property)
633/// r@midpoint <- 20  # Adjusts start/end to center at 20
634/// ```
635///
636/// ### Property Attributes
637///
638/// - `#[miniextendr(s7(getter))]` - Read-only computed property
639/// - `#[miniextendr(s7(getter, prop = "name"))]` - Named property getter
640/// - `#[miniextendr(s7(setter, prop = "name"))]` - Named property setter
641/// - `#[miniextendr(s7(getter, default = "0.0"))]` - Property with default value
642/// - `#[miniextendr(s7(getter, required))]` - Required property (error if not provided)
643/// - `#[miniextendr(s7(getter, frozen))]` - Property that can only be set once
644/// - `#[miniextendr(s7(getter, deprecated = "Use X instead"))]` - Deprecated property
645/// - `#[miniextendr(s7(validate))]` - Validator function for property
646///
647/// ## S7 Generic Dispatch Control
648///
649/// Control how S7 generics are created:
650///
651/// - `#[miniextendr(s7(no_dots))]` - Create strict generic without `...`
652/// - `#[miniextendr(s7(dispatch = "x,y"))]` - Multi-dispatch on multiple arguments
653/// - `#[miniextendr(s7(fallback))]` - Register method for `class_any` (catch-all).
654///   The generated R wrapper uses `tryCatch(x@.ptr, error = function(e) x)` to
655///   safely extract the self argument, so non-miniextendr objects won't crash with
656///   a slot-access error. Instead, incompatible objects produce a Rust type-conversion
657///   error when the method tries to interpret the argument as `&Self`.
658///
659/// ```ignore
660/// #[miniextendr(s7)]
661/// impl MyClass {
662///     /// Strict generic: function(x) instead of function(x, ...)
663///     #[miniextendr(s7(no_dots))]
664///     pub fn strict_method(&self) -> i32 { 42 }
665///
666///     /// Fallback method dispatched on class_any.
667///     /// Calling this on a non-MyClass object produces a type-conversion error,
668///     /// not a slot-access crash.
669///     #[miniextendr(s7(fallback))]
670///     pub fn describe(&self) -> String { "generic description".into() }
671/// }
672/// ```
673///
674/// ## S7 Type Conversion (`convert`)
675///
676/// Use `convert_from` and `convert_to` to enable S7's `convert()` for type coercion:
677///
678/// ```ignore
679/// use miniextendr_api::{miniextendr, ExternalPtr};
680///
681/// #[derive(ExternalPtr)]
682/// pub struct Celsius { value: f64 }
683///
684/// #[derive(ExternalPtr)]
685/// pub struct Fahrenheit { value: f64 }
686///
687/// #[miniextendr(s7)]
688/// impl Fahrenheit {
689///     pub fn new(value: f64) -> Self { Self { value } }
690///
691///     /// Convert FROM Celsius TO Fahrenheit.
692///     /// Usage: S7::convert(celsius_obj, Fahrenheit)
693///     #[miniextendr(s7(convert_from = "Celsius"))]
694///     pub fn from_celsius(c: ExternalPtr<Celsius>) -> Self {
695///         Fahrenheit { value: c.value * 9.0 / 5.0 + 32.0 }
696///     }
697///
698///     /// Convert FROM Fahrenheit TO Celsius.
699///     /// Usage: S7::convert(fahrenheit_obj, Celsius)
700///     #[miniextendr(s7(convert_to = "Celsius"))]
701///     pub fn to_celsius(&self) -> Celsius {
702///         Celsius { value: (self.value - 32.0) * 5.0 / 9.0 }
703///     }
704/// }
705/// ```
706///
707/// In R:
708/// ```r
709/// c <- Celsius(100)
710/// f <- S7::convert(c, Fahrenheit)  # Uses convert_from
711/// c2 <- S7::convert(f, Celsius)    # Uses convert_to
712/// ```
713///
714/// **Note:** Classes must be defined before they can be referenced in convert methods.
715/// Define the "from" class before the "to" class to avoid forward reference issues.
716///
717/// # Traits (ABI)
718///
719/// Apply `#[miniextendr]` to a trait to generate ABI metadata, then use
720/// `#[miniextendr] impl Trait for Type`. Registration is automatic.
721///
722/// # ALTREP
723///
724/// `#[miniextendr]` no longer generates ALTREP classes — `class`/`base`
725/// attributes on a one-field struct are a compile error. Use the per-family
726/// derives (`#[derive(AltrepInteger)]`, …) with `#[altrep(class = "...")]`
727/// instead; registration is automatic there.
728#[proc_macro_attribute]
729pub fn miniextendr(
730    attr: proc_macro::TokenStream,
731    item: proc_macro::TokenStream,
732) -> proc_macro::TokenStream {
733    // Try to parse as function first
734    if syn::parse::<syn::ItemFn>(item.clone()).is_ok() {
735        // Continue with function handling below
736    } else if syn::parse::<syn::ItemImpl>(item.clone()).is_ok() {
737        // Delegate to impl block parser
738        return miniextendr_impl::expand_impl(attr, item);
739    } else if syn::parse::<syn::ItemTrait>(item.clone()).is_ok() {
740        // Delegate to trait ABI generator
741        return miniextendr_trait::expand_trait(attr, item);
742    } else {
743        // Delegate to struct/enum dispatch (handles ALTREP, ExternalPtr, list, dataframe, factor, match_arg)
744        return struct_enum_dispatch::expand_struct_or_enum(attr, item);
745    }
746
747    let MiniextendrFnAttrs {
748        force_worker,
749        force_invisible,
750        check_interrupt,
751        coerce_all,
752        rng,
753        unwrap_in_r,
754        no_preconditions,
755        no_call_attribution,
756        return_pref,
757        return_pref_span,
758        s3_generic,
759        s3_class,
760        dots_spec,
761        dots_span,
762        lifecycle,
763        strict,
764        internal,
765        noexport,
766        export,
767        doc,
768        c_symbol,
769        r_name: fn_r_name,
770        r_entry,
771        r_post_checks,
772        r_on_exit,
773    } = syn::parse_macro_input!(attr as MiniextendrFnAttrs);
774
775    let mut parsed = syn::parse_macro_input!(item as MiniextendrFunctionParsed);
776
777    // Reject async functions
778    if let Some(asyncness) = &parsed.item().sig.asyncness {
779        return syn::Error::new_spanned(
780            asyncness,
781            "async functions are not supported by #[miniextendr]; \
782             R's C API is synchronous and incompatible with async executors",
783        )
784        .into_compile_error()
785        .into();
786    }
787
788    // Validate: reject type/const generic functions.
789    // Lifetime params ARE allowed — they are erased at codegen and produce a single monomorphic
790    // symbol, so `#[no_mangle] extern "C-unwind" fn f<'a>(...)` is valid.
791    // Type and const params require monomorphization → multiple symbols → cannot be #[no_mangle].
792    {
793        let params = &parsed.item().sig.generics.params;
794        let has_type_or_const = params
795            .iter()
796            .any(|p| matches!(p, syn::GenericParam::Type(_) | syn::GenericParam::Const(_)));
797
798        if has_type_or_const {
799            let err = syn::Error::new_spanned(
800                &parsed.item().sig.generics,
801                "#[miniextendr] functions cannot have generic type or const parameters. \
802                 Generic functions are incompatible with `extern \"C-unwind\"` and `#[no_mangle]` \
803                 required for R FFI. Consider using trait objects or monomorphization instead. \
804                 Explicit lifetime parameters are allowed (lifetimes are erased at codegen).",
805            );
806            return err.into_compile_error().into();
807        }
808    }
809
810    // NB: no automatic `#[track_caller]` (dropped in #1121). It made a *direct*
811    // panic's hook-location resolve to the generated wrapper glue instead of the
812    // user's `panic!` line, which defeats the `(at file:line)` suffix now folded
813    // into the R error message from the panic hook. See docs/TRACK_CALLER.md.
814    parsed.add_inline_never_if_needed();
815
816    // Extract commonly used values
817    let uses_internal_c_wrapper = parsed.uses_internal_c_wrapper();
818    let c_ident = if let Some(ref sym) = c_symbol {
819        syn::Ident::new(sym, parsed.c_wrapper_ident().span())
820    } else {
821        parsed.c_wrapper_ident()
822    };
823    let r_wrapper_generator = parsed.r_wrapper_const_ident();
824
825    // Extract references to parsed components
826    let rust_ident = parsed.ident();
827    let inputs = parsed.inputs();
828    let output = parsed.output();
829    let abi = parsed.abi();
830    let attrs = parsed.attrs();
831    let vis = parsed.vis();
832    let generics = parsed.generics();
833    let has_dots = parsed.has_dots();
834    let named_dots = parsed.named_dots().cloned();
835
836    // Fail fast on invalid extern "C-unwind" signatures *before* any codegen,
837    // so we never emit a wrapper that would be discarded by the surfaced error.
838    if let Some(user_abi) = abi
839        && let Err(e) = validate_extern_signature(user_abi, attrs, inputs, output)
840    {
841        return e.into_compile_error().into();
842    }
843
844    // Check for @title/@description conflicts with implicit values (doc-lint feature)
845    // Skip when `doc` attribute overrides the roxygen — implicit docs are irrelevant then.
846    let doc_lint_warnings = if doc.is_some() {
847        proc_macro2::TokenStream::new()
848    } else {
849        crate::roxygen::doc_conflict_warnings(attrs, rust_ident.span())
850    };
851
852    // calling the rust function with
853    let rust_inputs: Vec<syn::Ident> = inputs
854        .iter()
855        .filter_map(|arg| {
856            if let syn::FnArg::Typed(pt) = arg
857                && let syn::Pat::Ident(p) = pt.pat.as_ref()
858            {
859                return Some(p.ident.clone());
860            }
861            None
862        })
863        .collect();
864    // dbg!(&rust_inputs);
865
866    // Validate dots_spec usage (actual injection happens later in the function body)
867    if dots_spec.is_some() && !has_dots {
868        let err = syn::Error::new(
869            dots_span.unwrap_or_else(proc_macro2::Span::call_site),
870            "#[miniextendr(dots = typed_list!(...))] requires a `...` parameter in the function signature",
871        );
872        return err.into_compile_error().into();
873    }
874
875    // Analyze return type to determine:
876    // - Whether it returns SEXP (affects thread strategy)
877    // - Whether result should be invisible
878    let rust_result_ident =
879        syn::Ident::new("__miniextendr_rust_result", proc_macro2::Span::mixed_site());
880    let return_analysis = return_type_analysis::analyze_return_type(
881        output,
882        &rust_result_ident,
883        rust_ident,
884        unwrap_in_r,
885        strict,
886    );
887
888    let returns_sexp = return_analysis.returns_sexp;
889    let is_invisible_return_type = return_analysis.is_invisible;
890
891    // Apply explicit visibility override from #[miniextendr(invisible)] or #[miniextendr(visible)]
892    let is_invisible_return_type = force_invisible.unwrap_or(is_invisible_return_type);
893
894    // Check if any input parameter is main-thread-bound (SEXP or a !Send
895    // framework wrapper like AltrepSexp — neither can move into the worker
896    // closure, so the function must stay on the main thread)
897    let has_sexp_inputs = inputs.iter().any(|arg| {
898        if let syn::FnArg::Typed(pat_type) = arg {
899            is_main_thread_bound_input(pat_type.ty.as_ref())
900        } else {
901            false
902        }
903    });
904
905    // ═══════════════════════════════════════════════════════════════════════════
906    // Thread Strategy Selection
907    // ═══════════════════════════════════════════════════════════════════════════
908    //
909    // miniextendr supports two execution strategies:
910    //
911    // 1. **Main Thread Strategy** (with_r_unwind_protect) — DEFAULT
912    //    - All code runs on R's main thread
913    //    - Required when SEXP types are involved (not Send)
914    //    - Required for R API calls (Rf_*, R_*)
915    //    - Panic handling via R_UnwindProtect (Rust destructors run correctly)
916    //    - Errors are always returned as tagged SEXP values; the R wrapper
917    //      inspects the tag and raises a structured condition (`rust_*` class
918    //      layering) past the Rust boundary.
919    //    - Simpler execution model, better R integration
920    //
921    // 2. **Worker Thread Strategy** (run_on_worker + catch_unwind) — OPT-IN
922    //    - Argument conversion on main thread (SEXP → Rust types)
923    //    - Function execution on dedicated worker thread (clean panic isolation)
924    //    - Result conversion on main thread (Rust types → SEXP)
925    //    - Panic handling via catch_unwind (prevents unwinding across FFI boundary)
926    //    - Opt in with #[miniextendr(worker)]
927    //    - ExternalPtr<T> is Send: can be returned from worker thread functions
928    //    - R API calls from worker use with_r_thread (serialized to main thread)
929    //
930    // Default: Main thread (simpler execution model, compatible with the
931    // tagged-SEXP error transport)
932    // Override: Use worker thread with #[miniextendr(worker)]
933    //
934    // Thread strategy:
935    // - Main thread is always used unless force_worker is set
936    // - force_worker cannot override hard requirements for main thread
937    // - Hard requirements: returns_sexp, has_sexp_inputs, has_dots, check_interrupt
938    let requires_main_thread = returns_sexp || has_sexp_inputs || has_dots || check_interrupt;
939    let use_main_thread = !force_worker || requires_main_thread;
940
941    // Extract cfg attributes to apply to generated items (needed by CWrapperContext)
942    let cfg_attrs = extract_cfg_attrs(parsed.attrs());
943
944    let source_loc_doc = source_location_doc(rust_ident.span());
945
946    // Build individual per-parameter coerce and match_arg_several_ok lists
947    let mut coerce_params_list: Vec<String> = Vec::new();
948    let mut match_arg_several_ok_params_list: Vec<String> = Vec::new();
949    for input in inputs.iter() {
950        if let syn::FnArg::Typed(pt) = input
951            && let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
952        {
953            let param_name = pat_ident.ident.to_string();
954            if parsed.has_coerce_attr(&param_name) {
955                coerce_params_list.push(param_name.clone());
956            }
957            if parsed.has_match_arg_attr(&param_name) && parsed.has_several_ok(&param_name) {
958                match_arg_several_ok_params_list.push(param_name);
959            }
960        }
961    }
962
963    // Build the call expression: rust_ident(rust_input_1, rust_input_2, ...)
964    let fn_call_expr = quote::quote! { #rust_ident(#(#rust_inputs),*) };
965
966    // Determine return handling: use standalone-fn semantics (OptionIntoR for Option<T>)
967    // and handle unwrap_in_r (Result<T, E> → IntoR to pass result list to R).
968    let return_pref_is_set = !matches!(return_pref, crate::miniextendr_fn::ReturnPref::Auto);
969    let fn_return_handling = if unwrap_in_r && crate::return_type_analysis::output_is_result(output)
970    {
971        // In unwrap_in_r mode the IntoR here operates on the whole Result<T,E> (the
972        // framework's IntoR for Result encodes it as a tagged list for R to decode), NOT on
973        // the inner T. prefer= always targets that inner T, so there is nothing for it to
974        // wrap here — reject rather than silently drop it (see apply_return_pref docstring
975        // and the BUG4 audit finding).
976        if return_pref_is_set {
977            let span = return_pref_span.unwrap_or_else(proc_macro2::Span::call_site);
978            return syn::Error::new(
979                span,
980                "`prefer = ...` cannot be combined with `unwrap_in_r` on a function returning \
981                 `Result<T, E>`: `unwrap_in_r` converts the whole `Result<T, E>` via a single \
982                 `IntoR` impl (a tagged list for R to decode), not the inner `T` alone, so \
983                 there is no plain `T` for `prefer=` to wrap. Remove `prefer=`.",
984            )
985            .into_compile_error()
986            .into();
987        }
988        c_wrapper_builder::ReturnHandling::IntoR
989    } else {
990        let auto = c_wrapper_builder::detect_return_handling_standalone_fn(output);
991        // Apply return_pref override: wraps the result in AsList/AsExternalPtr/AsRNative.
992        // Only applies to the plain IntoR variant — Option*/Result*/Unit/RawSexp/ExternalPtr
993        // variants have no bare T to wrap and now hard-error instead of silently ignoring
994        // prefer= (see apply_return_pref docstring).
995        match apply_return_pref(auto, return_pref, return_pref_span) {
996            Ok(handling) => handling,
997            Err(err) => return err.into_compile_error().into(),
998        }
999    };
1000
1001    let thread_strategy = if use_main_thread {
1002        c_wrapper_builder::ThreadStrategy::MainThread
1003    } else {
1004        c_wrapper_builder::ThreadStrategy::WorkerThread
1005    };
1006
1007    // Build CWrapperContext for the standalone fn
1008    let mut c_wrapper_builder =
1009        c_wrapper_builder::CWrapperContext::builder(rust_ident.clone(), c_ident.clone())
1010            .r_wrapper_const(r_wrapper_generator.clone())
1011            .inputs(inputs.iter().cloned().collect())
1012            .output(output.clone())
1013            .call_expr(fn_call_expr)
1014            .thread_strategy(thread_strategy)
1015            .return_handling(fn_return_handling)
1016            .cfg_attrs(cfg_attrs.clone())
1017            .vis(vis.clone())
1018            .generics(generics.clone())
1019            .preserve_param_names();
1020
1021    if uses_internal_c_wrapper {
1022        // Normal Rust fn: generate full C wrapper
1023    } else {
1024        // extern "C-unwind" fn: user wrote the C symbol; only emit R_CallMethodDef
1025        c_wrapper_builder = c_wrapper_builder.skip_wrapper();
1026    }
1027
1028    if coerce_all {
1029        c_wrapper_builder = c_wrapper_builder.coerce_all();
1030    }
1031    for param in &coerce_params_list {
1032        c_wrapper_builder = c_wrapper_builder.with_coerce_param(param.clone());
1033    }
1034    for param in match_arg_several_ok_params_list {
1035        c_wrapper_builder = c_wrapper_builder.match_arg_several_ok(param);
1036    }
1037    if check_interrupt {
1038        c_wrapper_builder = c_wrapper_builder.check_interrupt();
1039    }
1040    if rng {
1041        c_wrapper_builder = c_wrapper_builder.rng();
1042    }
1043    if strict {
1044        c_wrapper_builder = c_wrapper_builder.strict();
1045    }
1046
1047    let c_wrapper = c_wrapper_builder.build().generate();
1048
1049    // region: R wrappers generation in `fn`
1050    // Build R formal parameters and call arguments using shared builder
1051    let mut arg_builder = RArgumentBuilder::new(inputs);
1052    if has_dots {
1053        arg_builder = arg_builder.with_dots(named_dots.clone().map(|id| id.to_string()));
1054    }
1055    // Add user-specified parameter defaults (Missing<T> defaults handled via body prelude)
1056    let mut merged_defaults = parsed.param_defaults();
1057    // For match_arg params, always use the choices placeholder as the formal
1058    // default — the write-time pass replaces it with `c("a", "b", ...)`.
1059    // If the user supplied `default = "\"X\""`, capture X as `preferred_default`
1060    // so the write-time pass rotates X to position 1; the user's literal does
1061    // NOT become the formal (otherwise R's `match.arg` would only see one
1062    // choice).
1063    //
1064    // Tuple: (placeholder, rust_param, preferred_default_unquoted_or_empty)
1065    let mut match_arg_placeholders: Vec<(String, String, String)> = Vec::new();
1066    // (r_name, rust_param) pairs — used later to build @param doc placeholders
1067    let mut match_arg_r_names: Vec<(String, String)> = Vec::new();
1068    for match_arg_param in parsed.match_arg_params() {
1069        let r_name = r_wrapper_builder::normalize_r_arg_string(match_arg_param);
1070        match_arg_r_names.push((r_name.clone(), match_arg_param.clone()));
1071        let preferred = match merged_defaults.get(&r_name) {
1072            Some(raw) => crate::match_arg_keys::extract_match_arg_default(raw),
1073            None => String::new(),
1074        };
1075        let placeholder = crate::match_arg_keys::choices_placeholder(&c_ident.to_string(), &r_name);
1076        merged_defaults.insert(r_name.clone(), placeholder.clone());
1077        match_arg_placeholders.push((placeholder, match_arg_param.clone(), preferred));
1078    }
1079    // Add c("a", "b", "c") default for choices params (idiomatic R match.arg pattern)
1080    for (param_name, choices) in parsed.choices_params() {
1081        let r_name = r_wrapper_builder::normalize_r_arg_string(param_name);
1082        let quoted: Vec<String> = choices.iter().map(|c| format!("\"{}\"", c)).collect();
1083        merged_defaults
1084            .entry(r_name)
1085            .or_insert_with(|| format!("c({})", quoted.join(", ")));
1086    }
1087    arg_builder = arg_builder.with_defaults(merged_defaults);
1088
1089    let r_formals = arg_builder.build_formals();
1090    let mut r_call_args_strs = arg_builder.build_call_args_vec();
1091
1092    // Prepend .call parameter if using internal C wrapper.
1093    // `#[miniextendr(no_call_attribution)]` / `fast` emits `.call = NULL`
1094    // instead of `match.call()` — saves ~1200 ns/call. The R-side
1095    // .miniextendr_raise_condition helper falls back to sys.call() so the
1096    // error UX is preserved (positional args instead of named).
1097    if uses_internal_c_wrapper {
1098        let call_arg = if no_call_attribution {
1099            ".call = NULL".to_string()
1100        } else {
1101            ".call = match.call()".to_string()
1102        };
1103        r_call_args_strs.insert(0, call_arg);
1104    }
1105
1106    // Build the R body string consistently
1107    let c_ident_str = c_ident.to_string();
1108    let call_args_joined = r_call_args_strs.join(", ");
1109    let call_expr = if r_call_args_strs.is_empty() {
1110        format!(".Call({})", c_ident_str)
1111    } else {
1112        format!(".Call({}, {})", c_ident_str, call_args_joined)
1113    };
1114    let r_wrapper_return_str = {
1115        // Capture result, check for tagged condition value, raise R condition if present.
1116        let final_return = if is_invisible_return_type {
1117            "invisible(.val)"
1118        } else {
1119            ".val"
1120        };
1121        crate::method_return_builder::standalone_body(&call_expr, final_return, "  ")
1122    };
1123    // Determine R function name and S3-specific comments
1124    let is_s3_method = s3_generic.is_some() || s3_class.is_some();
1125    let r_wrapper_ident_str: String;
1126    let s3_method_comment: String;
1127
1128    if is_s3_method {
1129        // For S3 methods, function name is generic.class
1130        // generic defaults to Rust function name if not specified
1131        let generic = s3_generic.clone().unwrap_or_else(|| rust_ident.to_string());
1132        // s3_class is guaranteed to be Some here because MiniextendrFnAttrs::parse
1133        // validates that s3(...) always has class specified
1134        let class = s3_class.as_ref().expect("s3_class validated at parse time");
1135        r_wrapper_ident_str = format!("{}.{}", generic, class);
1136        // Add @importFrom for vctrs generics so roxygen registers the dependency
1137        let import_comment = if crate::vctrs_generics::is_vctrs_generic(&generic) {
1138            format!("#' @importFrom vctrs {}\n", generic)
1139        } else {
1140            String::new()
1141        };
1142        s3_method_comment = format!("{}#' @method {} {}\n", import_comment, generic, class);
1143    } else if let Some(ref custom_name) = fn_r_name {
1144        r_wrapper_ident_str = custom_name.clone();
1145        s3_method_comment = String::new();
1146    } else if abi.is_some() {
1147        r_wrapper_ident_str = format!("unsafe_{}", rust_ident);
1148        s3_method_comment = String::new();
1149    } else {
1150        r_wrapper_ident_str = rust_ident.to_string();
1151        s3_method_comment = String::new();
1152    };
1153
1154    // Stable, consistent R formatting style: brace on same line, body indented, closing brace on its own line
1155    // r_formals is already a joined string from build_formals()
1156    let formals_joined = r_formals;
1157    let mut roxygen_tags = if let Some(ref doc_text) = doc {
1158        // Custom doc override: each line becomes a separate roxygen tag entry
1159        doc_text.lines().map(|l| l.to_string()).collect()
1160    } else {
1161        crate::roxygen::roxygen_tags_from_attrs(attrs)
1162    };
1163
1164    // Determine lifecycle: explicit attr > #[deprecated] extraction
1165    let lifecycle_spec = lifecycle.or_else(|| {
1166        attrs
1167            .iter()
1168            .find_map(crate::lifecycle::parse_rust_deprecated)
1169    });
1170
1171    // Inject lifecycle badge into roxygen tags if present
1172    if let Some(ref spec) = lifecycle_spec {
1173        crate::lifecycle::inject_lifecycle_badge(&mut roxygen_tags, spec);
1174    }
1175
1176    // Auto-generate @param tags for every non-dots parameter the user didn't
1177    // already document. Priority, per param:
1178    //   1. choices(...)      — quoted list, "One of ..." / "One or more of ..."
1179    //   2. match_arg         — placeholder resolved at write time (#210)
1180    //   3. everything else   — "(no documentation available)" fallback
1181    //
1182    // Collect (doc_placeholder, rust_param) as we go so the write-time resolver
1183    // registry gets an MX_MATCH_ARG_PARAM_DOCS entry for every match_arg param.
1184    let mut match_arg_param_doc_placeholders: Vec<(String, String)> = Vec::new();
1185    for arg in inputs.iter() {
1186        let syn::FnArg::Typed(pt) = arg else {
1187            continue;
1188        };
1189        let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
1190            continue;
1191        };
1192        if parsed.is_dots_param(&pat_ident.ident) {
1193            continue;
1194        }
1195        let rust_name = pat_ident.ident.to_string();
1196        let r_name = r_wrapper_builder::normalize_r_arg_ident(&pat_ident.ident).to_string();
1197        let already_documented = crate::roxygen::param_documented(&roxygen_tags, &r_name);
1198        if already_documented {
1199            continue;
1200        }
1201
1202        if let Some(choices) = parsed.choices_for_param(&rust_name) {
1203            let quoted: Vec<String> = choices.iter().map(|c| format!("\"{}\"", c)).collect();
1204            let prefix = if parsed.has_several_ok(&rust_name) {
1205                "One or more of"
1206            } else {
1207                "One of"
1208            };
1209            roxygen_tags.push(format!("@param {r_name} {prefix} {}.", quoted.join(", ")));
1210        } else if parsed.has_match_arg_attr(&rust_name) {
1211            let doc_placeholder =
1212                crate::match_arg_keys::param_doc_placeholder(&c_ident.to_string(), &r_name);
1213            roxygen_tags.push(format!("@param {r_name} {doc_placeholder}"));
1214            match_arg_param_doc_placeholders.push((doc_placeholder, rust_name));
1215        } else {
1216            roxygen_tags.push(format!("@param {r_name} (no documentation available)"));
1217        }
1218    }
1219
1220    // A standalone function's reference page is titled by its R wrapper name — never
1221    // the doc-comment prose. rustdoc summaries are markdown (intra-doc links, code
1222    // spans) that roxygen2 can't resolve as a `\title`; the prose is promoted to
1223    // `@description` by `roxygen_tags_from_attrs` instead. Without a `@title`, roxygen2
1224    // skips the `.Rd` entirely (#1054), so inject the wrapper name when none exists.
1225    if !roxygen_tags.is_empty() && !crate::roxygen::has_roxygen_tag(&roxygen_tags, "title") {
1226        roxygen_tags.insert(0, format!("@title {}", r_wrapper_ident_str));
1227    }
1228
1229    let roxygen_tags_str = crate::roxygen::format_roxygen_tags(&roxygen_tags);
1230    let has_export_tag = crate::roxygen::has_roxygen_tag(&roxygen_tags, "export");
1231    let has_no_rd_tag = crate::roxygen::has_roxygen_tag(&roxygen_tags, "noRd");
1232    let has_internal_tag = crate::roxygen::has_roxygen_tag(&roxygen_tags, "keywords internal");
1233    // Add roxygen comments: @source for traceability, @export if public
1234    let source_comment = format!(
1235        "#' @source Generated by miniextendr from Rust fn `{}`\n",
1236        rust_ident
1237    );
1238    // Inject @keywords internal if #[miniextendr(internal)] and not already present
1239    let internal_comment = if internal && !has_internal_tag {
1240        "#' @keywords internal\n"
1241    } else {
1242        ""
1243    };
1244    // S3 methods need both @method (for registration) AND @export (for NAMESPACE)
1245    // Don't auto-export functions marked with @noRd, @keywords internal, or attr flags
1246    // #[miniextendr(export)] forces @export even on non-pub functions
1247    let export_comment = if (matches!(vis, syn::Visibility::Public(_)) || export)
1248        && !has_export_tag
1249        && !has_no_rd_tag
1250        && !has_internal_tag
1251        && !internal
1252        && !noexport
1253    {
1254        "#' @export\n".to_string()
1255    } else {
1256        String::new()
1257    };
1258    // `noexport` means no man page at all (docs/CLASS_SYSTEMS.md export-control
1259    // table): inject @noRd so roxygen2 skips the Rd and the write-time
1260    // @rdname-by-file-stem grouping (registry.rs) leaves the fn out of shared
1261    // pages. Without this, an unexported fn keeps a \usage entry in man/,
1262    // which R CMD check flags as a code/documentation mismatch.
1263    let no_rd_comment = if noexport && !has_no_rd_tag {
1264        "#' @noRd\n"
1265    } else {
1266        ""
1267    };
1268    // Generate match.arg prelude for parameters with #[miniextendr(match_arg)]
1269    // Collect (r_param_name, rust_name, rust_type) for each match_arg param
1270    let match_arg_param_info: Vec<(String, String, &syn::Type)> = inputs
1271        .iter()
1272        .filter_map(|arg| {
1273            if let syn::FnArg::Typed(pt) = arg
1274                && let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
1275            {
1276                let rust_name = pat_ident.ident.to_string();
1277                if parsed.has_match_arg_attr(&rust_name) {
1278                    let r_name =
1279                        r_wrapper_builder::normalize_r_arg_ident(&pat_ident.ident).to_string();
1280                    return Some((r_name, rust_name, pt.ty.as_ref()));
1281                }
1282            }
1283            None
1284        })
1285        .collect();
1286
1287    let match_arg_prelude = if match_arg_param_info.is_empty() {
1288        String::new()
1289    } else {
1290        let mut lines = Vec::new();
1291        for (r_param, rust_name, _) in &match_arg_param_info {
1292            // factor → character normalization
1293            lines.push(format!(
1294                "{param} <- if (is.factor({param})) as.character({param}) else {param}",
1295                param = r_param,
1296            ));
1297            // match.arg pulls the choice list off the formal default (which the
1298            // write-time pass has populated as `c("a", "b", ...)`), so no
1299            // explicit second arg is needed.
1300            if parsed.has_several_ok(rust_name) {
1301                lines.push(format!(
1302                    "{param} <- base::match.arg({param}, several.ok = TRUE)",
1303                    param = r_param,
1304                ));
1305            } else {
1306                lines.push(format!(
1307                    "{param} <- base::match.arg({param})",
1308                    param = r_param,
1309                ));
1310            }
1311        }
1312        lines.join("\n  ")
1313    };
1314
1315    // Generate idiomatic match.arg prelude for choices params
1316    // These use the simpler pattern: `param <- match.arg(param)` (no C helper call needed)
1317    // With `several_ok`, emit `match.arg(param, several.ok = TRUE)` for multi-value selection
1318    let choices_prelude = {
1319        let mut lines = Vec::new();
1320        for arg in inputs.iter() {
1321            if let syn::FnArg::Typed(pt) = arg
1322                && let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
1323            {
1324                let rust_name = pat_ident.ident.to_string();
1325                if parsed.choices_for_param(&rust_name).is_some() {
1326                    let r_name =
1327                        r_wrapper_builder::normalize_r_arg_ident(&pat_ident.ident).to_string();
1328                    if parsed.has_several_ok(&rust_name) {
1329                        lines.push(format!(
1330                            "{r_name} <- match.arg({r_name}, several.ok = TRUE)"
1331                        ));
1332                    } else {
1333                        lines.push(format!("{r_name} <- match.arg({r_name})"));
1334                    }
1335                }
1336            }
1337        }
1338        if lines.is_empty() {
1339            String::new()
1340        } else {
1341            lines.join("\n  ")
1342        }
1343    };
1344
1345    // Generate lifecycle prelude if needed
1346    let lifecycle_prelude = lifecycle_spec
1347        .as_ref()
1348        .and_then(|spec| spec.r_prelude(&r_wrapper_ident_str));
1349
1350    // Generate R-side precondition checks (stopifnot + fallback precheck calls)
1351    // Skip both match_arg and choices params (already validated by match.arg)
1352    let mut skip_params: std::collections::HashSet<String> =
1353        parsed.match_arg_params().cloned().collect();
1354    for (param_name, _) in parsed.choices_params() {
1355        skip_params.insert(r_wrapper_builder::normalize_r_arg_string(param_name));
1356    }
1357    // `#[miniextendr(no_preconditions)]` / `fast` opts out of the stopifnot
1358    // prelude entirely. TryFromSexp still raises a typed Rust error on
1359    // mismatched input — see analysis/scaffolding-deep-findings-2026-05-20.md
1360    // for why this is ~1230 ns / 1-arg or ~3900 ns / 5-arg of savings.
1361    let precondition_prelude = if no_preconditions {
1362        String::new()
1363    } else {
1364        // A coerced integer-element vector reads via `&[i32]` (INTSXP-only), so its
1365        // precondition tightens to `is.integer` (issue #616). `coerce_params_list`
1366        // holds Rust names; normalize to R names.
1367        let precondition_opts = r_preconditions::PreconditionOptions {
1368            coerce_all,
1369            coerce_params: coerce_params_list
1370                .iter()
1371                .map(|p| r_wrapper_builder::normalize_r_arg_string(p))
1372                .collect(),
1373        };
1374        let precondition_output =
1375            r_preconditions::build_precondition_checks(inputs, &skip_params, &precondition_opts);
1376        if precondition_output.static_checks.is_empty() {
1377            String::new()
1378        } else {
1379            precondition_output.static_checks.join("\n  ")
1380        }
1381    };
1382
1383    // Combine all preludes: r_entry, on.exit, lifecycle, static preconditions, match.arg, choices, r_post_checks
1384    // (Missing<T> forwarding lives inline in the `.Call()` args — see
1385    // `build_call_args_vec` — because a prelude binding of the missing
1386    // sentinel errors on lookup.)
1387    let on_exit_str = r_on_exit.as_ref().map(|oe| oe.to_r_code());
1388    let combined_prelude = {
1389        let mut parts = Vec::new();
1390        if let Some(ref entry) = r_entry {
1391            parts.push(entry.as_str());
1392        }
1393        if let Some(ref s) = on_exit_str {
1394            parts.push(s.as_str());
1395        }
1396        if let Some(ref lc) = lifecycle_prelude {
1397            parts.push(lc.as_str());
1398        }
1399        if !precondition_prelude.is_empty() {
1400            parts.push(&precondition_prelude);
1401        }
1402        if !match_arg_prelude.is_empty() {
1403            parts.push(&match_arg_prelude);
1404        }
1405        if !choices_prelude.is_empty() {
1406            parts.push(&choices_prelude);
1407        }
1408        if let Some(ref post) = r_post_checks {
1409            parts.push(post.as_str());
1410        }
1411        if parts.is_empty() {
1412            None
1413        } else {
1414            Some(parts.join("\n  "))
1415        }
1416    };
1417
1418    let r_wrapper_string = if let Some(prelude) = combined_prelude {
1419        format!(
1420            "{}{}{}{}{}{}{} <- function({}) {{\n  {}\n  {}\n}}",
1421            roxygen_tags_str,
1422            source_comment,
1423            s3_method_comment,
1424            internal_comment,
1425            no_rd_comment,
1426            export_comment,
1427            r_wrapper_ident_str,
1428            formals_joined,
1429            prelude,
1430            r_wrapper_return_str
1431        )
1432    } else {
1433        format!(
1434            "{}{}{}{}{}{}{} <- function({}) {{\n  {}\n}}",
1435            roxygen_tags_str,
1436            source_comment,
1437            s3_method_comment,
1438            internal_comment,
1439            no_rd_comment,
1440            export_comment,
1441            r_wrapper_ident_str,
1442            formals_joined,
1443            r_wrapper_return_str
1444        )
1445    };
1446    // Use a raw string literal for better readability in macro expansion
1447    let r_wrapper_str = r_wrapper_raw_literal(&r_wrapper_string);
1448
1449    // endregion
1450
1451    // Generate doc strings with links
1452    let r_wrapper_doc = format!(
1453        "R wrapper code for [`{}`], calls [`{}`].",
1454        rust_ident, c_ident
1455    );
1456    let source_start = rust_ident.span().start();
1457    let source_line_lit = syn::LitInt::new(&source_start.line.to_string(), rust_ident.span());
1458    let source_col_lit =
1459        syn::LitInt::new(&(source_start.column + 1).to_string(), rust_ident.span());
1460
1461    // Get the normalized item for output, with roxygen tags stripped from docs.
1462    // Roxygen tags are for R documentation and shouldn't appear in rustdoc.
1463    let mut original_item = parsed.item_without_roxygen();
1464    // Strip only the miniextendr attributes; keep everything else.
1465    original_item
1466        .attrs
1467        .retain(|attr| !attr.path().is_ident("miniextendr"));
1468
1469    // Inject dots_typed binding into function body if dots = typed_list!(...) was specified
1470    if let Some(ref spec_tokens) = dots_spec {
1471        let dots_param = named_dots.clone().unwrap_or_else(|| {
1472            syn::Ident::new("__miniextendr_dots", proc_macro2::Span::call_site())
1473        });
1474        let validation_stmt = build_dots_validation_stmt(&dots_param, spec_tokens);
1475        original_item.block.stmts.insert(0, validation_stmt);
1476    }
1477
1478    let original_item = original_item;
1479
1480    // Generate match_arg choices helper C wrappers and R_CallMethodDef entries
1481    let match_arg_helpers = build_match_arg_helpers(
1482        &match_arg_param_info,
1483        &parsed,
1484        &c_ident.to_string(),
1485        &cfg_attrs,
1486    );
1487
1488    // Generate MX_MATCH_ARG_CHOICES entries for placeholder → choices replacement
1489    // Resolve the `MatchArg`-bound type used in the choices_str closure: for
1490    // `several_ok` params that's the inner element of the container, otherwise
1491    // it's the param type directly.
1492    let choices_ty_for = |rust_param: &str| -> Option<&syn::Type> {
1493        let (_, _, param_ty) = match_arg_param_info
1494            .iter()
1495            .find(|(_, rn, _)| rn == rust_param)?;
1496        let ty: &syn::Type = if parsed.has_several_ok(rust_param) {
1497            classify_several_ok_container(param_ty)
1498                .map(|(_, t)| t)
1499                .unwrap_or(param_ty)
1500        } else {
1501            param_ty
1502        };
1503        Some(ty)
1504    };
1505
1506    let match_arg_choices_entries: Vec<proc_macro2::TokenStream> = match_arg_placeholders
1507        .iter()
1508        .filter_map(|(placeholder, rust_param, preferred_default)| {
1509            let choices_ty = choices_ty_for(rust_param)?;
1510            let entry_ident = syn::Ident::new(
1511                &format!(
1512                    "match_arg_choices_entry_{}",
1513                    crate::match_arg_keys::placeholder_ident_suffix(placeholder)
1514                ),
1515                proc_macro2::Span::call_site(),
1516            );
1517            Some(crate::match_arg_keys::choices_entry_tokens(
1518                &cfg_attrs,
1519                &entry_ident,
1520                placeholder,
1521                choices_ty,
1522                preferred_default,
1523            ))
1524        })
1525        .collect();
1526
1527    // Generate MX_MATCH_ARG_PARAM_DOCS entries for @param doc placeholder → choice description
1528    let match_arg_param_doc_entries: Vec<proc_macro2::TokenStream> =
1529        match_arg_param_doc_placeholders
1530            .iter()
1531            .filter_map(|(doc_placeholder, rust_param)| {
1532                let choices_ty = choices_ty_for(rust_param)?;
1533                let several_ok_lit = parsed.has_several_ok(rust_param);
1534                let entry_ident = syn::Ident::new(
1535                    &format!(
1536                        "match_arg_param_doc_entry_{}",
1537                        crate::match_arg_keys::placeholder_ident_suffix(doc_placeholder)
1538                    ),
1539                    proc_macro2::Span::call_site(),
1540                );
1541                Some(crate::match_arg_keys::param_doc_entry_tokens(
1542                    &cfg_attrs,
1543                    &entry_ident,
1544                    doc_placeholder,
1545                    several_ok_lit,
1546                    choices_ty,
1547                ))
1548            })
1549            .collect();
1550
1551    // Generate doc comment linking to C wrapper and R wrapper constant
1552    let fn_r_wrapper_doc = format!(
1553        "See [`{}`] for C wrapper, [`{}`] for R wrapper.",
1554        c_ident, r_wrapper_generator
1555    );
1556
1557    let expanded: proc_macro::TokenStream = quote::quote! {
1558        // rust function with doc link to R wrapper
1559        #[doc = #fn_r_wrapper_doc]
1560        #original_item
1561
1562        // C wrapper
1563        #(#cfg_attrs)*
1564        #c_wrapper
1565
1566        // R wrapper (self-registers via distributed_slice)
1567        #(#cfg_attrs)*
1568        #[doc = #r_wrapper_doc]
1569        #[doc = concat!("Wraps Rust function `", stringify!(#rust_ident), "`.")]
1570        #[doc = #source_loc_doc]
1571        #[doc = concat!("Generated from source file `", file!(), "`.")]
1572        #[cfg_attr(not(target_arch = "wasm32"), ::miniextendr_api::linkme::distributed_slice(::miniextendr_api::registry::MX_R_WRAPPERS), linkme(crate = ::miniextendr_api::linkme))]
1573        #[allow(non_upper_case_globals)]
1574        #[allow(non_snake_case)]
1575        static #r_wrapper_generator: ::miniextendr_api::registry::RWrapperEntry =
1576            ::miniextendr_api::registry::RWrapperEntry {
1577                priority: ::miniextendr_api::registry::RWrapperPriority::Function,
1578                source_file: file!(),
1579                content: concat!(
1580                    "# Generated from Rust fn `",
1581                    stringify!(#rust_ident),
1582                    "` (",
1583                    file!(),
1584                    ":",
1585                    #source_line_lit,
1586                    ":",
1587                    #source_col_lit,
1588                    ")",
1589                    #r_wrapper_str
1590                ),
1591            };
1592
1593        // match_arg choices helpers (C wrappers + R_CallMethodDef entries)
1594        // Each helper's call_method_def self-registers via distributed_slice
1595        #(#match_arg_helpers)*
1596
1597        // match_arg choices entries for R wrapper default replacement
1598        #(#match_arg_choices_entries)*
1599
1600        // match_arg @param doc entries for R wrapper roxygen doc replacement
1601        #(#match_arg_param_doc_entries)*
1602
1603        // doc-lint warnings (if any)
1604        #doc_lint_warnings
1605    }
1606    .into();
1607
1608    expanded
1609}
1610
1611/// Maps a `ReturnPref` attribute value onto an auto-detected `ReturnHandling`.
1612///
1613/// Only the plain `IntoR` variant has a bare `T` for `prefer=` to wrap, so it is the
1614/// only variant substituted with its pref-specific counterpart
1615/// (`AsListOf`/`AsExternalPtrOf`/`AsNativeOf`). Every other variant (`Unit`, `RawSexp`,
1616/// `ExternalPtr`, `Option*`, `Result*`) has its own fixed SEXP-shape rule that
1617/// `prefer=` cannot compose with — returning a compile error for those is better than
1618/// silently dropping the attribute (see the BUG4 audit finding: `prefer = "list"` on an
1619/// `Option<T>` return used to be accepted and silently ignored).
1620fn apply_return_pref(
1621    auto: c_wrapper_builder::ReturnHandling,
1622    pref: crate::miniextendr_fn::ReturnPref,
1623    pref_span: Option<proc_macro2::Span>,
1624) -> syn::Result<c_wrapper_builder::ReturnHandling> {
1625    use crate::miniextendr_fn::ReturnPref;
1626    use c_wrapper_builder::ReturnHandling;
1627
1628    let wrapped = match pref {
1629        ReturnPref::Auto => return Ok(auto),
1630        ReturnPref::List => match auto {
1631            ReturnHandling::IntoR => Some(ReturnHandling::AsListOf),
1632            _ => None,
1633        },
1634        ReturnPref::ExternalPtr => match auto {
1635            ReturnHandling::IntoR => Some(ReturnHandling::AsExternalPtrOf),
1636            _ => None,
1637        },
1638        ReturnPref::Native => match auto {
1639            ReturnHandling::IntoR => Some(ReturnHandling::AsNativeOf),
1640            _ => None,
1641        },
1642    };
1643
1644    wrapped.ok_or_else(|| {
1645        let (pref_name, wrapper_name) = return_pref_names(pref);
1646        let span = pref_span.unwrap_or_else(proc_macro2::Span::call_site);
1647        syn::Error::new(
1648            span,
1649            format!(
1650                "`prefer = \"{pref_name}\"` cannot be honored on this return type. \
1651                 `prefer=` only applies to a function returning a plain `T: IntoR` value, \
1652                 which it wraps in `{wrapper_name}` before conversion. This function's return \
1653                 type falls into a different codegen category ({}) with its own fixed \
1654                 SEXP-shape rule, so there is no plain `T` for `prefer=` to wrap. Remove \
1655                 `prefer=`, or change the return type to a plain `T`.",
1656                return_handling_category_description(&auto),
1657            ),
1658        )
1659    })
1660}
1661
1662/// Human-readable `(attribute value, wrapper type)` pair for a [`ReturnPref`](crate::miniextendr_fn::ReturnPref),
1663/// used to phrase the `apply_return_pref` compile error.
1664fn return_pref_names(pref: crate::miniextendr_fn::ReturnPref) -> (&'static str, &'static str) {
1665    use crate::miniextendr_fn::ReturnPref;
1666    match pref {
1667        ReturnPref::Auto => ("auto", ""),
1668        ReturnPref::List => ("list", "AsList"),
1669        ReturnPref::ExternalPtr => ("externalptr", "AsExternalPtr"),
1670        ReturnPref::Native => ("native", "AsRNative"),
1671    }
1672}
1673
1674/// Human-readable description of a [`ReturnHandling`](c_wrapper_builder::ReturnHandling)
1675/// category, for the `apply_return_pref` compile error. Only describes the categories
1676/// [`c_wrapper_builder::detect_return_handling_standalone_fn`] can actually produce;
1677/// the wildcard arm covers variants that never reach `apply_return_pref` as `auto`
1678/// (`IntoR` itself, method-only `SelfHandle`, and the `As*Of` variants `apply_return_pref`
1679/// produces as *output*, never takes as input).
1680fn return_handling_category_description(rh: &c_wrapper_builder::ReturnHandling) -> &'static str {
1681    use c_wrapper_builder::ReturnHandling;
1682    match rh {
1683        ReturnHandling::Unit => "the unit return type `()`",
1684        ReturnHandling::RawSexp => "a raw `SEXP` return type",
1685        ReturnHandling::ExternalPtr => {
1686            "a `Self`-returning constructor, already converted via `ExternalPtr::new`"
1687        }
1688        ReturnHandling::OptionUnit => "`Option<()>`",
1689        ReturnHandling::OptionSexp => "`Option<SEXP>`",
1690        ReturnHandling::OptionIntoR | ReturnHandling::OptionIntoRUnwrap => "`Option<T>`",
1691        ReturnHandling::ResultUnit => "`Result<(), E>`",
1692        ReturnHandling::ResultSexp => "`Result<SEXP, E>`",
1693        ReturnHandling::ResultIntoR => "`Result<T, E>`",
1694        ReturnHandling::ResultNullOnErr => "`Result<T, ()>`",
1695        _ => "this return type",
1696    }
1697}
1698
1699/// Generate thread-safe wrappers for R FFI functions.
1700///
1701/// Apply this to an `extern "C-unwind"` block to generate, **for each
1702/// non-variadic function**, a pair of entry points:
1703///
1704/// - The original name (e.g. `Rf_allocVector`) — a safe Rust wrapper that
1705///   runs directly on R's main thread, routes through
1706///   `miniextendr_api::worker::with_r_thread` from an active miniextendr
1707///   worker context, and panics for arbitrary off-main callers.
1708/// - A `*_unchecked` sibling (`Rf_allocVector_unchecked`) — the raw
1709///   `extern "C-unwind"` declaration with no main-thread assertion and no
1710///   worker round-trip.
1711///
1712/// User code should reach for the checked variant by default; the unchecked
1713/// sibling exists for three known-safe contexts:
1714///
1715/// 1. **Inside ALTREP callbacks** — R is already calling us on the main
1716///    thread, so the assertion would always pass and the route would
1717///    deadlock the call back to R.
1718/// 2. **Inside a `with_r_unwind_protect` body** — the guard has established
1719///    main-thread context, and re-entering `with_r_thread` would nest two
1720///    `R_UnwindProtect` frames (paying the longjmp-leak cost twice).
1721/// 3. **Inside a `with_r_thread` body** — the assertion is redundant; you
1722///    are already where you needed to be.
1723///
1724/// The build-time lint **MXL301** enforces this: calling `*_unchecked`
1725/// outside one of those three contexts is a compile-time error. Without the
1726/// `worker-thread` feature, the checked variant still enforces the recorded
1727/// main-thread contract; it simply has no worker route available.
1728///
1729/// # Tradeoffs at a glance
1730///
1731/// | Variant | Asserts main thread | Routes to main | When to use |
1732/// |---|---|---|---|
1733/// | `Rf_foo` (checked) | yes (debug) | yes (from worker) | default |
1734/// | `Rf_foo_unchecked` | no | no | ALTREP callbacks, `with_r_unwind_protect`, `with_r_thread` |
1735///
1736/// # Behavior
1737///
1738/// All non-variadic functions are routed to the main thread via `with_r_thread`
1739/// when called from a worker thread. The return value is wrapped in `Sendable`
1740/// and sent back to the caller. This applies to both value-returning functions
1741/// (SEXP, i32, etc.) and pointer-returning functions (`*const T`, `*mut T`).
1742///
1743/// Pointer-returning functions (like `INTEGER`, `REAL`) are safe to route because
1744/// the underlying SEXP must be GC-protected by the caller, and R's GC only runs
1745/// during R API calls which are serialized through `with_r_thread`.
1746///
1747/// # Initialization Requirement
1748///
1749/// `miniextendr_runtime_init()` must be called before using any wrapped function.
1750/// Calling before initialization will panic with a descriptive error message.
1751///
1752/// # Limitations
1753///
1754/// - Variadic functions are passed through unchanged (no wrapper)
1755/// - Statics are passed through unchanged
1756/// - Functions with `#[link_name]` are passed through unchanged
1757///
1758/// # Example
1759///
1760/// ```ignore
1761/// #[r_ffi_checked]
1762/// unsafe extern "C-unwind" {
1763///     // Routed to main thread via with_r_thread when called from worker
1764///     pub fn Rf_ScalarInteger(arg1: i32) -> SEXP;
1765///     pub fn INTEGER(x: SEXP) -> *mut i32;
1766/// }
1767/// ```
1768#[proc_macro_attribute]
1769pub fn r_ffi_checked(
1770    _attr: proc_macro::TokenStream,
1771    item: proc_macro::TokenStream,
1772) -> proc_macro::TokenStream {
1773    let foreign_mod = syn::parse_macro_input!(item as syn::ItemForeignMod);
1774
1775    let foreign_mod_attrs = &foreign_mod.attrs;
1776    let abi = &foreign_mod.abi;
1777    let mut unchecked_items = Vec::new();
1778    let mut checked_wrappers = Vec::new();
1779
1780    for item in &foreign_mod.items {
1781        match item {
1782            syn::ForeignItem::Fn(fn_item) => {
1783                let is_variadic = fn_item.sig.variadic.is_some();
1784
1785                // Check if function already has #[link_name] - if so, pass through unchanged
1786                let has_link_name = fn_item
1787                    .attrs
1788                    .iter()
1789                    .any(|attr| attr.path().is_ident("link_name"));
1790
1791                if is_variadic || has_link_name {
1792                    // Pass through variadic functions and functions with explicit link_name unchanged
1793                    unchecked_items.push(item.clone());
1794                } else {
1795                    // Generate checked wrapper for non-variadic functions
1796                    let vis = &fn_item.vis;
1797                    let fn_name = &fn_item.sig.ident;
1798                    let fn_name_str = fn_name.to_string();
1799                    let unchecked_name = quote::format_ident!("{}_unchecked", fn_name);
1800                    let unchecked_name_str = unchecked_name.to_string();
1801                    let inputs = &fn_item.sig.inputs;
1802                    let output = &fn_item.sig.output;
1803                    // Filter out link_name attributes (already checked above, but be safe)
1804                    let attrs: Vec<_> = fn_item
1805                        .attrs
1806                        .iter()
1807                        .filter(|attr| !attr.path().is_ident("link_name"))
1808                        .collect();
1809                    let checked_doc = format!(
1810                        "Checked wrapper for `{}`. Calls `{}` and routes through `with_r_thread`.",
1811                        fn_name_str, unchecked_name_str
1812                    );
1813                    let checked_doc_lit = syn::LitStr::new(&checked_doc, fn_name.span());
1814                    let source_loc_doc = crate::source_location_doc(fn_name.span());
1815                    let source_loc_doc_lit = syn::LitStr::new(&source_loc_doc, fn_name.span());
1816
1817                    // Generate the unchecked FFI binding with #[link_name]
1818                    // Same visibility as the checked variant
1819                    let link_name = syn::LitStr::new(&fn_name_str, fn_name.span());
1820                    let unchecked_fn: syn::ForeignItem = syn::parse_quote! {
1821                        #(#attrs)*
1822                        #[doc = concat!("Unchecked FFI binding for `", stringify!(#fn_name), "`.")]
1823                        #[doc = #source_loc_doc_lit]
1824                        #[doc = concat!("Generated from source file `", file!(), "`.")]
1825                        #[link_name = #link_name]
1826                        #vis fn #unchecked_name(#inputs) #output;
1827                    };
1828                    unchecked_items.push(unchecked_fn);
1829
1830                    // Generate a checked wrapper function
1831                    let arg_names: Vec<_> = inputs
1832                        .iter()
1833                        .filter_map(|arg| {
1834                            if let syn::FnArg::Typed(pat_type) = arg
1835                                && let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref()
1836                            {
1837                                Some(pat_ident.ident.clone())
1838                            } else {
1839                                None
1840                            }
1841                        })
1842                        .collect();
1843
1844                    let is_never = matches!(output, syn::ReturnType::Type(_, ty) if matches!(**ty, syn::Type::Never(_)));
1845
1846                    let wrapper = if is_never {
1847                        // Never-returning functions (like Rf_error)
1848                        quote::quote! {
1849                            #(#attrs)*
1850                            #[doc = #checked_doc_lit]
1851                            #[doc = #source_loc_doc_lit]
1852                            #[doc = concat!("Generated from source file `", file!(), "`.")]
1853                            #[inline(always)]
1854                            #[allow(non_snake_case)]
1855                            #vis unsafe fn #fn_name(#inputs) #output {
1856                                ::miniextendr_api::worker::with_r_thread(move || unsafe {
1857                                    #unchecked_name(#(#arg_names),*)
1858                                })
1859                            }
1860                        }
1861                    } else {
1862                        // Normal functions - route via with_r_thread
1863                        quote::quote! {
1864                            #(#attrs)*
1865                            #[doc = #checked_doc_lit]
1866                            #[doc = #source_loc_doc_lit]
1867                            #[doc = concat!("Generated from source file `", file!(), "`.")]
1868                            #[inline(always)]
1869                            #[allow(non_snake_case)]
1870                            #vis unsafe fn #fn_name(#inputs) #output {
1871                                let result = ::miniextendr_api::worker::with_r_thread(move || {
1872                                    ::miniextendr_api::worker::Sendable(unsafe {
1873                                        #unchecked_name(#(#arg_names),*)
1874                                    })
1875                                });
1876                                result.0
1877                            }
1878                        }
1879                    };
1880                    checked_wrappers.push(wrapper);
1881                }
1882            }
1883            _ => {
1884                // Pass through statics and other items unchanged
1885                unchecked_items.push(item.clone());
1886            }
1887        }
1888    }
1889
1890    let expanded = quote::quote! {
1891        #(#foreign_mod_attrs)*
1892        unsafe #abi {
1893            #(#unchecked_items)*
1894        }
1895
1896        #(#checked_wrappers)*
1897    };
1898
1899    expanded.into()
1900}
1901
1902/// Derive macro for implementing `RNativeType` on a newtype wrapper.
1903///
1904/// This allows newtype wrappers around R native types to work with `Vec<T>`,
1905/// `&[T]` conversions and the `Coerce<R>` traits.
1906/// The inner type must implement `RNativeType`.
1907///
1908/// # Supported Struct Forms
1909///
1910/// Both tuple structs and single-field named structs are supported:
1911///
1912/// ```ignore
1913/// use miniextendr_api::RNativeType;
1914///
1915/// // Tuple struct (most common)
1916/// #[derive(Clone, Copy, RNativeType)]
1917/// struct UserId(i32);
1918///
1919/// // Named single-field struct
1920/// #[derive(Clone, Copy, RNativeType)]
1921/// struct Temperature { celsius: f64 }
1922/// ```
1923///
1924/// # Generated Code
1925///
1926/// For `struct UserId(i32)`, this generates:
1927///
1928/// ```ignore
1929/// impl RNativeType for UserId {
1930///     const SEXP_TYPE: SEXPTYPE = <i32 as RNativeType>::SEXP_TYPE;
1931///     const R_NA: Self = UserId(<i32 as RNativeType>::R_NA);
1932///
1933///     unsafe fn dataptr_mut(sexp: SEXP) -> *mut Self {
1934///         <i32 as RNativeType>::dataptr_mut(sexp).cast()
1935///     }
1936/// }
1937/// ```
1938///
1939/// # Using the Newtype with Coerce
1940///
1941/// Once `RNativeType` is derived, you can implement `Coerce` to/from the newtype:
1942///
1943/// ```ignore
1944/// impl Coerce<UserId> for i32 {
1945///     fn coerce(self) -> UserId { UserId(self) }
1946/// }
1947///
1948/// let id: UserId = 42.coerce();
1949/// ```
1950///
1951/// # Requirements
1952///
1953/// - Must be a newtype struct (exactly one field, tuple or named)
1954/// - The inner type must implement `RNativeType` (`i32`, `f64`, `RLogical`, `u8`, `Rcomplex`)
1955/// - Should also derive `Copy` (required by `RNativeType: Copy`)
1956#[proc_macro_derive(RNativeType)]
1957pub fn derive_rnative_type(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
1958    let input = syn::parse_macro_input!(input as syn::DeriveInput);
1959    let name = &input.ident;
1960    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
1961
1962    // Extract inner type and constructor — must be a newtype (single field)
1963    let (inner_ty, elt_ctor): (syn::Type, proc_macro2::TokenStream) = match &input.data {
1964        syn::Data::Struct(data) => match &data.fields {
1965            syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
1966                let ty = fields.unnamed.first().unwrap().ty.clone();
1967                let ctor = quote::quote! { Self(val) };
1968                (ty, ctor)
1969            }
1970            syn::Fields::Named(fields) if fields.named.len() == 1 => {
1971                let field = fields.named.first().unwrap();
1972                let ty = field.ty.clone();
1973                let field_name = field.ident.as_ref().unwrap();
1974                let ctor = quote::quote! { Self { #field_name: val } };
1975                (ty, ctor)
1976            }
1977            _ => {
1978                return syn::Error::new_spanned(
1979                    name,
1980                    "#[derive(RNativeType)] requires a newtype struct with exactly one field",
1981                )
1982                .into_compile_error()
1983                .into();
1984            }
1985        },
1986        _ => {
1987            return syn::Error::new_spanned(name, "#[derive(RNativeType)] only works on structs")
1988                .into_compile_error()
1989                .into();
1990        }
1991    };
1992
1993    let expanded = quote::quote! {
1994        impl #impl_generics ::miniextendr_api::RNativeType for #name #ty_generics #where_clause {
1995            const SEXP_TYPE: ::miniextendr_api::SEXPTYPE =
1996                <#inner_ty as ::miniextendr_api::RNativeType>::SEXP_TYPE;
1997
1998            const R_NA: Self = {
1999                let val = <#inner_ty as ::miniextendr_api::RNativeType>::R_NA;
2000                #elt_ctor
2001            };
2002
2003            #[inline]
2004            unsafe fn dataptr_mut(sexp: ::miniextendr_api::SEXP) -> *mut Self {
2005                // Newtype is repr(transparent), so we can cast the pointer
2006                unsafe {
2007                    <#inner_ty as ::miniextendr_api::RNativeType>::dataptr_mut(sexp).cast()
2008                }
2009            }
2010
2011            #[inline]
2012            fn elt(sexp: ::miniextendr_api::SEXP, i: isize) -> Self {
2013                let val = <#inner_ty as ::miniextendr_api::RNativeType>::elt(sexp, i);
2014                #elt_ctor
2015            }
2016        }
2017
2018    };
2019
2020    expanded.into()
2021}
2022
2023/// Derive macro for implementing `TypedExternal` on a type.
2024///
2025/// This makes the type compatible with `ExternalPtr<T>` for storing in R's external pointers.
2026///
2027/// # Basic Usage
2028///
2029/// ```ignore
2030/// use miniextendr_api::TypedExternal;
2031///
2032/// #[derive(ExternalPtr)]
2033/// struct MyData {
2034///     value: i32,
2035/// }
2036///
2037/// // Now you can use ExternalPtr<MyData>
2038/// let ptr = ExternalPtr::new(MyData { value: 42 });
2039/// ```
2040///
2041/// # Trait ABI
2042///
2043/// Trait dispatch wrappers are automatically generated:
2044///
2045/// ```ignore
2046/// use miniextendr_api::miniextendr;
2047///
2048/// #[derive(ExternalPtr)]
2049/// struct MyCounter {
2050///     value: i32,
2051/// }
2052///
2053/// #[miniextendr]
2054/// impl Counter for MyCounter {
2055///     fn value(&self) -> i32 { self.value }
2056///     fn increment(&mut self) { self.value += 1; }
2057/// }
2058/// ```
2059///
2060/// This generates additional infrastructure for type-erased trait dispatch:
2061/// - `__MxWrapperMyCounter` - Type-erased wrapper struct
2062/// - `__MX_BASE_VTABLE_MYCOUNTER` - Base vtable with drop/query
2063/// - `__mx_wrap_mycounter()` - Constructor returning `*mut mx_erased`
2064///
2065/// # Generated Code (Basic)
2066///
2067/// For a type `MyData` without traits:
2068///
2069/// ```ignore
2070/// impl TypedExternal for MyData {
2071///     const TYPE_NAME: &'static str = "MyData";
2072///     const TYPE_NAME_CSTR: &'static [u8] = b"MyData\0";
2073/// }
2074/// ```
2075#[proc_macro_derive(ExternalPtr, attributes(externalptr, r_data))]
2076pub fn derive_external_ptr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2077    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2078
2079    // Standalone `#[derive(ExternalPtr)]` always emits the `IntoExternalPtr`
2080    // marker (enabling the blanket `IntoR`); only the struct-level
2081    // `prefer = "native"` dispatch path suppresses it (#1283).
2082    externalptr_derive::derive_external_ptr(input, true)
2083        .unwrap_or_else(|e| e.into_compile_error())
2084        .into()
2085}
2086
2087/// Derive macro for ALTREP integer vector data types.
2088///
2089/// Auto-implements `AltrepLen`, `AltIntegerData`, and the low-level ALTREP
2090/// trait impls (`Altrep`, `AltVec`, `AltInteger`, `InferBase`).
2091///
2092/// # Attributes
2093///
2094/// - `#[altrep(len = "field_name")]` - Specify length field (auto-detects "len" or "length")
2095/// - `#[altrep(elt = "field_name")]` - For constant vectors, specify which field provides elements
2096/// - `#[altrep(dataptr)]` - Enable direct data-pointer access
2097/// - `#[altrep(serialize)]` - Enable ALTREP serialization support
2098/// - `#[altrep(subset)]` - Enable `Extract_subset` optimization
2099/// - `#[altrep(no_lowlevel)]` - Skip the automatic low-level trait impls
2100///
2101/// # Example (Constant Vector - Zero Boilerplate!)
2102///
2103/// ```ignore
2104/// #[derive(ExternalPtr, AltrepInteger)]
2105/// #[altrep(elt = "value")]  // All elements return this field
2106/// pub struct ConstantIntData {
2107///     value: i32,
2108///     len: usize,
2109/// }
2110///
2111/// // That's it! 3 lines instead of 30!
2112/// // AltrepLen, AltIntegerData, and low-level impls are auto-generated
2113///
2114/// #[miniextendr(class = "ConstantInt")]
2115/// pub struct ConstantIntClass(pub ConstantIntData);
2116/// ```
2117///
2118/// # Example (Custom elt() - Override One Method)
2119///
2120/// ```ignore
2121/// #[derive(ExternalPtr, AltrepInteger)]
2122/// pub struct ArithSeqData {
2123///     start: i32,
2124///     step: i32,
2125///     len: usize,
2126/// }
2127///
2128/// // Auto-generates AltrepLen and stub AltIntegerData
2129/// // Just override elt() for custom logic:
2130/// impl AltIntegerData for ArithSeqData {
2131///     fn elt(&self, i: usize) -> i32 {
2132///         self.start + (i as i32) * self.step
2133///     }
2134/// }
2135/// ```
2136#[proc_macro_derive(AltrepInteger, attributes(altrep))]
2137pub fn derive_altrep_integer(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2138    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2139    altrep_derive::derive_altrep_integer(input)
2140        .unwrap_or_else(|e| e.into_compile_error())
2141        .into()
2142}
2143
2144/// Derive macro for ALTREP real vector data types.
2145///
2146/// Auto-implements `AltrepLen` and `AltRealData` traits.
2147/// Supports the same `#[altrep(...)]` attributes as [`AltrepInteger`](derive@AltrepInteger).
2148#[proc_macro_derive(AltrepReal, attributes(altrep))]
2149pub fn derive_altrep_real(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2150    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2151    altrep_derive::derive_altrep_real(input)
2152        .unwrap_or_else(|e| e.into_compile_error())
2153        .into()
2154}
2155
2156/// Derive macro for ALTREP logical vector data types.
2157///
2158/// Auto-implements `AltrepLen` and `AltLogicalData` traits.
2159/// Supports the same `#[altrep(...)]` attributes as [`AltrepInteger`](derive@AltrepInteger).
2160#[proc_macro_derive(AltrepLogical, attributes(altrep))]
2161pub fn derive_altrep_logical(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2162    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2163    altrep_derive::derive_altrep_logical(input)
2164        .unwrap_or_else(|e| e.into_compile_error())
2165        .into()
2166}
2167
2168/// Derive macro for ALTREP raw vector data types.
2169///
2170/// Auto-implements `AltrepLen` and `AltRawData` traits.
2171/// Supports the same `#[altrep(...)]` attributes as [`AltrepInteger`](derive@AltrepInteger).
2172#[proc_macro_derive(AltrepRaw, attributes(altrep))]
2173pub fn derive_altrep_raw(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2174    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2175    altrep_derive::derive_altrep_raw(input)
2176        .unwrap_or_else(|e| e.into_compile_error())
2177        .into()
2178}
2179
2180/// Derive macro for ALTREP string vector data types.
2181///
2182/// Auto-implements `AltrepLen` and `AltStringData` traits.
2183/// Supports the same `#[altrep(...)]` attributes as [`AltrepInteger`](derive@AltrepInteger).
2184#[proc_macro_derive(AltrepString, attributes(altrep))]
2185pub fn derive_altrep_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2186    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2187    altrep_derive::derive_altrep_string(input)
2188        .unwrap_or_else(|e| e.into_compile_error())
2189        .into()
2190}
2191
2192/// Derive macro for ALTREP complex vector data types.
2193///
2194/// Auto-implements `AltrepLen` and `AltComplexData` traits.
2195/// Supports the same `#[altrep(...)]` attributes as [`AltrepInteger`](derive@AltrepInteger).
2196#[proc_macro_derive(AltrepComplex, attributes(altrep))]
2197pub fn derive_altrep_complex(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2198    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2199    altrep_derive::derive_altrep_complex(input)
2200        .unwrap_or_else(|e| e.into_compile_error())
2201        .into()
2202}
2203
2204/// Derive macro for ALTREP list vector data types.
2205///
2206/// Auto-implements `AltrepLen` and `AltListData` traits.
2207/// Supports the same `#[altrep(...)]` attributes as [`AltrepInteger`](derive@AltrepInteger),
2208/// except `dataptr` and `subset` which are not supported for list ALTREP.
2209#[proc_macro_derive(AltrepList, attributes(altrep))]
2210pub fn derive_altrep_list(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2211    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2212    altrep_derive::derive_altrep_list(input)
2213        .unwrap_or_else(|e| e.into_compile_error())
2214        .into()
2215}
2216
2217/// Derive ALTREP registration for a data struct.
2218///
2219/// Generates `TypedExternal`, `AltrepClass`, `RegisterAltrep`, `IntoR`,
2220/// linkme registration entry, and `Ref`/`Mut` accessor types.
2221///
2222/// The struct must already have low-level ALTREP traits implemented.
2223/// For most use cases, prefer a family-specific derive:
2224/// `#[derive(AltrepInteger)]`, `#[derive(AltrepReal)]`, etc.
2225/// Use `#[altrep(manual)]` on a family derive to skip data trait generation
2226/// when you provide your own `AltrepLen` + `Alt*Data` impls.
2227///
2228/// # Attributes
2229///
2230/// - `#[altrep(class = "Name")]` — custom ALTREP class name (defaults to struct name)
2231///
2232/// # Example
2233///
2234/// ```ignore
2235/// // Prefer family derives with manual:
2236/// #[derive(AltrepInteger)]
2237/// #[altrep(manual, class = "MyCustom", serialize)]
2238/// struct MyData { ... }
2239///
2240/// impl AltrepLen for MyData { ... }
2241/// impl AltIntegerData for MyData { ... }
2242/// ```
2243#[proc_macro_derive(Altrep, attributes(altrep))]
2244pub fn derive_altrep(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2245    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2246    altrep::derive_altrep(input)
2247        .unwrap_or_else(|e| e.into_compile_error())
2248        .into()
2249}
2250
2251/// Derive `IntoList` for a struct (Rust → R list).
2252///
2253/// - Named structs → named R list: `list(x = 1L, y = 2L)`
2254/// - Tuple structs → unnamed R list: `list(1L, 2L)`
2255/// - Fields annotated `#[into_list(ignore)]` are skipped
2256#[proc_macro_derive(IntoList, attributes(into_list))]
2257pub fn derive_into_list(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2258    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2259    list_derive::derive_into_list(input)
2260        .unwrap_or_else(|e| e.into_compile_error())
2261        .into()
2262}
2263
2264/// Derive `TryFromList` for a struct (R list → Rust).
2265///
2266/// - Named structs: extract by field name
2267/// - Tuple structs: extract by position (0, 1, 2, ...)
2268/// - Fields annotated `#[into_list(ignore)]` are not read and are initialized with `Default::default()`
2269#[proc_macro_derive(TryFromList, attributes(into_list))]
2270pub fn derive_try_from_list(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2271    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2272    list_derive::derive_try_from_list(input)
2273        .unwrap_or_else(|e| e.into_compile_error())
2274        .into()
2275}
2276
2277/// Derive `PreferList`: emits an `IntoR` impl selecting list as the type's default
2278/// Rust→R conversion (via `IntoList::into_list`).
2279///
2280/// A type carries exactly one representation default: stacking two `Prefer*`
2281/// derives is a compile error. Each `Prefer*` derive emits a fixed-name marker
2282/// const, so a second one triggers a guided `duplicate definitions with name
2283/// __miniextendr_conflicting_Prefer_derives__keep_ONE_or_use_call_site_As_wrappers`
2284/// error (alongside the raw conflicting-`IntoR`-impl error) — keep one `Prefer*`,
2285/// or drop them all and choose a representation per return value at the call site
2286/// with an `As*` wrapper (`AsList`, `AsExternalPtr`, `AsDataFrame`, ...).
2287///
2288/// # Example
2289///
2290/// ```ignore
2291/// #[derive(IntoList, PreferList)]
2292/// struct Config { verbose: bool, threads: i32 }
2293/// // IntoR produces list(verbose = TRUE, threads = 4L)
2294/// ```
2295#[proc_macro_derive(PreferList)]
2296pub fn derive_prefer_list(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2297    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2298    list_derive::derive_prefer_list(input)
2299        .unwrap_or_else(|e| e.into_compile_error())
2300        .into()
2301}
2302
2303/// Derive `PreferDataFrame`: when a type implements both `IntoDataFrame` (via `DataFrameRow`)
2304/// and other conversion paths, this selects data.frame as the default `IntoR` conversion.
2305///
2306/// # Example
2307///
2308/// ```ignore
2309/// #[derive(DataFrameRow, PreferDataFrame)]
2310/// struct Obs { time: f64, value: f64 }
2311/// // IntoR produces data.frame(time = ..., value = ...)
2312/// ```
2313#[proc_macro_derive(PreferDataFrame)]
2314pub fn derive_prefer_data_frame(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2315    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2316    list_derive::derive_prefer_data_frame(input)
2317        .unwrap_or_else(|e| e.into_compile_error())
2318        .into()
2319}
2320
2321/// Derive `PreferExternalPtr`: when a type implements both `ExternalPtr` and
2322/// other conversion paths (e.g., `IntoList`), this selects `ExternalPtr` wrapping
2323/// as the default `IntoR` conversion.
2324///
2325/// # Example
2326///
2327/// ```ignore
2328/// #[derive(ExternalPtr, IntoList, PreferExternalPtr)]
2329/// struct Model { weights: Vec<f64> }
2330/// // IntoR wraps as ExternalPtr (opaque R object), not list
2331/// ```
2332#[proc_macro_derive(PreferExternalPtr)]
2333pub fn derive_prefer_externalptr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2334    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2335    list_derive::derive_prefer_externalptr(input)
2336        .unwrap_or_else(|e| e.into_compile_error())
2337        .into()
2338}
2339
2340/// Derive `PreferRNativeType`: when a newtype wraps an `RNativeType` and also
2341/// implements other conversions, this selects the native R vector conversion
2342/// as the default `IntoR` path.
2343///
2344/// # Example
2345///
2346/// ```ignore
2347/// #[derive(Copy, Clone, RNativeType, PreferRNativeType)]
2348/// struct Meters(f64);
2349/// // IntoR produces a numeric scalar, not an ExternalPtr
2350/// ```
2351#[proc_macro_derive(PreferRNativeType)]
2352pub fn derive_prefer_rnative(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2353    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2354    list_derive::derive_prefer_rnative(input)
2355        .unwrap_or_else(|e| e.into_compile_error())
2356        .into()
2357}
2358
2359/// Derive `PreferVctrs`: emits an `IntoR` impl converting the type to its R vctrs object via
2360/// `IntoVctrs::into_vctrs`.
2361///
2362/// Pair with `#[derive(Vctrs)]` (which supplies `IntoVctrs`) so the type can be returned
2363/// directly from `#[miniextendr]` functions instead of `value.into_vctrs().map_err(...)`.
2364///
2365/// # Example
2366///
2367/// ```ignore
2368/// #[derive(Vctrs, PreferVctrs)]
2369/// #[vctrs(class = "percent", base = "double")]
2370/// struct Percent { #[vctrs(data)] values: Vec<f64> }
2371/// // IntoR builds the `percent` vctrs vector; a build failure becomes an R error.
2372/// ```
2373#[cfg(feature = "vctrs")]
2374#[proc_macro_derive(PreferVctrs)]
2375pub fn derive_prefer_vctrs(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2376    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2377    list_derive::derive_prefer_vctrs(input)
2378        .unwrap_or_else(|e| e.into_compile_error())
2379        .into()
2380}
2381
2382/// Derive `DataFrameRow`: generates a companion `*DataFrame` type with collection fields,
2383/// plus `IntoR` / `TryFromSexp` / `IntoDataFrame` impls for seamless R data.frame conversion.
2384///
2385/// # Example
2386///
2387/// ```ignore
2388/// #[derive(DataFrameRow)]
2389/// struct Measurement {
2390///     time: f64,
2391///     value: f64,
2392/// }
2393///
2394/// // Generates MeasurementDataFrame { time: Vec<f64>, value: Vec<f64> }
2395/// // plus conversion impls
2396/// ```
2397///
2398/// # Struct-level attributes
2399///
2400/// - `#[dataframe(name = "CustomDf")]` — custom name for the generated DataFrame type
2401/// - `#[dataframe(align)]` — pad shorter columns with NA to match longest
2402/// - `#[dataframe(tag = "my_tag")]` — attach a tag attribute to the data.frame
2403/// - `#[dataframe(conflicts = "string")]` — resolve conflicting column types as strings
2404///
2405/// # Field-level attributes
2406///
2407/// - `#[dataframe(skip)]` — omit this field from the DataFrame
2408/// - `#[dataframe(rename = "col")]` — custom column name
2409/// - `#[dataframe(as_list)]` — keep collection as single list column (no expansion)
2410/// - `#[dataframe(expand)]` / `#[dataframe(unnest)]` — expand collection into suffixed columns
2411/// - `#[dataframe(width = N)]` — pin expansion width (shorter rows get NA)
2412///
2413/// # Public surface (which verbs to call)
2414///
2415/// Every capability the derive provides has a documented, trait-based (or `std`)
2416/// verb — reach for these, not any incidental inherent plumbing:
2417///
2418/// - **Rows → R `data.frame`**: `rows.into_dataframe()?` (owned, GC-rooted
2419///   `BuiltDataFrame`) or `rows.wrap_data_frame()` (deferred `IntoR` wrapper);
2420///   parallel variant `rows.into_dataframe_par()?`. From the `IntoDataFrame` /
2421///   `AsDataFrameExt` traits (both re-exported from `miniextendr_api::prelude`).
2422/// - **R `data.frame` → rows**: `Vec::<Row>::from_dataframe(&df)?` (parallel:
2423///   `Vec::<Row>::from_dataframe_par(&df)?`), from the `FromDataFrame` trait — or
2424///   the one-call `Row::try_from_dataframe(sexp)` reader on the row type.
2425/// - **Rows ↔ the pure-Rust columnar companion** (`<Row>DataFrame`, `Vec`-columns,
2426///   no R involved): the `ColumnarFrame` trait (in the prelude) —
2427///   `<Row>DataFrame::from_rows(rows)` / `from_rows_par(rows)` (parallel build of
2428///   the *companion*, which `into_dataframe_par` does not give you) and, for
2429///   row-iterable companions, `companion.into_rows()`. `Vec<Row>: Into<companion>`
2430///   and the companion's `IntoIterator` are the equivalent `std` verbs.
2431/// - **Enum split representation**: `rows.into_dataframe_split()` returns one
2432///   `data.frame` per variant as an R list (only that variant's columns — no NA
2433///   fill), from the `IntoDataFrameSplit` trait (in the prelude). Enum rows
2434///   only; struct derives don't partition.
2435///
2436/// The generated `<Row>DataFrame` / `<Row>DataFrameIter` types are intermediate
2437/// column-oriented companions; you rarely name them directly.
2438#[proc_macro_derive(DataFrameRow, attributes(dataframe))]
2439pub fn derive_dataframe_row(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2440    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2441    dataframe_derive::derive_dataframe_row(input)
2442        .unwrap_or_else(|e| e.into_compile_error())
2443        .into()
2444}
2445
2446/// Derive `RFactor`: enables conversion between Rust enums and R factors.
2447///
2448/// # Usage
2449///
2450/// ```ignore
2451/// #[derive(Copy, Clone, RFactor)]
2452/// enum Color {
2453///     Red,
2454///     Green,
2455///     Blue,
2456/// }
2457/// ```
2458///
2459/// # Attributes
2460///
2461/// - `#[r_factor(rename = "name")]` - Rename a variant's level string
2462/// - `#[r_factor(rename_all = "snake_case")]` - Rename all variants (snake_case, kebab-case, lower, upper)
2463#[proc_macro_derive(RFactor, attributes(r_factor))]
2464pub fn derive_r_factor(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2465    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2466    factor_derive::derive_r_factor(input)
2467        .unwrap_or_else(|e| e.into_compile_error())
2468        .into()
2469}
2470
2471/// Derive `MatchArg`: enables conversion between Rust enums and R character strings
2472/// with `match.arg` semantics (partial matching, informative errors).
2473///
2474/// # Usage
2475///
2476/// ```ignore
2477/// #[derive(Copy, Clone, MatchArg)]
2478/// enum Mode {
2479///     Fast,
2480///     Safe,
2481///     Debug,
2482/// }
2483/// ```
2484///
2485/// # Attributes
2486///
2487/// - `#[match_arg(rename = "name")]` - Rename a variant's choice string
2488/// - `#[match_arg(rename_all = "snake_case")]` - Rename all variants (snake_case, kebab-case, lower, upper)
2489///
2490/// # Generated Implementations
2491///
2492/// - `MatchArg` - Choice metadata and bidirectional conversion
2493/// - `TryFromSexp` - Convert R STRSXP/factor to enum (with partial matching)
2494/// - `IntoR` - Convert enum to R character scalar
2495#[proc_macro_derive(MatchArg, attributes(match_arg))]
2496pub fn derive_match_arg(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2497    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2498    match_arg_derive::derive_match_arg(input)
2499        .unwrap_or_else(|e| e.into_compile_error())
2500        .into()
2501}
2502
2503/// Derive `TryFromSexp` for a single-field newtype: forward the R → Rust
2504/// conversion to the inner type.
2505///
2506/// Generates a scalar `TryFromSexp` impl that delegates to the inner type (so the
2507/// newtype inherits its exact SEXPTYPE checks, NA policy, and error text), plus a
2508/// `FromRNewtype` marker impl. The marker lets `miniextendr-api`'s container
2509/// blankets light up `Vec<T>` / `Option<T>` / `Vec<Option<T>>` automatically.
2510///
2511/// # Usage
2512///
2513/// ```ignore
2514/// use uuid::Uuid;
2515///
2516/// #[derive(TryFromSexp)]            // R -> Rust only
2517/// struct Pattern(regex::Regex);
2518///
2519/// #[derive(TryFromSexp, IntoR)]     // round-trip; Vec/Option containers work too
2520/// struct UserId(Uuid);
2521/// ```
2522///
2523/// Direction is chosen by which derive you list — derive only `TryFromSexp` for
2524/// inner types that read from R but cannot be written back (e.g. `regex::Regex`).
2525#[proc_macro_derive(TryFromSexp)]
2526pub fn derive_try_from_sexp(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2527    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2528    newtype_derive::derive_try_from_sexp(input)
2529        .unwrap_or_else(|e| e.into_compile_error())
2530        .into()
2531}
2532
2533/// Derive `IntoR` for a single-field newtype: forward the Rust → R conversion to
2534/// the inner type.
2535///
2536/// Generates a scalar `IntoR` impl that delegates to the inner type, plus an
2537/// `IntoRNewtype` marker (powering the `Option<T>` / `Vec<Option<T>>` container
2538/// blankets) and a concrete `IntoRVecElement` impl (powering `Vec<T>`). See
2539/// `#[derive(TryFromSexp)]` for usage.
2540///
2541/// Do not derive both `IntoR` and `MatchArg` on the same type: both feed the
2542/// single `IntoR for Vec<T>` blanket slot and would collide (E0119).
2543#[proc_macro_derive(IntoR)]
2544pub fn derive_into_r(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2545    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2546    newtype_derive::derive_into_r(input)
2547        .unwrap_or_else(|e| e.into_compile_error())
2548        .into()
2549}
2550
2551/// Derive `Vctrs`: enables creating vctrs-compatible S3 vector classes from Rust structs.
2552///
2553/// # Usage
2554///
2555/// ```ignore
2556/// #[derive(Vctrs)]
2557/// #[vctrs(class = "percent", base = "double")]
2558/// pub struct Percent {
2559///     data: Vec<f64>,
2560/// }
2561/// ```
2562///
2563/// # Attributes
2564///
2565/// - `#[vctrs(class = "name")]` - R class name (required)
2566/// - `#[vctrs(base = "type")]` - Base type: double, integer, logical, character, raw, list, record
2567/// - `#[vctrs(abbr = "abbr")]` - Abbreviation for `vec_ptype_abbr`
2568/// - `#[vctrs(inherit_base = true|false)]` - Whether to include base type in class vector
2569///
2570/// # Generated Implementations
2571///
2572/// - `VctrsClass` - Metadata trait for vctrs class information
2573/// - `VctrsRecord` (for `base = "record"`) - Field names for record types
2574#[cfg(feature = "vctrs")]
2575#[proc_macro_derive(Vctrs, attributes(vctrs))]
2576pub fn derive_vctrs(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2577    let input = syn::parse_macro_input!(input as syn::DeriveInput);
2578    vctrs_derive::derive_vctrs(input)
2579        .unwrap_or_else(|e| e.into_compile_error())
2580        .into()
2581}
2582
2583/// Create a `TypedListSpec` for validating `...` arguments or lists.
2584///
2585/// This macro provides ergonomic syntax for defining typed list specifications
2586/// that can be used with `Dots::typed()` to validate the structure of
2587/// `...` arguments passed from R.
2588///
2589/// # Syntax
2590///
2591/// ```text
2592/// typed_list!(
2593///     name => type_spec,    // required field with type
2594///     name? => type_spec,   // optional field with type
2595///     name,                 // required field, any type
2596///     name?,                // optional field, any type
2597/// )
2598/// ```
2599///
2600/// For strict mode (no extra fields allowed):
2601/// ```text
2602/// typed_list!(@exact; name => type_spec, ...)
2603/// ```
2604///
2605/// # Type Specifications
2606///
2607/// ## Base types (with optional length)
2608/// - `numeric()` / `numeric(4)` - Real/double vector
2609/// - `integer()` / `integer(4)` - Integer vector
2610/// - `logical()` / `logical(4)` - Logical vector
2611/// - `character()` / `character(4)` - Character vector
2612/// - `raw()` / `raw(4)` - Raw vector
2613/// - `complex()` / `complex(4)` - Complex vector
2614/// - `list()` / `list(4)` - List (VECSXP)
2615///
2616/// ## Special types
2617/// - `data_frame()` - Data frame
2618/// - `factor()` - Factor
2619/// - `matrix()` - Matrix
2620/// - `array()` - Array
2621/// - `function()` - Function
2622/// - `environment()` - Environment
2623/// - `null()` - NULL only
2624/// - `any()` - Any type
2625///
2626/// ## String literals
2627/// - `"numeric"`, `"integer"`, etc. - Same as call syntax
2628/// - `"data.frame"` - Data frame (alias)
2629/// - `"MyClass"` - Any other string is treated as a class name (uses `Rf_inherits`)
2630///
2631/// # Examples
2632///
2633/// ## Basic usage
2634///
2635/// ```ignore
2636/// use miniextendr_api::{miniextendr, typed_list, Dots};
2637///
2638/// #[miniextendr]
2639/// pub fn process_args(dots: ...) -> Result<i32, String> {
2640///     let args = dots.typed(typed_list!(
2641///         alpha => numeric(4),
2642///         beta => list(),
2643///         gamma? => "character",
2644///     )).map_err(|e| e.to_string())?;
2645///
2646///     let alpha: Vec<f64> = args.get("alpha").map_err(|e| e.to_string())?;
2647///     Ok(alpha.len() as i32)
2648/// }
2649/// ```
2650///
2651/// ## Strict mode
2652///
2653/// ```ignore
2654/// // Reject any extra named fields
2655/// let args = dots.typed(typed_list!(@exact;
2656///     x => numeric(),
2657///     y => numeric(),
2658/// ))?;
2659/// ```
2660///
2661/// ## Class checking
2662///
2663/// ```ignore
2664/// // Check for specific R class (uses Rf_inherits semantics)
2665/// let args = dots.typed(typed_list!(
2666///     data => "data.frame",
2667///     model => "lm",
2668/// ))?;
2669/// ```
2670///
2671/// ## Attribute sugar
2672///
2673/// Instead of calling `.typed()` manually, you can use `typed_list!` directly in the
2674/// `#[miniextendr]` attribute for automatic validation:
2675///
2676/// ```ignore
2677/// #[miniextendr(dots = typed_list!(x => numeric(), y => numeric()))]
2678/// pub fn my_func(...) -> String {
2679///     // `dots_typed` is automatically created and validated
2680///     let x: f64 = dots_typed.get("x").expect("x");
2681///     let y: f64 = dots_typed.get("y").expect("y");
2682///     format!("x={}, y={}", x, y)
2683/// }
2684/// ```
2685///
2686/// This injects validation at the start of the function body:
2687/// ```ignore
2688/// let dots_typed = _dots.typed(typed_list!(...))
2689///     .unwrap_or_else(|e| panic!("dots validation failed: {e}"));
2690/// ```
2691///
2692/// See the [`#[miniextendr]`](macro@miniextendr) attribute documentation for more details.
2693///
2694#[proc_macro]
2695pub fn typed_list(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2696    let parsed = syn::parse_macro_input!(input as typed_list::TypedListInput);
2697    typed_list::expand_typed_list(parsed).into()
2698}
2699
2700/// Define a compile-time-validated wrapper for an R `data.frame` input.
2701///
2702/// `typed_dataframe!` mirrors [`typed_list!`] for the data.frame shape:
2703/// declare the columns once, get a struct that implements `TryFromSexp`
2704/// (validating both the `data.frame` class and per-column SEXPTYPE) plus
2705/// per-column borrowed accessors that return `&[T]`.
2706///
2707/// # Syntax
2708///
2709/// ```ignore
2710/// typed_dataframe! {
2711///     /// The shape we accept for the Theoph PK dataset.
2712///     pub TheophDf {
2713///         subject: i32,
2714///         weight: f64,
2715///         dose: f64,
2716///         flag: Option<i32>,   // optional column
2717///     }
2718/// }
2719/// ```
2720///
2721/// For strict mode (reject any column not declared):
2722/// ```ignore
2723/// typed_dataframe! {
2724///     @exact;
2725///     pub Strict { x: i32 }
2726/// }
2727/// ```
2728///
2729/// # Supported element types
2730///
2731/// v1 supports column element types that implement
2732/// `miniextendr_api::RNativeType`:
2733///
2734/// - `i32` — `INTSXP`
2735/// - `f64` — `REALSXP`
2736/// - `u8` — `RAWSXP`
2737/// - `miniextendr_api::RLogical` — `LGLSXP`
2738/// - `miniextendr_api::Rcomplex` — `CPLXSXP`
2739///
2740/// `String`/`&str` column types are not yet supported (character vectors
2741/// don't expose a contiguous slice). `bool` is also not yet supported as
2742/// a direct field type — use `RLogical` and convert per-element, or
2743/// follow the open follow-up issues from PR #698.
2744///
2745/// # Generated API
2746///
2747/// For each `name: T` column the macro emits:
2748/// - `pub fn name(&self) -> &[T]` (required)
2749/// - `pub fn name(&self) -> Option<&[T]>` (optional, `Option<T>`)
2750///
2751/// Plus housekeeping:
2752/// - `pub fn nrow(&self) -> usize`
2753/// - `pub fn ncol(&self) -> usize` (count of *declared* columns)
2754/// - `pub fn as_sexp(&self) -> SEXP`
2755///
2756/// All borrowed accessors are bound to `&self`; the SEXP is protected
2757/// by the surrounding `#[miniextendr]` call wrapper while the struct is
2758/// alive.
2759///
2760/// # Error reporting
2761///
2762/// `TryFromSexp::try_from_sexp` batches every per-column error into a
2763/// single `SexpError::InvalidValue`, so the R user sees one diagnostic
2764/// covering all missing or wrong-typed columns rather than a sequence of
2765/// stop-on-first-failure messages.
2766///
2767/// # Example
2768///
2769/// ```ignore
2770/// use miniextendr_api::{miniextendr, typed_dataframe};
2771///
2772/// typed_dataframe! {
2773///     pub TheophDf {
2774///         subject: i32,
2775///         weight: f64,
2776///         dose: f64,
2777///     }
2778/// }
2779///
2780/// #[miniextendr]
2781/// pub fn theoph_nrow(df: TheophDf) -> i32 {
2782///     // df.subject() -> &[i32], df.weight() -> &[f64]
2783///     // Lengths are guaranteed equal across columns (data.frame invariant).
2784///     df.nrow() as i32
2785/// }
2786/// ```
2787///
2788/// [`typed_list!`]: macro@typed_list
2789#[proc_macro]
2790pub fn typed_dataframe(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2791    let parsed = syn::parse_macro_input!(input as typed_dataframe::TypedDataframeInput);
2792    typed_dataframe::expand_typed_dataframe(parsed).into()
2793}
2794
2795/// Construct an R list from Rust values.
2796///
2797/// This macro provides a convenient way to create R lists in Rust code,
2798/// using R-like syntax. Values are converted to R objects via the [`IntoR`] trait.
2799///
2800/// # Syntax
2801///
2802/// ```ignore
2803/// // Named entries (like R's list())
2804/// list!(
2805///     alpha = 1,
2806///     beta = "hello",
2807///     "my-name" = vec![1, 2, 3],
2808/// )
2809///
2810/// // Unnamed entries
2811/// list!(1, "hello", vec![1, 2, 3])
2812///
2813/// // Mixed (unnamed entries get empty string names)
2814/// list!(alpha = 1, 2, beta = "hello")
2815///
2816/// // Empty list
2817/// list!()
2818/// ```
2819///
2820/// # Examples
2821///
2822/// ```ignore
2823/// use miniextendr_api::{list, IntoR};
2824///
2825/// // Create a named list
2826/// let my_list = list!(
2827///     x = 42,
2828///     y = "hello world",
2829///     z = vec![1.0, 2.0, 3.0],
2830/// );
2831///
2832/// // In R this is equivalent to:
2833/// // list(x = 42L, y = "hello world", z = c(1, 2, 3))
2834/// ```
2835///
2836/// [`IntoR`]: https://docs.rs/miniextendr-api/latest/miniextendr_api/into_r/trait.IntoR.html
2837#[proc_macro]
2838pub fn list(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2839    let parsed = syn::parse_macro_input!(input as list_macro::ListInput);
2840    list_macro::expand_list(parsed).into()
2841}
2842
2843/// Evaluate R code written as **Rust tokens**, validated at compile time.
2844///
2845/// `r!` takes a single R expression as a token stream, `stringify!`s it into a
2846/// static R source string at build time, and evaluates it via
2847/// `miniextendr_api::expression::r_eval_str` (the same protect-safe parse + eval
2848/// path as `r_str!`).
2849///
2850/// # What you get today
2851///
2852/// Because the argument is a Rust token tree, the Rust front-end already
2853/// rejects **unbalanced delimiters** (`r!(f(1, 2)` won't compile) and
2854/// lexically invalid tokens before R ever sees the string — a cheap
2855/// compile-time guard over the pure-runtime `r_str!`. The source is lowered to
2856/// a `&'static str` (`stringify!`), so there is no `format!` allocation at the
2857/// call site.
2858///
2859/// This proc-macro additionally validates a conservative subset of known-bad
2860/// R syntax constructs (trailing binary operators, consecutive non-unary
2861/// binary operators, bare `if`/`while`/`for` without a body, etc.) and emits
2862/// a precise compile error pointing at the offending token. Empty (missing)
2863/// call arguments — `f(, x)`, `matrix(, 2, 2)` — are valid R and pass.
2864///
2865/// # What is deferred
2866///
2867/// Direct `Rf_lang*` call-tree lowering (skipping the runtime parser entirely)
2868/// is tracked as a follow-up in issue #938 (item 2). Until then `r!` parses
2869/// its static string at first evaluation, exactly like `r_str!`.
2870///
2871/// # Non-goals
2872///
2873/// A complete R grammar validator is not achievable over Rust tokens:
2874/// - Single-quoted strings (`'hello'`) and backtick-quoted names (`` `foo` ``)
2875///   already die at the Rust lexer — nothing to validate.
2876/// - `%op%` tokenises as `%`, ident, `%` and is accepted without analysis.
2877/// - Anything the validator cannot confidently classify as wrong passes through
2878///   unvalidated (conservative reject-only-known-bad design).
2879///
2880/// # Forms
2881///
2882/// - `r!(R tokens…)` — evaluate in `R_GlobalEnv`.
2883/// - `r!(env: e; R tokens…)` — evaluate in the environment SEXP `e`. The
2884///   leading `env: <expr> ;` is consumed as Rust, the rest is R source.
2885///
2886/// Both evaluate to `Result<SEXP, String>`; the `SEXP` is **unprotected**.
2887///
2888/// # Safety
2889///
2890/// Expands to an `unsafe` block; the underlying FFI is `#[r_ffi_checked]`, so
2891/// calls from a worker thread are serialized onto the R thread.
2892///
2893/// # Example
2894///
2895/// ```ignore
2896/// let three = r!(1L + 2L)?;
2897/// let rows = r!(getFromNamespace(".theoph_rows", "dataframeflows")())?;
2898/// let in_env = r!(env: my_env; x + 1)?;
2899/// ```
2900#[proc_macro]
2901pub fn r(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2902    r_macro::expand(input)
2903}
2904
2905/// Internal proc macro used by TPIE (Trait-Provided Impl Expansion).
2906///
2907/// Called by `__mx_impl_<Trait>!` macro_rules macros generated by `#[miniextendr]` on traits.
2908/// Do not call directly.
2909#[proc_macro]
2910#[doc(hidden)]
2911pub fn __mx_trait_impl_expand(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2912    miniextendr_impl_trait::expand_tpie(input)
2913}
2914
2915/// Generate `TypedExternal` and `IntoExternalPtr` impls for a concrete monomorphization
2916/// of a generic type.
2917///
2918/// Since `#[derive(ExternalPtr)]` rejects generic types, use this macro to generate
2919/// the necessary impls for a specific type instantiation.
2920///
2921/// # Example
2922///
2923/// ```ignore
2924/// struct Wrapper<T> { inner: T }
2925///
2926/// impl_typed_external!(Wrapper<i32>);
2927/// impl_typed_external!(Wrapper<String>);
2928/// ```
2929#[proc_macro]
2930pub fn impl_typed_external(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2931    match typed_external_macro::impl_typed_external(input.into()) {
2932        Ok(tokens) => tokens.into(),
2933        Err(err) => err.into_compile_error().into(),
2934    }
2935}
2936
2937/// Generate the `R_init_*` entry point for a miniextendr R package.
2938///
2939/// This macro consolidates all package initialization into a single line.
2940/// It generates an `extern "C-unwind"` function that R calls when loading
2941/// the shared library.
2942///
2943/// # Usage
2944///
2945/// ```ignore
2946/// // Auto-detects package name from CARGO_CRATE_NAME (recommended):
2947/// miniextendr_api::miniextendr_init!();
2948///
2949/// // Or specify explicitly (for edge cases):
2950/// miniextendr_api::miniextendr_init!(mypkg);
2951/// ```
2952///
2953/// The generated function calls `miniextendr_api::init::package_init` which
2954/// handles panic hooks, runtime init, locale assertion, ALTREP setup, trait ABI
2955/// registration, routine registration, and symbol locking.
2956#[proc_macro]
2957pub fn miniextendr_init(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
2958    let pkg_name: syn::Ident = if input.is_empty() {
2959        // Auto-detect from CARGO_CRATE_NAME (set by cargo during compilation).
2960        // Cargo normalizes hyphens → underscores, so this is almost always a
2961        // valid Rust/C identifier. Still parse through syn so malformed values
2962        // surface as a compile error rather than an ICE.
2963        let name = match std::env::var("CARGO_CRATE_NAME") {
2964            Ok(n) => n,
2965            Err(_) => {
2966                return syn::Error::new(
2967                    proc_macro2::Span::call_site(),
2968                    "CARGO_CRATE_NAME not set. Either pass the package name explicitly: \
2969                     miniextendr_init!(mypkg), or ensure you're building with cargo.",
2970                )
2971                .into_compile_error()
2972                .into();
2973            }
2974        };
2975        match syn::parse_str::<syn::Ident>(&name) {
2976            Ok(id) => id,
2977            Err(_) => {
2978                return syn::Error::new(
2979                    proc_macro2::Span::call_site(),
2980                    format!(
2981                        "CARGO_CRATE_NAME `{name}` is not a valid C identifier; \
2982                         R_init_<pkg> must match `[A-Za-z_][A-Za-z0-9_]*`. \
2983                         Pass the name explicitly: miniextendr_init!(my_pkg)."
2984                    ),
2985                )
2986                .into_compile_error()
2987                .into();
2988            }
2989        }
2990    } else {
2991        syn::parse_macro_input!(input as syn::Ident)
2992    };
2993    let fn_name = syn::Ident::new(&format!("R_init_{}", pkg_name), pkg_name.span());
2994    let unload_name = syn::Ident::new(&format!("R_unload_{}", pkg_name), pkg_name.span());
2995
2996    // Build a byte string literal with NUL terminator for the package name.
2997    let mut name_bytes = pkg_name.to_string().into_bytes();
2998    name_bytes.push(0);
2999    let byte_lit = syn::LitByteStr::new(&name_bytes, pkg_name.span());
3000
3001    let expanded = quote::quote! {
3002        // wasm32: pull in the host-generated `wasm_registry.rs` snapshot
3003        // (committed by the user crate, regenerated by `just wasm-prepare`).
3004        // The path is relative to the file invoking `miniextendr_init!()` —
3005        // by convention `<crate>/src/rust/lib.rs`, so the snapshot sits at
3006        // `<crate>/src/rust/wasm_registry.rs`. Module is `#[doc(hidden)]`
3007        // because it's purely an internal bridge between the user crate's
3008        // wrapper / vtable / register-fn `#[no_mangle]` exports and
3009        // `miniextendr_api::registry::install_wasm_runtime_slices`.
3010        #[cfg(target_arch = "wasm32")]
3011        #[path = "wasm_registry.rs"]
3012        #[doc(hidden)]
3013        mod __miniextendr_wasm_registry;
3014
3015        #[unsafe(no_mangle)]
3016        pub unsafe extern "C-unwind" fn #fn_name(
3017            dll: *mut ::miniextendr_api::sys::DllInfo,
3018        ) {
3019            // wasm32: install the pre-generated runtime tables before
3020            // package_init runs. linkme didn't gather anything (the slices
3021            // are OnceLock-backed on wasm32), so register_routines /
3022            // universal_query would otherwise see empty slices.
3023            #[cfg(target_arch = "wasm32")]
3024            ::miniextendr_api::registry::install_wasm_runtime_slices(
3025                __miniextendr_wasm_registry::MX_CALL_DEFS_WASM,
3026                __miniextendr_wasm_registry::MX_ALTREP_REGISTRATIONS_WASM,
3027                __miniextendr_wasm_registry::MX_TRAIT_DISPATCH_WASM,
3028            );
3029
3030            unsafe {
3031                // SAFETY: byte literal is a valid NUL-terminated string produced by the macro.
3032                let pkg_name = ::std::ffi::CStr::from_bytes_with_nul_unchecked(#byte_lit);
3033                ::miniextendr_api::init::package_init(dll, pkg_name);
3034            }
3035        }
3036
3037        /// R_unload_<pkg> entry point — R calls this on `detach(unload=TRUE)` /
3038        /// `dyn.unload()`. Signals the miniextendr worker thread (if enabled)
3039        /// to exit cleanly. See `#103`.
3040        #[unsafe(no_mangle)]
3041        pub unsafe extern "C-unwind" fn #unload_name(
3042            _dll: *mut ::miniextendr_api::sys::DllInfo,
3043        ) {
3044            ::miniextendr_api::worker::miniextendr_runtime_shutdown();
3045        }
3046
3047        /// Linker anchor: stub.c takes the address of this symbol to force the
3048        /// linker to pull in the user crate's archive member from the staticlib.
3049        /// With codegen-units = 1, this single member contains all linkme
3050        /// distributed_slice entries. The name is package-independent so stub.c
3051        /// doesn't need configure substitution.
3052        ///
3053        /// Defined as a function rather than a static so it stays exported under
3054        /// the webR wasm RUSTFLAG -Zdefault-visibility=hidden, which keeps
3055        /// no_mangle functions exported (like the R_init entry point) but hides
3056        /// no_mangle statics. A hidden anchor breaks wasm side-module dlopen
3057        /// (bad export type, undefined). See miniextendr webR notes (#494).
3058        #[unsafe(no_mangle)]
3059        pub extern "C" fn miniextendr_force_link() {}
3060    };
3061
3062    expanded.into()
3063}
3064
3065#[cfg(test)]
3066mod tests;