Skip to main content

miniextendr_macros/
c_wrapper_builder.rs

1//! Unified C wrapper generation for standalone functions and impl methods.
2//!
3//! This module provides shared infrastructure for generating C wrappers that:
4//! - Run on R's main thread inside `with_r_unwind_protect`
5//! - Perform parameter conversion from SEXP to Rust types
6//! - Convert Rust return values back to SEXP
7//! - Properly handle panics and R errors
8//!
9//! The same infrastructure is used by both `#[miniextendr]` on standalone functions
10//! and `#[miniextendr(env|r6|s3|s4|s7)]` on impl blocks.
11
12use proc_macro2::TokenStream;
13use quote::{format_ident, quote};
14
15/// Strategy for converting a Rust return value into an R `SEXP`.
16///
17/// Determined automatically by [`detect_return_handling`] from the function's return type,
18/// or set explicitly via [`CWrapperContextBuilder::return_handling`]. Each variant
19/// handles a different return type pattern, controlling how the C wrapper converts
20/// the Rust value back to R and how errors/None values are surfaced.
21///
22/// Every conversion of a value goes through [`return_conversion`]:
23/// `IntoR::try_into_sexp`, with a failed conversion raised as a classed R
24/// error (#2272).
25#[derive(#[automatically_derived]impl ::core::fmt::Debug for ReturnHandling {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "Unit RawSexp ExternalPtr SelfHandle SelfHandleResult SelfHandleOption IntoR OptionUnit OptionSexp OptionIntoR OptionClassPayload OptionExternalPtr ResultUnit ResultSexp ResultIntoR ResultNullOnErr ResultExternalPtr AsListOf AsExternalPtrOf AsNativeOf",
            match self {
                ReturnHandling::Unit => 0usize,
                ReturnHandling::RawSexp => 5usize,
                ReturnHandling::ExternalPtr => 13usize,
                ReturnHandling::SelfHandle => 25usize,
                ReturnHandling::SelfHandleResult => 36usize,
                ReturnHandling::SelfHandleOption => 53usize,
                ReturnHandling::IntoR => 70usize,
                ReturnHandling::OptionUnit => 76usize,
                ReturnHandling::OptionSexp => 87usize,
                ReturnHandling::OptionIntoR => 98usize,
                ReturnHandling::OptionClassPayload => 110usize,
                ReturnHandling::OptionExternalPtr => 129usize,
                ReturnHandling::ResultUnit => 147usize,
                ReturnHandling::ResultSexp => 158usize,
                ReturnHandling::ResultIntoR => 169usize,
                ReturnHandling::ResultNullOnErr => 181usize,
                ReturnHandling::ResultExternalPtr => 197usize,
                ReturnHandling::AsListOf => 215usize,
                ReturnHandling::AsExternalPtrOf => 224usize,
                ReturnHandling::AsNativeOf => 240usize,
            })
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for ReturnHandling {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Unit => ReturnHandling::Unit,
            Self::RawSexp => ReturnHandling::RawSexp,
            Self::ExternalPtr => ReturnHandling::ExternalPtr,
            Self::SelfHandle => ReturnHandling::SelfHandle,
            Self::SelfHandleResult => ReturnHandling::SelfHandleResult,
            Self::SelfHandleOption => ReturnHandling::SelfHandleOption,
            Self::IntoR => ReturnHandling::IntoR,
            Self::OptionUnit => ReturnHandling::OptionUnit,
            Self::OptionSexp => ReturnHandling::OptionSexp,
            Self::OptionIntoR => ReturnHandling::OptionIntoR,
            Self::OptionClassPayload => ReturnHandling::OptionClassPayload,
            Self::OptionExternalPtr => ReturnHandling::OptionExternalPtr,
            Self::ResultUnit => ReturnHandling::ResultUnit,
            Self::ResultSexp => ReturnHandling::ResultSexp,
            Self::ResultIntoR => ReturnHandling::ResultIntoR,
            Self::ResultNullOnErr => ReturnHandling::ResultNullOnErr,
            Self::ResultExternalPtr => ReturnHandling::ResultExternalPtr,
            Self::AsListOf => ReturnHandling::AsListOf,
            Self::AsExternalPtrOf => ReturnHandling::AsExternalPtrOf,
            Self::AsNativeOf => ReturnHandling::AsNativeOf,
        }
    }
}Clone)]
26pub enum ReturnHandling {
27    /// Returns unit type `()` -- emits `R_NilValue`.
28    Unit,
29    /// Returns raw `SEXP` -- passes the value through unchanged (no conversion).
30    RawSexp,
31    /// Returns `Self` -- wraps the value in an `ExternalPtr` via `ExternalPtr::new`.
32    ExternalPtr,
33    /// Returns `&Self` / `&mut Self` (an in-place builder) -- evaluates the call
34    /// for its side effect (the mutation already happened through `&mut self`),
35    /// discards the returned borrow, and returns the *same* `self_sexp` handle
36    /// unchanged. This gives R in-place value semantics with no clone: the R
37    /// object the user piped in is returned verbatim, wrapping the now-mutated
38    /// Rust value. Only valid for instance methods (requires `self_sexp`).
39    SelfHandle,
40    /// Fallible in-place step whose call expression yields `Result<(), E>`
41    /// (`&mut self -> Result<&mut Self, E>`, or `self -> Result<Self, E>` after
42    /// the write-back closure): raise on `Err`, return the same `self_sexp`
43    /// handle on `Ok` (#1432, #1433).
44    SelfHandleResult,
45    /// `Option` sibling of [`SelfHandleResult`](Self::SelfHandleResult): the
46    /// call yields `Option<()>`; `NULL` on `None`, as every `Option` return
47    /// gives, and the same handle on `Some`.
48    SelfHandleOption,
49    /// Returns an arbitrary type `T: IntoR` -- converts it ([`return_conversion`]).
50    IntoR,
51    /// Returns `Option<()>` -- raises an error on `None`, otherwise emits `R_NilValue`.
52    OptionUnit,
53    /// Returns `Option<SEXP>` -- raises an error on `None`, otherwise passes through.
54    OptionSexp,
55    /// Returns `Option<T>` -- converts the whole `Option` through its `IntoR`, so `None`
56    /// becomes whatever `IntoR for Option<T>` gives: `NULL` for containers, references
57    /// and pointers, a typed `NA` for scalars. This is the one rule for an `Option<T>`
58    /// return from a standalone function, an inherent method and a trait method
59    /// (#1415, #2088); [`detect_return_handling`] picks it for every `Option<T>` but
60    /// the shapes below.
61    OptionIntoR,
62    /// Returns `Option<T>` under an explicit class wrap (`Option<WrapAs*<T>>` or
63    /// `wrap = "..."`): `Some` converts the class payload through `T: IntoR`, `None`
64    /// is `NULL`, as `IntoR for Option<T>` would give if it could exist (the orphan
65    /// rule refuses it in the class's crate). The R wrapper's class constructor lets
66    /// `NULL` through.
67    OptionClassPayload,
68    /// Returns `Option<Self>` -- a lookup-shaped fallible constructor (e.g. `try_find`).
69    /// A method-only shape: `Some(Self)` is wrapped in an `ExternalPtr` via
70    /// `ExternalPtr::new` (same as [`ExternalPtr`](Self::ExternalPtr)), since `Self`
71    /// generally has no `IntoR`, and the `Option<ExternalPtr<Self>>` converts as
72    /// any `Option` does: `None` is `NULL`. The R-side wrapper treats a non-`NULL`
73    /// value exactly like a bare `Self` return (wrapped class object via
74    /// `ReturnStrategy::for_method` — see `ParsedMethod::returns_option_self`).
75    OptionExternalPtr,
76    /// Returns `Result<(), E>` -- raises an error on `Err`, otherwise emits `R_NilValue`.
77    ResultUnit,
78    /// Returns `Result<SEXP, E>` -- raises an error on `Err`, otherwise passes through.
79    ResultSexp,
80    /// Returns `Result<T, E>` -- raises an error on `Err`, otherwise converts the `Ok` value.
81    ResultIntoR,
82    /// Returns `Result<T, ()>` -- maps `Err(())` to `Err(NullOnErr)` then converts via `IntoR`.
83    /// `None`/`Err` maps to R `NULL` (unit error is a deliberate sentinel, not a Rust failure).
84    ResultNullOnErr,
85    /// Returns `Result<Self, E>` -- a fallible constructor-shaped method (e.g. `from_r`,
86    /// `try_new`). Raises an error on `Err` (same as [`ResultIntoR`](Self::ResultIntoR)), but
87    /// wraps `Ok(Self)` in an `ExternalPtr` via `ExternalPtr::new` (same as
88    /// [`ExternalPtr`](Self::ExternalPtr)) instead of routing it through `IntoR` (which `Self`
89    /// generally does not implement). The R-side wrapper mirrors this: a successful return is
90    /// treated exactly like a bare `Self` return (wrapped class object via
91    /// `ReturnStrategy::for_method` — see `ParsedMethod::returns_result_self`).
92    ResultExternalPtr,
93    /// Returns `T` where `T: IntoList` -- wraps in `AsList(result)` then converts it.
94    ///
95    /// Produced when `#[miniextendr(prefer = "list")]` is used on a function returning `T: IntoList`.
96    /// Distinct from returning `AsList<T>` explicitly only in that the wrapping is generated
97    /// by the macro rather than written by the user.
98    AsListOf,
99    /// Returns `T` where `T: IntoExternalPtr` -- wraps in `AsExternalPtr(result)` then converts it.
100    ///
101    /// Produced when `#[miniextendr(prefer = "externalptr")]` is used on a function returning
102    /// `T: IntoExternalPtr`. Distinct from the existing `ExternalPtr` variant (which boxes `Self`
103    /// via `ExternalPtr::new`): this variant calls `IntoExternalPtr::into_external_ptr()` on `T`.
104    AsExternalPtrOf,
105    /// Returns `T` where `T: RNativeType` -- wraps in `AsRNative(result)` then converts it.
106    ///
107    /// Produced when `#[miniextendr(prefer = "native")]` is used on a function returning `T: RNativeType`.
108    AsNativeOf,
109}
110
111/// How the generated `Err` arm turns an error value into condition parts
112/// (message, class vector, structured data).
113#[derive(#[automatically_derived]impl ::core::fmt::Debug for ErrPartsMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Probe { prefix: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Probe prefix", &__self_0),
            Self::Serde { prefix: __self_0, spec: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Serde prefix spec", __self_0, &__self_1),
        }
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for ErrPartsMode {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Probe { prefix: __self_0 } =>
                ErrPartsMode::Probe {
                    prefix: ::core::clone::Clone::clone(__self_0),
                },
            Self::Serde { prefix: __self_0, spec: __self_1 } =>
                ErrPartsMode::Serde {
                    prefix: ::core::clone::Clone::clone(__self_0),
                    spec: ::core::clone::Clone::clone(__self_1),
                },
        }
    }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ErrPartsMode {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ErrPartsMode {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Probe { prefix: __self_0 }, Self::Probe {
                    prefix: __arg1_0 }) => __self_0 == __arg1_0,
                (Self::Serde { prefix: __self_0, spec: __self_1 },
                    Self::Serde { prefix: __arg1_0, spec: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ErrPartsMode {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<String>;
        let _:
                ::core::cmp::AssertParamIsEq<crate::miniextendr_fn::SerdeErrorSpec>;
    }
}Eq)]
114pub enum ErrPartsMode {
115    /// Autoref-specialisation probe (`__mx_result_err_parts!`): under the API
116    /// crate's `serde` feature, the shape `serde_error_shape!` declared for the
117    /// error type in this crate, if any; else `RConditionData` when the error
118    /// type implements it; else, under `serde`, the serde shape for an
119    /// `E: Serialize + Display` with `prefix` (`<crate>_error`) as the family
120    /// class; `Debug` otherwise.
121    Probe { prefix: String },
122    /// `#[miniextendr(serde_error(..))]`: serialize the error with serde; the enum
123    /// variant becomes the member class `<prefix>_<variant>`, the payload fields
124    /// become the condition's data. `prefix` is the crate default (`<crate>_error`);
125    /// the shape declared for the error type, the spec's named `shape` and its
126    /// own options (`tag`, `prefix`, `skip`, `rename`, `as_*`) reach
127    /// `serde_err_parts` as `SerdeErrorShape`s, applied in that order.
128    Serde {
129        prefix: String,
130        spec: crate::miniextendr_fn::SerdeErrorSpec,
131    },
132}
133
134impl ErrPartsMode {
135    /// Resolve a parsed `serde_error` spec (or its absence) into a mode.
136    pub fn from_spec(spec: Option<&crate::miniextendr_fn::SerdeErrorSpec>) -> Self {
137        let prefix = crate::miniextendr_fn::default_serde_error_prefix();
138        match spec {
139            None => ErrPartsMode::Probe { prefix },
140            Some(spec) => ErrPartsMode::Serde {
141                prefix,
142                spec: spec.clone(),
143            },
144        }
145    }
146
147    /// The expression yielding an `ErrParts` from the bound error `e`.
148    pub fn expr(&self) -> TokenStream {
149        match self {
150            ErrPartsMode::Probe { prefix } => {
151                let marker = crate::miniextendr_fn::init_marker_path();
152                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "__mx_result_err_parts");
    ::quote::__private::push_bang(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "e");
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&prefix, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&marker, &mut _s);
            _s
        });
    _s
}quote! { ::miniextendr_api::__mx_result_err_parts!(e, #prefix, #marker) }
153            }
154            ErrPartsMode::Serde { prefix, spec } => {
155                // The shape declared for the error type comes first. The
156                // user's path keeps its span: a misspelt or mistyped shape is
157                // reported on it.
158                let marker = crate::miniextendr_fn::init_marker_path();
159                let declared = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "__mx_declared_serde_shape");
    ::quote::__private::push_bang(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "e");
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&marker, &mut _s);
            _s
        });
    _s
}quote! { ::miniextendr_api::__mx_declared_serde_shape!(e, #marker) };
160                let mut shapes: Vec<TokenStream> = std::iter::once(declared)
161                    .chain(spec.shape.iter().map(
162                        |path| {
    let mut _s = ::quote::__private::TokenStream::new();
    let _span: ::quote::__private::Span =
        ::quote::__private::get_span(syn::spanned::Spanned::span(path)).__into_span();
    ::quote::__private::push_and_spanned(&mut _s, _span);
    ::quote::ToTokens::to_tokens(&path, &mut _s);
    _s
}quote::quote_spanned!(syn::spanned::Spanned::span(path)=> &#path),
163                    ))
164                    .collect();
165                let call = |shapes: &[TokenStream]| {
166                    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "condition");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "serde_err_parts");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_ident(&mut _s, "e");
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&prefix, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    {
                        use ::quote::__private::ext::*;
                        let mut _first = true;
                        let has_iter = ::quote::__private::HasIterator::<false>;
                        #[allow(unused_mut)]
                        let (mut shapes, i) = shapes.quote_into_iter();
                        let has_iter = has_iter | i;
                        <_ as
                                ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                        while true {
                            let shapes =
                                match shapes.next() {
                                    Some(_x) => ::quote::__private::RepInterp(_x),
                                    None => break,
                                };
                            if !_first { ::quote::__private::push_comma(&mut _s); }
                            _first = false;
                            ::quote::ToTokens::to_tokens(&shapes, &mut _s);
                        }
                    }
                    _s
                });
            _s
        });
    _s
}quote! {
167                        ::miniextendr_api::condition::serde_err_parts(&e, #prefix, &[#(#shapes),*])
168                    }
169                };
170                match spec.own_shape() {
171                    None => call(&shapes),
172                    Some(own) => {
173                        let ident = syn::Ident::new(
174                            "__MX_SERDE_ERROR_SHAPE",
175                            proc_macro2::Span::mixed_site(),
176                        );
177                        shapes.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_and(&mut _s);
    ::quote::ToTokens::to_tokens(&ident, &mut _s);
    _s
}quote!(&#ident));
178                        let call = call(&shapes);
179                        {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "const");
            ::quote::ToTokens::to_tokens(&ident, &mut _s);
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "condition");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SerdeErrorShape");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&own, &mut _s);
            ::quote::__private::push_semi(&mut _s);
            ::quote::ToTokens::to_tokens(&call, &mut _s);
            _s
        });
    _s
}quote! {{
180                            const #ident: ::miniextendr_api::condition::SerdeErrorShape = #own;
181                            #call
182                        }}
183                    }
184                }
185            }
186        }
187    }
188}
189
190/// The conversion of a returned value to the `SEXP` a generated entry point
191/// returns (#2272): `IntoR::try_into_sexp(value)`, and a failed conversion
192/// becomes the tagged condition value of a `Result` error (`kind =
193/// "result_err"`): the error's message, classes and fields, read through
194/// `RConditionData`, which every `IntoR::Error` implements
195/// (`condition::into_r_err_parts`). No panic, so no framework file location
196/// in the message.
197///
198/// `call` is the call slot: `Some(__miniextendr_call)` in a `.Call` wrapper,
199/// `None` where the entry has none (sidecar getters, trait vtable shims; the
200/// R guard supplies the call).
201///
202/// An infallible `IntoR` (`Error = Infallible`) costs nothing: the `Err` arm
203/// is uninhabited and compiles away.
204pub(crate) fn return_conversion(value: &TokenStream, call: &TokenStream) -> TokenStream {
205    return_conversion_at(value, call, proc_macro2::Span::call_site())
206}
207
208/// [`return_conversion`] with the `try_into_sexp` path spanned at `span`, so
209/// a value without `IntoR` is reported there.
210pub(crate) fn return_conversion_at(
211    value: &TokenStream,
212    call: &TokenStream,
213    span: proc_macro2::Span,
214) -> TokenStream {
215    let try_into_sexp =
216        {
    let mut _s = ::quote::__private::TokenStream::new();
    let _span: ::quote::__private::Span =
        ::quote::__private::get_span(span).__into_span();
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "miniextendr_api");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "into_r");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "IntoR");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "try_into_sexp");
    _s
}quote::quote_spanned!(span=> ::miniextendr_api::into_r::IntoR::try_into_sexp);
217    let err_value = into_r_err_value(call);
218    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "match");
    ::quote::ToTokens::to_tokens(&try_into_sexp, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&value, &mut _s);
            _s
        });
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Ok");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "__mx_sexp");
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_ident(&mut _s, "__mx_sexp");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Err");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "__mx_error");
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::ToTokens::to_tokens(&err_value, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    _s
}quote! {
219        match #try_into_sexp(#value) {
220            ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
221            ::core::result::Result::Err(__mx_error) => #err_value,
222        }
223    }
224}
225
226/// [`return_conversion`] as a `Result<SEXP, SEXP>`: `Ok` the converted value,
227/// `Err` the tagged condition value of a failed conversion, for a getter that
228/// keeps a converted value and must not keep a condition (a cached field,
229/// #2271).
230pub(crate) fn return_conversion_result(value: &TokenStream, call: &TokenStream) -> TokenStream {
231    let err_value = into_r_err_value(call);
232    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "match");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "into_r");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "IntoR");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "try_into_sexp");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&value, &mut _s);
            _s
        });
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Ok");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "__mx_sexp");
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Ok");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "__mx_sexp");
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Err");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "__mx_error");
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Err");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::ToTokens::to_tokens(&err_value, &mut _s);
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    _s
}quote! {
233        match ::miniextendr_api::into_r::IntoR::try_into_sexp(#value) {
234            ::core::result::Result::Ok(__mx_sexp) => ::core::result::Result::Ok(__mx_sexp),
235            ::core::result::Result::Err(__mx_error) => ::core::result::Result::Err(#err_value),
236        }
237    }
238}
239
240/// The tagged condition value of a failed return conversion, the error bound
241/// to `__mx_error` ([`return_conversion`]).
242fn into_r_err_value(call: &TokenStream) -> TokenStream {
243    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "error_value");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s,
                "result_err_condition_value");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "condition");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "into_r_err_parts");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_and(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "__mx_error");
                            _s
                        });
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::ToTokens::to_tokens(&call, &mut _s);
                    ::quote::__private::push_comma(&mut _s);
                    _s
                });
            _s
        });
    _s
}quote! {
244        // SAFETY: every generated entry point converts its return value
245        // inside its R unwind guard, on R's main thread.
246        unsafe {
247            ::miniextendr_api::error_value::result_err_condition_value(
248                ::miniextendr_api::condition::into_r_err_parts(&__mx_error),
249                #call,
250            )
251        }
252    }
253}
254
255/// All information needed to generate a C wrapper function for an R-exported Rust item.
256///
257/// This struct abstracts over the differences between standalone `#[miniextendr]` functions
258/// and `impl` block methods (R6, S3, S4, S7, Env). It is constructed via
259/// [`CWrapperContextBuilder`] and consumed by [`CWrapperContext::generate`], which emits
260/// both the `extern "C-unwind"` wrapper and the corresponding `R_CallMethodDef` constant.
261pub struct CWrapperContext {
262    /// Identifier of the original Rust function or method being wrapped.
263    pub fn_ident: syn::Ident,
264    /// The name R calls the item by, for the messages the wrapper raises
265    /// (`` `name()` returned no value``). `None` uses `fn_ident`.
266    pub r_name: Option<String>,
267    /// Identifier for the generated C wrapper (e.g., `C_<crate>_foo` or `C_<crate>_Type__method`).
268    pub c_ident: syn::Ident,
269    /// Identifier of the `R_WRAPPER_*` const that holds the generated R wrapper
270    /// code string, for a rustdoc cross-reference. `None` for impl methods: the
271    /// class's wrapper parts are registered in an anonymous `const _` per impl
272    /// block, which has no path to link to.
273    pub r_wrapper_const: Option<syn::Ident>,
274    /// Function parameters (excluding the `self` receiver for methods).
275    /// Each parameter becomes a `SEXP` argument in the C wrapper signature.
276    pub inputs: syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
277    /// Concrete method item supplying types for declaration-copied signatures.
278    pub inferred_signature: Option<TokenStream>,
279    /// The original Rust return type. Used by strict-mode to inspect whether the inner
280    /// type is lossy (e.g., `i64`, `u64`) and needs checked conversion.
281    pub output: syn::ReturnType,
282    /// Statements emitted before the call expression. For instance methods, this
283    /// includes extracting `self` from the `ExternalPtr` SEXP.
284    pub pre_call: Vec<TokenStream>,
285    /// Statements after argument conversion, before the argument borrows and
286    /// the Rust call.
287    pub post_conversion: Vec<TokenStream>,
288    /// The actual Rust call expression (e.g., `my_func(arg0, arg1)` or
289    /// `self_ref.method(arg0)`). Inserted into the wrapper body after conversions.
290    pub call_expr: TokenStream,
291    /// How to convert the Rust return value into a `SEXP` for R.
292    pub return_handling: ReturnHandling,
293    /// When `true`, all parameters use coercing conversion (`Rf_coerceVector`) instead
294    /// of strict type-matching. Set by `#[miniextendr(coerce)]`.
295    pub coerce_all: bool,
296    /// Names of individual parameters that use coercing conversion.
297    /// Set by `#[miniextendr(coerce = "param_name")]`.
298    pub coerce_params: Vec<String>,
299    /// Borrowed parameters using their explicit conversion.
300    pub convert_params: Vec<String>,
301    /// When `true`, emits `R_CheckUserInterrupt()` before the call expression.
302    /// Set by `#[miniextendr(check_interrupt)]`.
303    pub check_interrupt: bool,
304    /// When `true`, wraps the call in `GetRNGstate()`/`PutRNGstate()` for R's
305    /// random number generator state management. Set by `#[miniextendr(rng)]`.
306    pub rng: bool,
307    /// `#[cfg(...)]` attributes from the original item, propagated to the C wrapper
308    /// and `call_method_def` constant so they are conditionally compiled.
309    pub cfg_attrs: Vec<syn::Attribute>,
310    /// For methods: the type identifier (e.g., `MyStruct`). Used in doc comments
311    /// and default `call_method_def` naming. `None` for standalone functions.
312    pub type_context: Option<syn::Ident>,
313    /// Whether the original method has a `self` receiver. When `true`, the C wrapper
314    /// includes a `self_sexp` parameter before the regular arguments.
315    pub has_self: bool,
316    /// Override for the `call_method_def` constant name. If `None`, defaults to
317    /// `call_method_def_{type}_{method}` (methods) or `call_method_def_{fn}` (standalone).
318    pub call_method_def_ident: Option<syn::Ident>,
319    /// When `true`, uses `checked_into_sexp_*` for lossy return types (`i64`, `u64`,
320    /// `isize`, `usize` and their `Vec` variants) instead of the `IntoR` conversion.
321    /// Set by `#[miniextendr(strict)]`.
322    pub strict: bool,
323    /// How `Err` values become condition parts. Set by `#[miniextendr(serde_error)]`.
324    pub err_parts: ErrPartsMode,
325    /// Parameter names with `#[miniextendr(match_arg, several_ok)]` — use
326    /// `match_arg_vec_from_sexp` (instead of `TryFromSexp`) for the `Vec<T>` conversion
327    /// so each element is validated against the enum's `MatchArg::CHOICES`.
328    ///
329    /// Scalar `match_arg` doesn't need entries here because R-side `match.arg()`
330    /// already narrowed the SEXP to a valid choice; the default `TryFromSexp for Enum`
331    /// (generated by `#[derive(MatchArg)]`) decodes it.
332    pub match_arg_several_ok_params: Vec<String>,
333    /// Choice parameters whose type wraps the choice in `Missing` / `Option`
334    /// layers (#1473, #1551), with where their innermost value comes from.
335    /// Converted by the layered decoder
336    /// (`RustConversionBuilder::with_layered_choice`) instead of
337    /// `TryFromSexp`, which no downstream crate can implement for
338    /// `Option<ItsEnum>`.
339    pub layered_choice_params: Vec<(String, crate::rust_conversion_builder::ChoiceLeaf)>,
340    /// `#[miniextendr(no_na)]` parameters (Rust name) with the author's
341    /// `no_na(message = ..)`, if any. Their converted value is checked right
342    /// after the conversion (`RustConversionBuilder::with_no_na`), after the R
343    /// guard `!anyNA(x)` already ran (for an `Either`, in place of the guard).
344    pub no_na_params: Vec<(String, Option<String>)>,
345    /// Parameters whose declared type carries parameter markers
346    /// (`Checked<T>` / `Unchecked<T>`, #1566), with the markers, outermost
347    /// first. `inputs` holds the inner type, which is what converts; the
348    /// value is then wrapped in the markers for the call
349    /// (`RustConversionBuilder::with_param_markers`).
350    pub param_markers: Vec<(String, Vec<crate::type_inspect::ParamMarker>)>,
351    /// The R formal of each parameter (#1842): the name a conversion error
352    /// gives the argument, in its message and `e$param`
353    /// (`RustConversionBuilder::with_formals`).
354    pub formals: crate::r_wrapper_builder::Formals,
355    /// When `true`, preserve original parameter names from `inputs` in the C wrapper
356    /// signature instead of renaming to `arg_0`, `arg_1`, ... The fn path preserves
357    /// user identifiers for rustdoc visibility; impl method path uses `arg_N` for safety.
358    pub preserve_param_names: bool,
359    /// Visibility of the generated `extern "C-unwind"` wrapper function.
360    /// Default: [`syn::Visibility::Inherited`] (no visibility keyword).
361    /// Standalone `#[miniextendr]` fns forward the user's visibility (`pub`, `pub(crate)`, etc.).
362    pub vis: syn::Visibility,
363    /// Generic parameters of the wrapped function, emitted on the C wrapper signature
364    /// as `fn #c_ident #generics(...)`. Default: empty (no generics).
365    pub generics: syn::Generics,
366    /// When `true`, the original Rust fn is already an `extern "C-unwind"` symbol (user-written).
367    /// Skip generating the wrapper body but still emit the `R_CallMethodDef` for registration.
368    /// The `numArgs` count excludes the synthetic `__miniextendr_call` SEXP parameter since
369    /// the user-written fn doesn't have it.
370    pub skip_wrapper: bool,
371}
372
373impl CWrapperContext {
374    /// Creates a new [`CWrapperContextBuilder`] with the given function and C wrapper identifiers.
375    ///
376    /// All other fields start at their defaults (empty/false/None). Use the builder methods
377    /// to configure the context, then call [`CWrapperContextBuilder::build`] to finalize.
378    pub fn builder(fn_ident: syn::Ident, c_ident: syn::Ident) -> CWrapperContextBuilder {
379        CWrapperContextBuilder {
380            fn_ident,
381            r_name: None,
382            c_ident,
383            r_wrapper_const: None,
384            inputs: syn::punctuated::Punctuated::new(),
385            inferred_signature: None,
386            output: syn::ReturnType::Default,
387            pre_call: Vec::new(),
388            post_conversion: Vec::new(),
389            call_expr: None,
390            return_handling: None,
391            coerce_all: false,
392            coerce_params: Vec::new(),
393            convert_params: Vec::new(),
394            check_interrupt: false,
395            rng: false,
396            cfg_attrs: Vec::new(),
397            type_context: None,
398            has_self: false,
399            call_method_def_ident: None,
400            strict: false,
401            err_parts: ErrPartsMode::from_spec(None),
402            match_arg_several_ok_params: Vec::new(),
403            layered_choice_params: Vec::new(),
404            no_na_params: Vec::new(),
405            param_markers: Vec::new(),
406            formals: crate::r_wrapper_builder::Formals::default(),
407            preserve_param_names: false,
408            vis: syn::Visibility::Inherited,
409            generics: syn::Generics::default(),
410            skip_wrapper: false,
411        }
412    }
413
414    /// Generates the complete output for this wrapper: an `extern "C-unwind"` function
415    /// and an `R_CallMethodDef` constant, both decorated with `#[cfg(...)]` attributes
416    /// if present.
417    ///
418    /// When `skip_wrapper` is set (for user-written `extern "C-unwind"` fns), only the
419    /// `R_CallMethodDef` is emitted — the fn body itself is already the C symbol.
420    pub fn generate(&self) -> TokenStream {
421        let call_method_def = self.generate_call_method_def();
422
423        let cfg_attrs = &self.cfg_attrs;
424
425        if self.skip_wrapper {
426            // User-written extern "C-unwind" fn — only emit the registration entry
427            {
    let mut _s = ::quote::__private::TokenStream::new();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut cfg_attrs, i) = cfg_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let cfg_attrs =
                match cfg_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&cfg_attrs, &mut _s);
        }
    }
    ::quote::ToTokens::to_tokens(&call_method_def, &mut _s);
    _s
}quote! {
428                #(#cfg_attrs)*
429                #call_method_def
430            }
431        } else {
432            let c_wrapper = self.generate_wrapper();
433
434            {
    let mut _s = ::quote::__private::TokenStream::new();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut cfg_attrs, i) = cfg_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let cfg_attrs =
                match cfg_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&cfg_attrs, &mut _s);
        }
    }
    ::quote::ToTokens::to_tokens(&c_wrapper, &mut _s);
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut cfg_attrs, i) = cfg_attrs.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let cfg_attrs =
                match cfg_attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&cfg_attrs, &mut _s);
        }
    }
    ::quote::ToTokens::to_tokens(&call_method_def, &mut _s);
    _s
}quote! {
435                #(#cfg_attrs)*
436                #c_wrapper
437
438                #(#cfg_attrs)*
439                #call_method_def
440            }
441        }
442    }
443
444    /// The name the wrapper's messages give the item: `r_name` when set,
445    /// otherwise the Rust identifier.
446    fn message_name(&self) -> String {
447        self.r_name
448            .clone()
449            .unwrap_or_else(|| self.fn_ident.to_string())
450    }
451
452    /// Builds the C wrapper's parameter list from the Rust function signature.
453    ///
454    /// Returns a tuple of:
455    /// - `c_params`: `SEXP` parameter declarations for the C wrapper signature. Always
456    ///   starts with `__miniextendr_call` (the R call object for error context), followed
457    ///   by `self_sexp` for instance methods, then `arg_0`, `arg_1`, ... for each input.
458    /// - `rust_args`: The original Rust parameter identifiers (used in the call expression).
459    /// - `sexp_idents`: The generated `arg_N` identifiers (used in SEXP-to-Rust conversions).
460    fn build_c_params(&self) -> (Vec<TokenStream>, Vec<syn::Ident>, Vec<syn::Ident>) {
461        let mut c_params: Vec<TokenStream> = Vec::new();
462        let mut rust_args: Vec<syn::Ident> = Vec::new();
463        let mut sexp_idents: Vec<syn::Ident> = Vec::new();
464
465        // First param is always __miniextendr_call for error context
466        c_params.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "__miniextendr_call");
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SEXP");
    _s
}quote!(__miniextendr_call: ::miniextendr_api::SEXP));
467
468        // For instance methods, add self_sexp parameter
469        if self.has_self {
470            let self_sexp = crate::naming::self_sexp_ident();
471            c_params.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&self_sexp, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SEXP");
    _s
}quote!(#self_sexp: ::miniextendr_api::SEXP));
472        }
473
474        // Add regular parameters
475        for (idx, arg) in self.inputs.iter().enumerate() {
476            if let syn::FnArg::Typed(pt) = arg
477                && let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
478            {
479                let ident = &pat_ident.ident;
480                // When preserve_param_names is set, use the original parameter name
481                // (visible in rustdoc). Otherwise use arg_N for predictable mangling.
482                let param_ident = if self.preserve_param_names {
483                    // Keep the user's span: the names are distinct, so no
484                    // conversion rebinds another slot, and a mixed-site span
485                    // would take this crate's edition (`gen` is a keyword in
486                    // 2024 but a plain parameter name in a 2021 crate).
487                    ident.clone()
488                } else {
489                    // Conversion binds the user's identifiers in order. A
490                    // mixed-site slot keeps a parameter named `arg_1` from
491                    // replacing the next argument's SEXP.
492                    match ::quote::__private::IdentFragmentAdapter(&idx) {
    arg =>
        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("arg_{0}", arg))
                    }),
            ::quote::__private::Option::Some::<::quote::__private::Span>(proc_macro2::Span::mixed_site())),
}format_ident!("arg_{}", idx, span = proc_macro2::Span::mixed_site())
493                };
494
495                c_params.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&param_ident, &mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SEXP");
    _s
}quote!(#param_ident: ::miniextendr_api::SEXP));
496                rust_args.push(ident.clone());
497                sexp_idents.push(param_ident);
498            }
499        }
500
501        (c_params, rust_args, sexp_idents)
502    }
503
504    /// Generates `TryFromSexp` conversion statements for each parameter.
505    ///
506    /// Each statement converts an `arg_N: SEXP` into the corresponding Rust type
507    /// declared in the original function signature. Respects `strict` and `coerce` settings.
508    /// `prepared` names the parameters whose alias check declared a prepared
509    /// state ([`Self::build_alias_guard`]), which their conversion reads.
510    fn build_conversion_stmts(
511        &self,
512        sexp_idents: &[syn::Ident],
513        prepared: Vec<String>,
514    ) -> Vec<TokenStream> {
515        let builder = prepared
516            .into_iter()
517            .fold(self.conversion_builder(), |builder, name| {
518                builder.with_prepared_param(name)
519            });
520        builder.build_conversions(&self.inputs, sexp_idents)
521    }
522
523    /// Configure argument conversion once for both metadata and value conversion.
524    fn conversion_builder(&self) -> crate::RustConversionBuilder {
525        let mut builder = crate::RustConversionBuilder::new();
526        if self.inferred_signature.is_some() {
527            builder = builder.with_inferred_types();
528        }
529        if self.strict {
530            builder = builder.with_strict();
531        }
532        if self.coerce_all {
533            builder = builder.with_coerce_all();
534        }
535        for param in &self.convert_params {
536            builder = builder.with_convert_param(param.clone());
537        }
538        for param in &self.coerce_params {
539            builder = builder.with_coerce_param(param.clone());
540        }
541        for param in &self.match_arg_several_ok_params {
542            builder = builder.with_match_arg_several_ok(param.clone());
543        }
544        for (param, leaf) in &self.layered_choice_params {
545            builder = builder.with_layered_choice(param.clone(), leaf.clone());
546        }
547        for (param, message) in &self.no_na_params {
548            builder = builder.with_no_na(param.clone(), message.clone());
549        }
550        for (param, markers) in &self.param_markers {
551            builder = builder.with_param_markers(param.clone(), markers.clone());
552        }
553        builder = builder.with_formals(self.formals.clone());
554        // A standalone fn's R wrapper passes `Quoted` / `Quosure` arguments
555        // unevaluated (#1835); a method's is generated per class system and
556        // does not, so there they stay a compile error.
557        match &self.type_context {
558            None => builder = builder.with_unevaluated_args(),
559            Some(type_ident) => builder = builder.with_self_type(::syn::__private::parse_quote({
        let mut _s = ::quote::__private::TokenStream::new();
        ::quote::ToTokens::to_tokens(&type_ident, &mut _s);
        _s
    })syn::parse_quote!(#type_ident)),
560        }
561        builder
562    }
563
564    /// Check the actual converters' native borrows before creating references.
565    /// Metadata handles scalar/slice leaves, aliases, and supported containers.
566    ///
567    /// Also returns the parameters (Rust names) it declares a prepared state
568    /// for, which their conversions read ([`Self::build_conversion_stmts`]).
569    fn build_alias_guard(&self, sexp_idents: &[syn::Ident]) -> (TokenStream, Vec<String>) {
570        let builder = self.conversion_builder();
571        let mut metadata = Vec::new();
572        let mut args = Vec::new();
573        let mut preparations = Vec::new();
574        let mut prepared = Vec::new();
575        for (arg, sexp_ident) in self.inputs.iter().zip(sexp_idents) {
576            if let syn::FnArg::Typed(pt) = arg
577                && let syn::Pat::Ident(pat_ident) = pt.pat.as_ref()
578                && let Some(borrow) = builder.native_borrow_metadata(pt, sexp_ident)
579            {
580                let name = crate::naming::ident_name(&pat_ident.ident);
581                if let Some(preparation) = builder.preparation(pt, sexp_ident) {
582                    preparations.push((metadata.len(), preparation));
583                    prepared.push(name.clone());
584                }
585                metadata.push(borrow);
586                args.push({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&sexp_ident, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::ToTokens::to_tokens(&name, &mut _s);
            _s
        });
    _s
}quote! { (#sexp_ident, #name) });
587            }
588        }
589        if args.is_empty() {
590            return (TokenStream::new(), prepared);
591        }
592        if preparations.is_empty() {
593            return (
594                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s,
                "__miniextendr_native_borrows");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    {
                        use ::quote::__private::ext::*;
                        let mut _first = true;
                        let has_iter = ::quote::__private::HasIterator::<false>;
                        #[allow(unused_mut)]
                        let (mut metadata, i) = metadata.quote_into_iter();
                        let has_iter = has_iter | i;
                        <_ as
                                ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                        while true {
                            let metadata =
                                match metadata.next() {
                                    Some(_x) => ::quote::__private::RepInterp(_x),
                                    None => break,
                                };
                            if !_first { ::quote::__private::push_comma(&mut _s); }
                            _first = false;
                            ::quote::ToTokens::to_tokens(&metadata, &mut _s);
                        }
                    }
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "if");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "from_r");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "borrow");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "needs_check");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_and(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "__miniextendr_native_borrows");
                    _s
                });
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "unsafe");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "from_r");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "borrow");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s,
                                "assert_no_aliases");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_group(&mut _s,
                                        ::quote::__private::Delimiter::Bracket,
                                        {
                                            let mut _s = ::quote::__private::TokenStream::new();
                                            {
                                                use ::quote::__private::ext::*;
                                                let mut _first = true;
                                                let has_iter = ::quote::__private::HasIterator::<false>;
                                                #[allow(unused_mut)]
                                                let (mut args, i) = args.quote_into_iter();
                                                let has_iter = has_iter | i;
                                                <_ as
                                                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                                                while true {
                                                    let args =
                                                        match args.next() {
                                                            Some(_x) => ::quote::__private::RepInterp(_x),
                                                            None => break,
                                                        };
                                                    if !_first { ::quote::__private::push_comma(&mut _s); }
                                                    _first = false;
                                                    ::quote::ToTokens::to_tokens(&args, &mut _s);
                                                }
                                            }
                                            _s
                                        });
                                    ::quote::__private::push_comma(&mut _s);
                                    ::quote::__private::push_ident(&mut _s,
                                        "__miniextendr_native_borrows");
                                    ::quote::__private::push_comma(&mut _s);
                                    _s
                                });
                            ::quote::__private::push_semi(&mut _s);
                            _s
                        });
                    _s
                });
            _s
        });
    _s
}quote! {{
595                    let __miniextendr_native_borrows = [#(#metadata),*];
596                    if ::miniextendr_api::from_r::borrow::needs_check(&__miniextendr_native_borrows) {
597                        // SAFETY: wrapper arguments are rooted on R's main thread, and
598                        // every allocating traversal runs inside R unwind protection.
599                        unsafe {
600                            ::miniextendr_api::from_r::borrow::assert_no_aliases(
601                                [#(#args),*], __miniextendr_native_borrows,
602                            );
603                        }
604                    }
605                }},
606                prepared,
607            );
608        }
609        (
610            crate::rust_conversion_builder::two_pass_alias_guard(&metadata, &args, &preparations),
611            prepared,
612        )
613    }
614
615    /// The borrows of the borrowed external arguments (`&T` / `&mut T` /
616    /// views, #2106), except those a marker rebinds to another type.
617    fn arg_borrows(&self) -> TokenStream {
618        let unborrowed: Vec<String> = self
619            .param_markers
620            .iter()
621            .map(|(name, _)| name.clone())
622            .chain(self.convert_params.iter().cloned())
623            .collect();
624        let self_ty: Option<syn::Type> = self.type_context.as_ref().map(|t| ::syn::__private::parse_quote({
        let mut _s = ::quote::__private::TokenStream::new();
        ::quote::ToTokens::to_tokens(&t, &mut _s);
        _s
    })syn::parse_quote!(#t));
625        crate::externalptr_args::arg_borrows(&self.inputs, &unborrowed, self_ty.as_ref())
626    }
627
628    /// Generates the `extern "C-unwind"` wrapper, which runs on R's main thread.
629    ///
630    /// The wrapper body is enclosed in `with_r_unwind_protect`: Rust panics become
631    /// tagged conditions for the R wrapper to raise, while R exits resume after Rust
632    /// cleanup. With `rng`, an outer R unwind guard also covers loading and saving
633    /// state. The inner guard converts Rust panics to values so `PutRNGstate()` still
634    /// runs; the result stays rooted while that call may allocate.
635    fn generate_wrapper(&self) -> TokenStream {
636        let c_ident = &self.c_ident;
637        let vis = &self.vis;
638        let generics = &self.generics;
639        let (c_params, _, sexp_idents) = self.build_c_params();
640        let (alias_guard, prepared) = self.build_alias_guard(&sexp_idents);
641        let conversion_stmts = self.build_conversion_stmts(&sexp_idents, prepared);
642        let type_setup = self
643            .inferred_signature
644            .as_ref()
645            .map(|callable| crate::trait_signature::setup(&self.inputs, self.has_self, callable));
646        let borrow = self.arg_borrows();
647        let pre_call = &self.pre_call;
648        let post_conversion = &self.post_conversion;
649        let call_expr = &self.call_expr;
650
651        let pre_call_checks = if self.check_interrupt {
652            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "unsafe");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "sys");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "R_CheckUserInterrupt");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_semi(&mut _s);
            _s
        });
    _s
}quote! {
653                unsafe { ::miniextendr_api::sys::R_CheckUserInterrupt(); }
654            }
655        } else {
656            TokenStream::new()
657        };
658
659        let return_handling = self.generate_return_handling(call_expr);
660
661        let doc = self.generate_doc_comment();
662        let source_loc_doc = crate::source_location_doc(self.fn_ident.span());
663
664        let guarded_body = self.protect_wrapper_body({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&type_setup, &mut _s);
    ::quote::ToTokens::to_tokens(&alias_guard, &mut _s);
    ::quote::ToTokens::to_tokens(&pre_call_checks, &mut _s);
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut pre_call, i) = pre_call.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let pre_call =
                match pre_call.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&pre_call, &mut _s);
        }
    }
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut conversion_stmts, i) = conversion_stmts.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let conversion_stmts =
                match conversion_stmts.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&conversion_stmts, &mut _s);
        }
    }
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::HasIterator::<false>;
        #[allow(unused_mut)]
        let (mut post_conversion, i) = post_conversion.quote_into_iter();
        let has_iter = has_iter | i;
        <_ as ::quote::__private::CheckHasIterator<true>>::check(has_iter);
        while true {
            let post_conversion =
                match post_conversion.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&post_conversion, &mut _s);
        }
    }
    ::quote::ToTokens::to_tokens(&borrow, &mut _s);
    ::quote::ToTokens::to_tokens(&return_handling, &mut _s);
    _s
}quote! {
665            #type_setup
666            #alias_guard
667            #pre_call_checks
668            #(#pre_call)*
669            #(#conversion_stmts)*
670            #(#post_conversion)*
671            #borrow
672            #return_handling
673        });
674
675        {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&doc, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&source_loc_doc, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"Generated from source file `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "file");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "no_mangle");
                    _s
                });
            _s
        });
    ::quote::ToTokens::to_tokens(&vis, &mut _s);
    ::quote::__private::push_ident(&mut _s, "extern");
    ::quote::__private::parse(&mut _s, "\"C-unwind\"");
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::ToTokens::to_tokens(&c_ident, &mut _s);
    ::quote::ToTokens::to_tokens(&generics, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            {
                use ::quote::__private::ext::*;
                let mut _first = true;
                let has_iter = ::quote::__private::HasIterator::<false>;
                #[allow(unused_mut)]
                let (mut c_params, i) = c_params.quote_into_iter();
                let has_iter = has_iter | i;
                <_ as
                        ::quote::__private::CheckHasIterator<true>>::check(has_iter);
                while true {
                    let c_params =
                        match c_params.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    if !_first { ::quote::__private::push_comma(&mut _s); }
                    _first = false;
                    ::quote::ToTokens::to_tokens(&c_params, &mut _s);
                }
            }
            _s
        });
    ::quote::__private::push_rarrow(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SEXP");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s,
                "__miniextendr_deferred_mark");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "deferred_condition");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "mark");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_ident(&mut _s, "__miniextendr_value");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&guarded_body, &mut _s);
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "deferred_condition");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "finish");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s,
                                "__miniextendr_deferred_mark");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_ident(&mut _s,
                                "__miniextendr_value");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "core");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Some");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s,
                                        "__miniextendr_call");
                                    _s
                                });
                            ::quote::__private::push_comma(&mut _s);
                            _s
                        });
                    _s
                });
            _s
        });
    _s
}quote! {
676            #[doc = #doc]
677            #[doc = #source_loc_doc]
678            #[doc = ::core::concat!("Generated from source file `", ::core::file!(), "`.")]
679            #[unsafe(no_mangle)]
680            #vis extern "C-unwind" fn #c_ident #generics(#(#c_params),*) -> ::miniextendr_api::SEXP {
681                let __miniextendr_deferred_mark = ::miniextendr_api::deferred_condition::mark();
682                let __miniextendr_value = #guarded_body;
683                unsafe {
684                    ::miniextendr_api::deferred_condition::finish(
685                        __miniextendr_deferred_mark,
686                        __miniextendr_value,
687                        ::core::option::Option::Some(__miniextendr_call),
688                    )
689                }
690            }
691        }
692    }
693
694    /// Protect the complete main-thread portion of a wrapper.
695    ///
696    /// With RNG enabled, the inner guard converts Rust panics into values so
697    /// state is saved on both success and panic. The outer guard covers RNG
698    /// loading, result protection, and saving; either RNG call can raise in R.
699    fn protect_wrapper_body(&self, body: TokenStream) -> TokenStream {
700        let guarded_body = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unwind_protect");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "with_r_unwind_protect");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "move");
            ::quote::__private::push_or_or(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::ToTokens::to_tokens(&body, &mut _s);
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Some");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "__miniextendr_call");
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    _s
}quote! {
701            ::miniextendr_api::unwind_protect::with_r_unwind_protect(
702                move || { #body },
703                ::core::option::Option::Some(__miniextendr_call),
704            )
705        };
706        if self.rng {
707            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "unwind_protect");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "with_r_unwind_protect");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "move");
            ::quote::__private::push_or_or(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "unsafe");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "sys");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s,
                                "GetRNGstate_unchecked");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                ::quote::__private::TokenStream::new());
                            ::quote::__private::push_semi(&mut _s);
                            _s
                        });
                    ::quote::__private::push_ident(&mut _s, "let");
                    ::quote::__private::push_ident(&mut _s,
                        "__miniextendr_rng_value");
                    ::quote::__private::push_eq(&mut _s);
                    ::quote::ToTokens::to_tokens(&guarded_body, &mut _s);
                    ::quote::__private::push_semi(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "let");
                    ::quote::__private::push_ident(&mut _s,
                        "__miniextendr_rng_result");
                    ::quote::__private::push_eq(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "unsafe");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "gc_protect");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "OwnedProtect");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "new");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s,
                                        "__miniextendr_rng_value");
                                    _s
                                });
                            _s
                        });
                    ::quote::__private::push_semi(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "unsafe");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "sys");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s,
                                "PutRNGstate_unchecked");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                ::quote::__private::TokenStream::new());
                            ::quote::__private::push_semi(&mut _s);
                            _s
                        });
                    ::quote::__private::push_ident(&mut _s,
                        "__miniextendr_rng_result");
                    ::quote::__private::push_dot(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "get");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Some");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s,
                        "__miniextendr_call");
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    _s
}quote! {
708                ::miniextendr_api::unwind_protect::with_r_unwind_protect(
709                    move || {
710                        unsafe { ::miniextendr_api::sys::GetRNGstate_unchecked(); }
711                        let __miniextendr_rng_value = #guarded_body;
712                        let __miniextendr_rng_result = unsafe {
713                            ::miniextendr_api::gc_protect::OwnedProtect::new(__miniextendr_rng_value)
714                        };
715                        unsafe { ::miniextendr_api::sys::PutRNGstate_unchecked(); }
716                        __miniextendr_rng_result.get()
717                    },
718                    ::core::option::Option::Some(__miniextendr_call),
719                )
720            }
721        } else {
722            guarded_body
723        }
724    }
725
726    /// Generates the inline return-handling code for the wrapper.
727    ///
728    /// Emits the call expression followed by conversion logic based on [`ReturnHandling`].
729    /// For `Option`/`Result` variants, also emits error-path code that returns a
730    /// tagged condition SEXP (which the R-side wrapper raises).
731    fn generate_return_handling(&self, call_expr: &TokenStream) -> TokenStream {
732        let fn_name = self.message_name();
733        let err_parts = self.err_parts.expr();
734        let self_sexp = crate::naming::self_sexp_ident();
735        let wrapper_call = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Some");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "__miniextendr_call");
            _s
        });
    _s
}quote!(::core::option::Option::Some(__miniextendr_call));
736
737        match &self.return_handling {
738            ReturnHandling::Unit => {
739                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SEXP");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "nil");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    _s
}quote! {
740                    #call_expr;
741                    ::miniextendr_api::SEXP::nil()
742                }
743            }
744            ReturnHandling::RawSexp => {
745                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    _s
}quote! {
746                    #call_expr
747                }
748            }
749            ReturnHandling::ExternalPtr => {
750                let conversion = return_conversion(
751                    &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "externalptr");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "ExternalPtr");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "new");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "__result");
            _s
        });
    _s
}quote!(::miniextendr_api::externalptr::ExternalPtr::new(__result)),
752                    &wrapper_call,
753                );
754                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&conversion, &mut _s);
    _s
}quote! {
755                    let __result = #call_expr;
756                    #conversion
757                }
758            }
759            ReturnHandling::SelfHandle => {
760                // In-place builder: the `&mut self` method mutated the value
761                // pointed to by `self_sexp`. Evaluate the call only for that
762                // side effect, drop the returned `&Self`/`&mut Self` borrow
763                // immediately (the trailing `;` ends its lifetime), and hand
764                // back the SAME ExternalPtr handle. No clone, no rewrap.
765                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_underscore(&mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&self_sexp, &mut _s);
    _s
}quote! {
766                    let _ = #call_expr;
767                    #self_sexp
768                }
769            }
770            ReturnHandling::SelfHandleResult => {
771                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "result");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Result");
    ::quote::__private::push_lt(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_comma(&mut _s);
    ::quote::__private::push_underscore(&mut _s);
    ::quote::__private::push_gt(&mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "if");
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "result");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Result");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Err");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "e");
            _s
        });
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "return");
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "error_value");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "result_err_condition_value");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&err_parts, &mut _s);
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "core");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Some");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s,
                                        "__miniextendr_call");
                                    _s
                                });
                            ::quote::__private::push_comma(&mut _s);
                            _s
                        });
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            _s
        });
    ::quote::ToTokens::to_tokens(&self_sexp, &mut _s);
    _s
}quote! {
772                    let __result: ::core::result::Result<(), _> = #call_expr;
773                    if let ::core::result::Result::Err(e) = __result {
774                        return unsafe { ::miniextendr_api::error_value::result_err_condition_value(
775                            #err_parts, ::core::option::Option::Some(__miniextendr_call),
776                        ) };
777                    }
778                    #self_sexp
779                }
780            }
781            ReturnHandling::SelfHandleOption => {
782                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Option");
    ::quote::__private::push_lt(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_gt(&mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "if");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_dot(&mut _s);
    ::quote::__private::push_ident(&mut _s, "is_none");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "return");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "nil");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_semi(&mut _s);
            _s
        });
    ::quote::ToTokens::to_tokens(&self_sexp, &mut _s);
    _s
}quote! {
783                    let __result: ::core::option::Option<()> = #call_expr;
784                    if __result.is_none() {
785                        return ::miniextendr_api::SEXP::nil();
786                    }
787                    #self_sexp
788                }
789            }
790            ReturnHandling::IntoR => {
791                let result_ident = ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__result"))
            }), ::quote::__private::Option::None)format_ident!("__result");
792                let conversion = self.sexp_conversion_expr(&result_ident, true);
793                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::ToTokens::to_tokens(&result_ident, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&conversion, &mut _s);
    _s
}quote! {
794                    let #result_ident = #call_expr;
795                    #conversion
796                }
797            }
798            ReturnHandling::OptionUnit => {
799                let error_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}()` returned no value",
                fn_name))
    })format!("`{fn_name}()` returned no value");
800                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "if");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_dot(&mut _s);
    ::quote::__private::push_ident(&mut _s, "is_none");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "return");
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "error_value");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "make_rust_condition_value");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&error_msg, &mut _s);
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "error_value");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "kind");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "NONE_ERR");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "core");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "None");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "core");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Some");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s,
                                        "__miniextendr_call");
                                    _s
                                });
                            ::quote::__private::push_comma(&mut _s);
                            _s
                        });
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            _s
        });
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SEXP");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "nil");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    _s
}quote! {
801                    let __result = #call_expr;
802                    if __result.is_none() {
803                        return unsafe { ::miniextendr_api::error_value::make_rust_condition_value(
804                            #error_msg, ::miniextendr_api::error_value::kind::NONE_ERR, ::core::option::Option::None, ::core::option::Option::Some(__miniextendr_call),
805                        ) };
806                    }
807                    ::miniextendr_api::SEXP::nil()
808                }
809            }
810            ReturnHandling::OptionSexp => {
811                let error_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}()` returned no value",
                fn_name))
    })format!("`{fn_name}()` returned no value");
812                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "match");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Some");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "v");
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_ident(&mut _s, "v");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "None");
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_ident(&mut _s, "return");
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "error_value");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "make_rust_condition_value");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&error_msg, &mut _s);
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "error_value");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "kind");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "NONE_ERR");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "core");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "None");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "core");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Some");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s,
                                        "__miniextendr_call");
                                    _s
                                });
                            ::quote::__private::push_comma(&mut _s);
                            _s
                        });
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    _s
}quote! {
813                    let __result = #call_expr;
814                    match __result {
815                        ::core::option::Option::Some(v) => v,
816                        ::core::option::Option::None => return unsafe { ::miniextendr_api::error_value::make_rust_condition_value(
817                            #error_msg, ::miniextendr_api::error_value::kind::NONE_ERR, ::core::option::Option::None, ::core::option::Option::Some(__miniextendr_call),
818                        ) },
819                    }
820                }
821            }
822            ReturnHandling::OptionIntoR => {
823                // For Option<T> where Option<T>: IntoR (e.g. Option<&T>, Option<Vec<T>>).
824                // Convert the whole Option — its IntoR impl handles None → NULL/NA.
825                // result_ident holds the full Option<T>, so the strict lookup must
826                // see the full type (checked_option_* helpers).
827                let result_ident = ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__result"))
            }), ::quote::__private::Option::None)format_ident!("__result");
828                let conversion = self.sexp_conversion_expr(&result_ident, false);
829                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::ToTokens::to_tokens(&result_ident, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&conversion, &mut _s);
    _s
}quote! {
830                    let #result_ident = #call_expr;
831                    #conversion
832                }
833            }
834            ReturnHandling::OptionClassPayload => {
835                // Option<Class> under an explicit class wrap: no `IntoR for Option<Class>`
836                // can exist, so convert Some's payload through `Class: IntoR`; None is NULL.
837                let result_ident = ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__result"))
            }), ::quote::__private::Option::None)format_ident!("__result");
838                let conversion = self.sexp_conversion_expr(&result_ident, true);
839                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "match");
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Some");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::ToTokens::to_tokens(&result_ident, &mut _s);
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::ToTokens::to_tokens(&conversion, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Option");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "None");
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "nil");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    _s
}quote! {
840                    match #call_expr {
841                        ::core::option::Option::Some(#result_ident) => #conversion,
842                        ::core::option::Option::None => ::miniextendr_api::SEXP::nil(),
843                    }
844                }
845            }
846            // Option<Self>: wrap Some(Self) in an ExternalPtr like the bare-Self path;
847            // the Option<ExternalPtr<Self>> gives NULL for None.
848            ReturnHandling::OptionExternalPtr => {
849                let conversion = return_conversion(
850                    &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_dot(&mut _s);
    ::quote::__private::push_ident(&mut _s, "map");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "externalptr");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "ExternalPtr");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "new");
            _s
        });
    _s
}quote!(__result.map(::miniextendr_api::externalptr::ExternalPtr::new)),
851                    &wrapper_call,
852                );
853                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&conversion, &mut _s);
    _s
}quote! {
854                    let __result = #call_expr;
855                    #conversion
856                }
857            }
858            ReturnHandling::ResultUnit => {
859                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "if");
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "result");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Result");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Err");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "e");
            _s
        });
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "return");
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "error_value");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "result_err_condition_value");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&err_parts, &mut _s);
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "core");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Some");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s,
                                        "__miniextendr_call");
                                    _s
                                });
                            ::quote::__private::push_comma(&mut _s);
                            _s
                        });
                    _s
                });
            ::quote::__private::push_semi(&mut _s);
            _s
        });
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "SEXP");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "nil");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    _s
}quote! {
860                    let __result = #call_expr;
861                    if let ::core::result::Result::Err(e) = __result {
862                        return unsafe { ::miniextendr_api::error_value::result_err_condition_value(
863                            #err_parts, ::core::option::Option::Some(__miniextendr_call),
864                        ) };
865                    }
866                    ::miniextendr_api::SEXP::nil()
867                }
868            }
869            ReturnHandling::ResultSexp => {
870                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "match");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Ok");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "v");
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_ident(&mut _s, "v");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Err");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "e");
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_ident(&mut _s, "return");
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "error_value");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "result_err_condition_value");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&err_parts, &mut _s);
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "core");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Some");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s,
                                        "__miniextendr_call");
                                    _s
                                });
                            ::quote::__private::push_comma(&mut _s);
                            _s
                        });
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    _s
}quote! {
871                    let __result = #call_expr;
872                    match __result {
873                        ::core::result::Result::Ok(v) => v,
874                        ::core::result::Result::Err(e) => return unsafe { ::miniextendr_api::error_value::result_err_condition_value(
875                            #err_parts, ::core::option::Option::Some(__miniextendr_call),
876                        ) },
877                    }
878                }
879            }
880            ReturnHandling::ResultIntoR => {
881                let result_ident = ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__result"))
            }), ::quote::__private::Option::None)format_ident!("__result");
882                let conversion = self.sexp_conversion_expr(&result_ident, true);
883                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::ToTokens::to_tokens(&result_ident, &mut _s);
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_ident(&mut _s, "match");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Ok");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "v");
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_ident(&mut _s, "v");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Err");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "e");
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_ident(&mut _s, "return");
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "error_value");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "result_err_condition_value");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&err_parts, &mut _s);
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "core");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Some");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s,
                                        "__miniextendr_call");
                                    _s
                                });
                            ::quote::__private::push_comma(&mut _s);
                            _s
                        });
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&conversion, &mut _s);
    _s
}quote! {
884                    let __result = #call_expr;
885                    let #result_ident = match __result {
886                        ::core::result::Result::Ok(v) => v,
887                        ::core::result::Result::Err(e) => return unsafe { ::miniextendr_api::error_value::result_err_condition_value(
888                            #err_parts, ::core::option::Option::Some(__miniextendr_call),
889                        ) },
890                    };
891                    #conversion
892                }
893            }
894            // Result<T, ()>: unit error is a deliberate sentinel — always return NULL on Err.
895            ReturnHandling::ResultNullOnErr => {
896                let result_ident = ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__result"))
            }), ::quote::__private::Option::None)format_ident!("__result");
897                let conversion = self.sexp_conversion_expr(&result_ident, true);
898                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "match");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Ok");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::ToTokens::to_tokens(&result_ident, &mut _s);
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::ToTokens::to_tokens(&conversion, &mut _s);
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Err");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "miniextendr_api");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "SEXP");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "nil");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    _s
}quote! {
899                    let __result = #call_expr;
900                    match __result {
901                        ::core::result::Result::Ok(#result_ident) => #conversion,
902                        ::core::result::Result::Err(()) => ::miniextendr_api::SEXP::nil(),
903                    }
904                }
905            }
906            // Result<Self, E>: raise on Err like ResultIntoR, but wrap Ok(Self) in an
907            // ExternalPtr like the bare-Self path rather than routing through IntoR.
908            ReturnHandling::ResultExternalPtr => {
909                let conversion = return_conversion(
910                    &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "externalptr");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "ExternalPtr");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "new");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "__result");
            _s
        });
    _s
}quote!(::miniextendr_api::externalptr::ExternalPtr::new(__result)),
911                    &wrapper_call,
912                );
913                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_ident(&mut _s, "match");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Ok");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "v");
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_ident(&mut _s, "v");
            ::quote::__private::push_comma(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Result");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Err");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "e");
                    _s
                });
            ::quote::__private::push_fat_arrow(&mut _s);
            ::quote::__private::push_ident(&mut _s, "return");
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "error_value");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "result_err_condition_value");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::ToTokens::to_tokens(&err_parts, &mut _s);
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "core");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Option");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Some");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s,
                                        "__miniextendr_call");
                                    _s
                                });
                            ::quote::__private::push_comma(&mut _s);
                            _s
                        });
                    _s
                });
            ::quote::__private::push_comma(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&conversion, &mut _s);
    _s
}quote! {
914                    let __result = #call_expr;
915                    let __result = match __result {
916                        ::core::result::Result::Ok(v) => v,
917                        ::core::result::Result::Err(e) => return unsafe { ::miniextendr_api::error_value::result_err_condition_value(
918                            #err_parts, ::core::option::Option::Some(__miniextendr_call),
919                        ) },
920                    };
921                    #conversion
922                }
923            }
924            ReturnHandling::AsListOf => {
925                let conversion = return_conversion(
926                    &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "convert");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "AsList");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "__result");
            _s
        });
    _s
}quote!(::miniextendr_api::convert::AsList(__result)),
927                    &wrapper_call,
928                );
929                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&conversion, &mut _s);
    _s
}quote! {
930                    let __result = #call_expr;
931                    #conversion
932                }
933            }
934            ReturnHandling::AsExternalPtrOf => {
935                let conversion = return_conversion(
936                    &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "convert");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "AsExternalPtr");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "__result");
            _s
        });
    _s
}quote!(::miniextendr_api::convert::AsExternalPtr(__result)),
937                    &wrapper_call,
938                );
939                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&conversion, &mut _s);
    _s
}quote! {
940                    let __result = #call_expr;
941                    #conversion
942                }
943            }
944            ReturnHandling::AsNativeOf => {
945                let conversion = return_conversion(
946                    &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "miniextendr_api");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "convert");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "AsRNative");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "__result");
            _s
        });
    _s
}quote!(::miniextendr_api::convert::AsRNative(__result)),
947                    &wrapper_call,
948                );
949                {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "let");
    ::quote::__private::push_ident(&mut _s, "__result");
    ::quote::__private::push_eq(&mut _s);
    ::quote::ToTokens::to_tokens(&call_expr, &mut _s);
    ::quote::__private::push_semi(&mut _s);
    ::quote::ToTokens::to_tokens(&conversion, &mut _s);
    _s
}quote! {
950                    let __result = #call_expr;
951                    #conversion
952                }
953            }
954        }
955    }
956
957    /// Returns the SEXP conversion expression for `result_ident`, using strict
958    /// checked conversion if strict mode is on and the inner return type is lossy,
959    /// otherwise falling back to [`return_conversion`].
960    ///
961    /// `result_holds_unwrapped` says what `result_ident` is bound to at runtime:
962    /// `true` when the arm already unwrapped the declared `Option<T>` /
963    /// `Result<T, E>` wrapper (so the strict lookup must see the inner `T`),
964    /// `false` when `result_ident` holds the full declared return type (so
965    /// `Option<lossy>` must resolve to the `checked_option_*` helpers — passing
966    /// the stripped inner type there emits a scalar helper call on an `Option`
967    /// value, which does not compile; caught by the strict-default CI leg).
968    fn sexp_conversion_expr(
969        &self,
970        result_ident: &syn::Ident,
971        result_holds_unwrapped: bool,
972    ) -> TokenStream {
973        if self.strict {
974            // Extract the type `result_ident` actually holds from the output type
975            let inner_ty = match &self.output {
976                syn::ReturnType::Type(_, ty) => {
977                    let ty = ty.as_ref();
978                    // Strip an Option<T> / Result<T, E> wrapper only when the
979                    // calling arm bound the unwrapped value.
980                    if result_holds_unwrapped
981                        && let syn::Type::Path(p) = ty
982                        && let Some(seg) = p.path.segments.last()
983                    {
984                        let name = seg.ident.to_string();
985                        if (name == "Option" || name == "Result")
986                            && let Some(inner) = first_type_argument(seg)
987                        {
988                            Some(inner)
989                        } else {
990                            Some(ty)
991                        }
992                    } else {
993                        Some(ty)
994                    }
995                }
996                syn::ReturnType::Default => None,
997            };
998
999            if let Some(inner_ty) = inner_ty.and_then(|ty| {
1000                crate::return_type_analysis::strict_conversion_for_type(ty, result_ident)
1001            }) {
1002                return inner_ty;
1003            }
1004        }
1005
1006        return_conversion(
1007            &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&result_ident, &mut _s);
    _s
}quote!(#result_ident),
1008            &{
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "core");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Option");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "Some");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "__miniextendr_call");
            _s
        });
    _s
}quote!(::core::option::Option::Some(__miniextendr_call)),
1009        )
1010    }
1011
1012    /// Generates the `R_CallMethodDef` constant for R's `.Call` interface registration.
1013    ///
1014    /// The constant contains the C symbol name, a `DL_FUNC` pointer to the wrapper
1015    /// (obtained via `transmute`), and the argument count. R uses this at package load
1016    /// time (via `R_registerRoutines`) to register the native routine.
1017    fn generate_call_method_def(&self) -> TokenStream {
1018        let fn_ident = &self.fn_ident;
1019        let c_ident = &self.c_ident;
1020        // When skip_wrapper is set, the user-written fn doesn't have the synthetic
1021        // __miniextendr_call SEXP param — use the actual input count. Otherwise
1022        // use build_c_params() which includes __miniextendr_call + self_sexp.
1023        let num_args = if self.skip_wrapper {
1024            self.inputs
1025                .iter()
1026                .filter(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
    syn::FnArg::Typed(_) => true,
    _ => false,
}matches!(arg, syn::FnArg::Typed(_)))
1027                .count()
1028        } else {
1029            let (c_params, _, _) = self.build_c_params();
1030            c_params.len()
1031        };
1032        // Use custom call_method_def_ident if set, otherwise use default naming
1033        let call_method_def_ident = self.call_method_def_ident.clone().unwrap_or_else(|| {
1034            if let Some(ref type_ident) = self.type_context {
1035                match ::quote::__private::IdentFragmentAdapter(&type_ident) {
    arg =>
        match ::quote::__private::IdentFragmentAdapter(&fn_ident) {
            arg =>
                ::quote::__private::mk_ident(&::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("call_method_def_{0}_{1}",
                                        arg, arg))
                            }),
                    ::quote::__private::Option::None.or(arg.span()).or(arg.span())),
        },
}format_ident!("call_method_def_{}_{}", type_ident, fn_ident)
1036            } else {
1037                match ::quote::__private::IdentFragmentAdapter(&fn_ident) {
    arg =>
        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("call_method_def_{0}",
                                arg))
                    }), ::quote::__private::Option::None.or(arg.span())),
}format_ident!("call_method_def_{}", fn_ident)
1038            }
1039        });
1040
1041        let registration =
1042            crate::call_method_def::call_method_def(&call_method_def_ident, c_ident, num_args);
1043
1044        let item_label = if let Some(ref type_ident) = self.type_context {
1045            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}::{1}`", type_ident, fn_ident))
    })format!("`{}::{}`", type_ident, fn_ident)
1046        } else {
1047            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", fn_ident))
    })format!("`{}`", fn_ident)
1048        };
1049        let doc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("R call method definition for {0} (C wrapper: [`{1}`]).",
                item_label, c_ident))
    })format!(
1050            "R call method definition for {} (C wrapper: [`{}`]).",
1051            item_label, c_ident
1052        );
1053        let doc_example = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Value: `R_CallMethodDef {{ name: \"{0}\", numArgs: {1}, fun: <DL_FUNC> }}`",
                c_ident, num_args))
    })format!(
1054            "Value: `R_CallMethodDef {{ name: \"{}\", numArgs: {}, fun: <DL_FUNC> }}`",
1055            c_ident, num_args
1056        );
1057        let source_loc_doc = crate::source_location_doc(self.fn_ident.span());
1058
1059        {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&doc, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&doc_example, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&source_loc_doc, &mut _s);
            _s
        });
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "doc");
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "core");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "concat");
            ::quote::__private::push_bang(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::parse(&mut _s,
                        "\"Generated from source file `\"");
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "core");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "file");
                    ::quote::__private::push_bang(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_comma(&mut _s);
                    ::quote::__private::parse(&mut _s, "\"`.\"");
                    _s
                });
            _s
        });
    ::quote::ToTokens::to_tokens(&registration, &mut _s);
    _s
}quote! {
1060            #[doc = #doc]
1061            #[doc = #doc_example]
1062            #[doc = #source_loc_doc]
1063            #[doc = ::core::concat!("Generated from source file `", ::core::file!(), "`.")]
1064            #registration
1065        }
1066    }
1067
1068    /// Generates a rustdoc comment string for the C wrapper function.
1069    ///
1070    /// Includes the original function/method name and a cross-reference to the
1071    /// R wrapper constant when there is one.
1072    fn generate_doc_comment(&self) -> String {
1073        let item = match self.type_context {
1074            Some(ref type_ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::{1}", type_ident,
                self.fn_ident))
    })format!("{}::{}", type_ident, self.fn_ident),
1075            None => self.fn_ident.to_string(),
1076        };
1077        match self.r_wrapper_const {
1078            Some(ref r_wrapper_const) => {
1079                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("C wrapper for [`{0}`]. See [`{1}`] for R wrapper.",
                item, r_wrapper_const))
    })format!("C wrapper for [`{item}`]. See [`{r_wrapper_const}`] for R wrapper.")
1080            }
1081            None => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("C wrapper for [`{0}`].", item))
    })format!("C wrapper for [`{item}`]."),
1082        }
1083    }
1084}
1085
1086/// Builder for [`CWrapperContext`].
1087///
1088/// Created via [`CWrapperContext::builder`]. All fields except `fn_ident` and `c_ident`
1089/// (provided at construction) default to empty/false/None. The required `call_expr`
1090/// must be set before calling [`build`](Self::build) or it will panic.
1091///
1092/// `return_handling` is auto-detected from the function signature if not
1093/// explicitly set.
1094pub struct CWrapperContextBuilder {
1095    /// Rust function/method identifier (set at construction).
1096    fn_ident: syn::Ident,
1097    /// R-facing name for raised messages. Defaults to `fn_ident`.
1098    r_name: Option<String>,
1099    /// C wrapper function identifier (set at construction).
1100    c_ident: syn::Ident,
1101    /// R wrapper constant identifier for doc cross-references, if the wrapper has one.
1102    r_wrapper_const: Option<syn::Ident>,
1103    /// Function parameters (excluding `self`). Defaults to empty.
1104    inputs: syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
1105    inferred_signature: Option<TokenStream>,
1106    /// Rust return type. Defaults to `()` (no return type annotation).
1107    output: syn::ReturnType,
1108    /// Pre-call statements emitted before the call expression. Defaults to empty.
1109    pre_call: Vec<TokenStream>,
1110    /// Statements after argument conversion, on R's main thread.
1111    post_conversion: Vec<TokenStream>,
1112    /// The Rust call expression. **Required.**
1113    call_expr: Option<TokenStream>,
1114    /// Return handling override. If `None`, auto-detected from `output` via [`detect_return_handling`].
1115    return_handling: Option<ReturnHandling>,
1116    /// Enable coercing conversion for all parameters.
1117    coerce_all: bool,
1118    /// Names of individual parameters with coercing conversion enabled.
1119    coerce_params: Vec<String>,
1120    convert_params: Vec<String>,
1121    /// Emit `R_CheckUserInterrupt()` before the call.
1122    check_interrupt: bool,
1123    /// Wrap call in `GetRNGstate()`/`PutRNGstate()`.
1124    rng: bool,
1125    /// `#[cfg(...)]` attributes to propagate to generated items.
1126    cfg_attrs: Vec<syn::Attribute>,
1127    /// Type identifier for method context (e.g., `MyStruct`). `None` for standalone functions.
1128    type_context: Option<syn::Ident>,
1129    /// Whether the original method has a `self` receiver.
1130    has_self: bool,
1131    /// Custom `call_method_def` constant name override.
1132    call_method_def_ident: Option<syn::Ident>,
1133    /// Enable strict checked conversions for lossy return types.
1134    strict: bool,
1135    /// How `Err` values become condition parts.
1136    err_parts: ErrPartsMode,
1137    /// Parameter names with `match_arg + several_ok` — forwarded to
1138    /// `RustConversionBuilder::with_match_arg_several_ok` so each element of the
1139    /// Vec is decoded via `match_arg_vec_from_sexp` (enum's `MatchArg::CHOICES`).
1140    match_arg_several_ok_params: Vec<String>,
1141    /// Layered choice parameters — forwarded to
1142    /// `RustConversionBuilder::with_layered_choice`.
1143    layered_choice_params: Vec<(String, crate::rust_conversion_builder::ChoiceLeaf)>,
1144    /// `no_na` parameters, forwarded to `RustConversionBuilder::with_no_na`.
1145    no_na_params: Vec<(String, Option<String>)>,
1146    /// Marked parameters, forwarded to
1147    /// `RustConversionBuilder::with_param_markers`.
1148    param_markers: Vec<(String, Vec<crate::type_inspect::ParamMarker>)>,
1149    /// The parameters' R formals, forwarded to
1150    /// `RustConversionBuilder::with_formals`.
1151    formals: crate::r_wrapper_builder::Formals,
1152    /// When `true`, use original parameter names in C wrapper signature (for rustdoc).
1153    preserve_param_names: bool,
1154    /// Visibility of the generated `extern "C-unwind"` wrapper.
1155    vis: syn::Visibility,
1156    /// Generic parameters for the C wrapper signature.
1157    generics: syn::Generics,
1158    /// When `true`, skip wrapper body but still emit `R_CallMethodDef`.
1159    skip_wrapper: bool,
1160}
1161
1162impl CWrapperContextBuilder {
1163    /// Sets the name R calls the item by, used in the messages the wrapper
1164    /// raises in place of the Rust identifier. Share the resolved name with
1165    /// the R wrapper generator, including renames and postfixes.
1166    pub fn r_name(mut self, r_name: String) -> Self {
1167        self.r_name = Some(r_name);
1168        self
1169    }
1170
1171    /// Sets the R wrapper constant identifier (e.g., `R_WRAPPER_my_func`) the
1172    /// wrapper's rustdoc links to.
1173    pub fn r_wrapper_const(mut self, ident: syn::Ident) -> Self {
1174        self.r_wrapper_const = Some(ident);
1175        self
1176    }
1177
1178    /// Sets the function parameters (excluding `self` receiver).
1179    /// Each input becomes a `SEXP` argument in the C wrapper.
1180    pub fn inputs(
1181        mut self,
1182        inputs: syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
1183    ) -> Self {
1184        self.inputs = inputs;
1185        self
1186    }
1187
1188    /// Infer inherited parameter types from this concrete method item.
1189    pub fn inferred_signature(mut self, callable: TokenStream) -> Self {
1190        self.inferred_signature = Some(callable);
1191        self
1192    }
1193
1194    /// Sets the Rust return type. Used for auto-detecting [`ReturnHandling`]
1195    /// and for strict-mode type inspection.
1196    pub fn output(mut self, output: syn::ReturnType) -> Self {
1197        self.output = output;
1198        self
1199    }
1200
1201    /// Sets pre-call statements emitted before the call expression.
1202    /// Typically used for self-extraction in instance methods.
1203    pub fn pre_call(mut self, stmts: Vec<TokenStream>) -> Self {
1204        self.pre_call = stmts;
1205        self
1206    }
1207
1208    /// Statements that need converted arguments, without shortening their scope.
1209    pub fn post_conversion(mut self, stmts: Vec<TokenStream>) -> Self {
1210        self.post_conversion = stmts;
1211        self
1212    }
1213
1214    /// Sets the Rust call expression (e.g., `my_func(arg0)` or `self_ref.method(arg0)`).
1215    /// **Required** -- [`build`](Self::build) panics if not set.
1216    pub fn call_expr(mut self, expr: TokenStream) -> Self {
1217        self.call_expr = Some(expr);
1218        self
1219    }
1220
1221    /// Overrides the return handling strategy. If not called, auto-detected from `output`
1222    /// via [`detect_return_handling`].
1223    pub fn return_handling(mut self, handling: ReturnHandling) -> Self {
1224        self.return_handling = Some(handling);
1225        self
1226    }
1227
1228    /// Enables coercing conversion for all parameters via `Rf_coerceVector`.
1229    pub fn coerce_all(mut self) -> Self {
1230        self.coerce_all = true;
1231        self
1232    }
1233
1234    /// Enables coercing conversion for a specific named parameter.
1235    pub fn with_coerce_param(mut self, param_name: String) -> Self {
1236        self.coerce_params.push(param_name);
1237        self
1238    }
1239
1240    /// Use a reference's conversion rather than borrowing an external value.
1241    pub fn with_convert_param(mut self, param_name: String) -> Self {
1242        self.convert_params.push(param_name);
1243        self
1244    }
1245
1246    /// Enables `R_CheckUserInterrupt()` before the call expression.
1247    pub fn check_interrupt(mut self) -> Self {
1248        self.check_interrupt = true;
1249        self
1250    }
1251
1252    /// Enable RNG state management (GetRNGstate/PutRNGstate).
1253    pub fn rng(mut self) -> Self {
1254        self.rng = true;
1255        self
1256    }
1257
1258    /// Sets `#[cfg(...)]` attributes to propagate to the C wrapper and `call_method_def`.
1259    pub fn cfg_attrs(mut self, attrs: Vec<syn::Attribute>) -> Self {
1260        self.cfg_attrs = attrs;
1261        self
1262    }
1263
1264    /// Sets the type context for methods (e.g., `MyStruct`). Used in doc comments
1265    /// and default `call_method_def` naming.
1266    pub fn type_context(mut self, type_ident: syn::Ident) -> Self {
1267        self.type_context = Some(type_ident);
1268        self
1269    }
1270
1271    /// Marks this as an instance method with a `self` receiver.
1272    /// Causes the C wrapper to include a `self_sexp` parameter.
1273    pub fn has_self(mut self) -> Self {
1274        self.has_self = true;
1275        self
1276    }
1277
1278    /// Enables strict checked conversions for lossy return types (`i64`, `u64`, `isize`,
1279    /// `usize` and their `Vec` variants).
1280    pub fn strict(mut self) -> Self {
1281        self.strict = true;
1282        self
1283    }
1284
1285    /// Choose how `Err` values become condition parts (default: the
1286    /// `RConditionData`/`Debug` probe). See [`ErrPartsMode`].
1287    pub fn err_parts(mut self, mode: ErrPartsMode) -> Self {
1288        self.err_parts = mode;
1289        self
1290    }
1291
1292    /// Record a parameter as `match_arg + several_ok`.
1293    ///
1294    /// Passed through to `RustConversionBuilder::with_match_arg_several_ok`, which
1295    /// switches that parameter's conversion from `TryFromSexp` to
1296    /// `match_arg_vec_from_sexp::<Inner>` so each STRSXP element is validated against
1297    /// the enum's `MatchArg::CHOICES`.
1298    pub fn match_arg_several_ok(mut self, param_name: String) -> Self {
1299        self.match_arg_several_ok_params.push(param_name);
1300        self
1301    }
1302
1303    /// Record a choice parameter whose type wraps the choice in `Missing` /
1304    /// `Option` layers (#1473, #1551).
1305    ///
1306    /// Passed through to `RustConversionBuilder::with_layered_choice`, which
1307    /// decodes the layers outermost first (an omitted argument is
1308    /// `Missing::Absent`, `NULL` is `None`) and the choice itself from `leaf`.
1309    pub fn layered_choice(
1310        mut self,
1311        param_name: String,
1312        leaf: crate::rust_conversion_builder::ChoiceLeaf,
1313    ) -> Self {
1314        self.layered_choice_params.push((param_name, leaf));
1315        self
1316    }
1317
1318    /// Record a `#[miniextendr(no_na)]` parameter (its Rust name) and the
1319    /// author's `no_na(message = "...")`, if any.
1320    ///
1321    /// Passed through to `RustConversionBuilder::with_no_na`, which checks the
1322    /// converted value (`TryFromSexp::__mx_has_na`) right after its binding,
1323    /// for what the type reads as `NA` beyond the R guard's `anyNA()`. An
1324    /// `Either` has no R guard, and its value checks the input instead
1325    /// (`TryFromSexp::__mx_input_has_na`).
1326    pub fn no_na(mut self, param_name: String, message: Option<String>) -> Self {
1327        self.no_na_params.push((param_name, message));
1328        self
1329    }
1330
1331    /// Record a parameter (its Rust name) whose declared type carries the
1332    /// parameter `markers` (`Checked<T>` / `Unchecked<T>`, #1566, outermost
1333    /// first). The inputs hold the inner type; the converted value is wrapped
1334    /// in the markers before the call.
1335    pub fn param_markers(
1336        mut self,
1337        param_name: String,
1338        markers: Vec<crate::type_inspect::ParamMarker>,
1339    ) -> Self {
1340        self.param_markers.push((param_name, markers));
1341        self
1342    }
1343
1344    /// Name each parameter by its R formal (#1842) in the conversion errors
1345    /// (their message and `e$param`); without it, the Rust name without
1346    /// leading underscores.
1347    pub fn formals(mut self, formals: crate::r_wrapper_builder::Formals) -> Self {
1348        self.formals = formals;
1349        self
1350    }
1351
1352    /// Set a custom call_method_def identifier.
1353    ///
1354    /// If not set, the default naming is used:
1355    /// - With type_context: `call_method_def_{type}_{method}`
1356    /// - Without: `call_method_def_{method}`
1357    pub fn call_method_def_ident(mut self, ident: syn::Ident) -> Self {
1358        self.call_method_def_ident = Some(ident);
1359        self
1360    }
1361
1362    /// Preserve original parameter names in the C wrapper signature.
1363    ///
1364    /// When `true`, `build_c_params` uses the original identifier from `inputs` instead
1365    /// of renaming to `arg_N`. Enables rustdoc to show descriptive parameter names.
1366    /// Used by the standalone-fn path; impl methods use the default `arg_N` form.
1367    pub fn preserve_param_names(mut self) -> Self {
1368        self.preserve_param_names = true;
1369        self
1370    }
1371
1372    /// Set the visibility of the generated `extern "C-unwind"` wrapper.
1373    ///
1374    /// Defaults to [`syn::Visibility::Inherited`]. Standalone fns forward the user's
1375    /// declared visibility (`pub`, `pub(crate)`, etc.).
1376    pub fn vis(mut self, vis: syn::Visibility) -> Self {
1377        self.vis = vis;
1378        self
1379    }
1380
1381    /// Set the generic parameters for the C wrapper function signature.
1382    ///
1383    /// Defaults to empty generics. Standalone fns with generic parameters
1384    /// must forward them so the generated wrapper is also generic.
1385    pub fn generics(mut self, generics: syn::Generics) -> Self {
1386        self.generics = generics;
1387        self
1388    }
1389
1390    /// Skip generating the wrapper body and only emit the `R_CallMethodDef`.
1391    ///
1392    /// Use this when the Rust fn is already `extern "C-unwind"` with `#[no_mangle]` or
1393    /// `#[unsafe(no_mangle)]` (the user wrote the C symbol directly). The function still
1394    /// needs to be registered with R via `R_CallMethodDef`.
1395    ///
1396    /// When set, `numArgs` is computed from `inputs` directly (no synthetic
1397    /// `__miniextendr_call` param).
1398    pub fn skip_wrapper(mut self) -> Self {
1399        self.skip_wrapper = true;
1400        self
1401    }
1402
1403    /// Consumes the builder and returns a fully configured [`CWrapperContext`].
1404    ///
1405    /// If `return_handling` was not set, auto-detects from the `output` type via
1406    /// [`detect_return_handling`].
1407    ///
1408    /// # Panics
1409    ///
1410    /// Panics if `call_expr` was not set.
1411    pub fn build(self) -> CWrapperContext {
1412        let call_expr = self
1413            .call_expr
1414            .expect("call_expr is required for CWrapperContext");
1415
1416        // Detect return handling if not explicitly set
1417        let return_handling = self
1418            .return_handling
1419            .unwrap_or_else(|| detect_return_handling(&self.output, None));
1420
1421        CWrapperContext {
1422            fn_ident: self.fn_ident,
1423            r_name: self.r_name,
1424            c_ident: self.c_ident,
1425            r_wrapper_const: self.r_wrapper_const,
1426            inputs: self.inputs,
1427            inferred_signature: self.inferred_signature,
1428            output: self.output,
1429            pre_call: self.pre_call,
1430            post_conversion: self.post_conversion,
1431            call_expr,
1432            return_handling,
1433            coerce_all: self.coerce_all,
1434            coerce_params: self.coerce_params,
1435            convert_params: self.convert_params,
1436            check_interrupt: self.check_interrupt,
1437            rng: self.rng,
1438            cfg_attrs: self.cfg_attrs,
1439            type_context: self.type_context,
1440            has_self: self.has_self,
1441            call_method_def_ident: self.call_method_def_ident,
1442            strict: self.strict,
1443            err_parts: self.err_parts,
1444            match_arg_several_ok_params: self.match_arg_several_ok_params,
1445            layered_choice_params: self.layered_choice_params,
1446            no_na_params: self.no_na_params,
1447            param_markers: self.param_markers,
1448            formals: self.formals,
1449            preserve_param_names: self.preserve_param_names,
1450            vis: self.vis,
1451            generics: self.generics,
1452            skip_wrapper: self.skip_wrapper,
1453        }
1454    }
1455}
1456
1457/// Detects the [`ReturnHandling`] strategy from a return type: the one rule for
1458/// standalone functions, inherent methods and trait methods.
1459///
1460/// - No return type annotation (`Default`) maps to [`ReturnHandling::Unit`].
1461/// - An explicit type is analyzed by [`detect_return_handling_from_type`].
1462/// - `wrap` is the explicit class wrap (`WrapAs*<T>` marker or `wrap = "..."`
1463///   attribute) when there is one: an `Option<Class>` under it converts its payload
1464///   ([`ReturnHandling::OptionClassPayload`]), since no `IntoR for Option<Class>`
1465///   can exist.
1466pub fn detect_return_handling(
1467    output: &syn::ReturnType,
1468    wrap: Option<&crate::return_wrap::ReturnWrap>,
1469) -> ReturnHandling {
1470    match output {
1471        syn::ReturnType::Default => ReturnHandling::Unit,
1472        syn::ReturnType::Type(_, ty) => match detect_return_handling_from_type(ty) {
1473            ReturnHandling::OptionIntoR if wrap.is_some_and(|wrap| wrap.is_optional_class()) => {
1474                ReturnHandling::OptionClassPayload
1475            }
1476            handling => handling,
1477        },
1478    }
1479}
1480
1481/// Determines the [`ReturnHandling`] variant for a concrete `syn::Type`.
1482///
1483/// Recognition rules:
1484/// - `()` -> [`Unit`](ReturnHandling::Unit)
1485/// - `Self` -> [`ExternalPtr`](ReturnHandling::ExternalPtr)
1486/// - `SEXP` -> [`RawSexp`](ReturnHandling::RawSexp)
1487/// - `Option<T>` -> [`OptionUnit`](ReturnHandling::OptionUnit) for `T = ()`,
1488///   [`OptionSexp`](ReturnHandling::OptionSexp) for `T = SEXP`,
1489///   [`OptionExternalPtr`](ReturnHandling::OptionExternalPtr) for `T = Self`, and
1490///   [`OptionIntoR`](ReturnHandling::OptionIntoR) for every other `T`
1491/// - `Result<T, E>` -> recurses into `T` for `ResultUnit`, `ResultSexp`, `ResultExternalPtr`
1492///   (`T = Self`), or `ResultIntoR`
1493/// - Anything else -> [`IntoR`](ReturnHandling::IntoR)
1494fn detect_return_handling_from_type(ty: &syn::Type) -> ReturnHandling {
1495    match ty {
1496        // Unit tuple ()
1497        syn::Type::Tuple(t) if t.elems.is_empty() => ReturnHandling::Unit,
1498
1499        // Self - wrap in ExternalPtr
1500        syn::Type::Path(p)
1501            if p.path
1502                .segments
1503                .last()
1504                .map(|s| s.ident == "Self")
1505                .unwrap_or(false) =>
1506        {
1507            ReturnHandling::ExternalPtr
1508        }
1509
1510        // SEXP - pass through
1511        syn::Type::Path(p)
1512            if p.path
1513                .segments
1514                .last()
1515                .map(|s| s.ident == "SEXP")
1516                .unwrap_or(false) =>
1517        {
1518            ReturnHandling::RawSexp
1519        }
1520
1521        // Option<T>
1522        syn::Type::Path(p)
1523            if p.path
1524                .segments
1525                .last()
1526                .map(|s| s.ident == "Option")
1527                .unwrap_or(false) =>
1528        {
1529            if let Some(inner_ty) = first_type_argument(p.path.segments.last().unwrap()) {
1530                match inner_ty {
1531                    syn::Type::Tuple(t) if t.elems.is_empty() => ReturnHandling::OptionUnit,
1532                    syn::Type::Path(ip)
1533                        if ip
1534                            .path
1535                            .segments
1536                            .last()
1537                            .map(|s| s.ident == "SEXP")
1538                            .unwrap_or(false) =>
1539                    {
1540                        ReturnHandling::OptionSexp
1541                    }
1542                    // Option<Self>: a lookup-shaped fallible constructor. Wrap
1543                    // `Some(Self)` in an ExternalPtr like the bare-`Self` path, rather
1544                    // than routing it through `IntoR` (which `Self` generally lacks).
1545                    // Symmetric with `Result<Self, E>` -> `ResultExternalPtr` below.
1546                    syn::Type::Path(ip)
1547                        if ip
1548                            .path
1549                            .segments
1550                            .last()
1551                            .map(|s| s.ident == "Self")
1552                            .unwrap_or(false) =>
1553                    {
1554                        ReturnHandling::OptionExternalPtr
1555                    }
1556                    _ => ReturnHandling::OptionIntoR,
1557                }
1558            } else {
1559                ReturnHandling::OptionIntoR
1560            }
1561        }
1562
1563        // Result<T, E>
1564        syn::Type::Path(p)
1565            if p.path
1566                .segments
1567                .last()
1568                .map(|s| s.ident == "Result")
1569                .unwrap_or(false) =>
1570        {
1571            let seg = p.path.segments.last().unwrap();
1572            // Special case: Result<T, ()> — unit error is a deliberate sentinel that maps to
1573            // R NULL, not a failure.
1574            let err_is_unit = crate::second_type_argument(seg)
1575                .is_some_and(|ty| #[allow(non_exhaustive_omitted_patterns)] match ty {
    syn::Type::Tuple(t) if t.elems.is_empty() => true,
    _ => false,
}matches!(ty, syn::Type::Tuple(t) if t.elems.is_empty()));
1576            if err_is_unit {
1577                return ReturnHandling::ResultNullOnErr;
1578            }
1579            if let Some(ok_ty) = first_type_argument(seg) {
1580                match ok_ty {
1581                    syn::Type::Tuple(t) if t.elems.is_empty() => ReturnHandling::ResultUnit,
1582                    syn::Type::Path(ip)
1583                        if ip
1584                            .path
1585                            .segments
1586                            .last()
1587                            .map(|s| s.ident == "SEXP")
1588                            .unwrap_or(false) =>
1589                    {
1590                        ReturnHandling::ResultSexp
1591                    }
1592                    // Result<Self, E>: a fallible constructor-shaped method. Wrap
1593                    // `Ok(Self)` in an ExternalPtr like the bare-`Self` path, rather
1594                    // than routing it through `IntoR` (which `Self` generally lacks).
1595                    syn::Type::Path(ip)
1596                        if ip
1597                            .path
1598                            .segments
1599                            .last()
1600                            .map(|s| s.ident == "Self")
1601                            .unwrap_or(false) =>
1602                    {
1603                        ReturnHandling::ResultExternalPtr
1604                    }
1605                    _ => ReturnHandling::ResultIntoR,
1606                }
1607            } else {
1608                ReturnHandling::ResultIntoR
1609            }
1610        }
1611
1612        // Everything else - use IntoR
1613        _ => ReturnHandling::IntoR,
1614    }
1615}
1616
1617/// Extracts the first generic type argument from a path segment's angle-bracketed arguments.
1618///
1619/// For example, given `Option<String>`, returns `Some(&String)`.
1620/// Returns `None` if the segment has no angle-bracketed arguments or no type arguments.
1621fn first_type_argument(seg: &syn::PathSegment) -> Option<&syn::Type> {
1622    if let syn::PathArguments::AngleBracketed(ab) = &seg.arguments {
1623        for arg in ab.args.iter() {
1624            if let syn::GenericArgument::Type(ty) = arg {
1625                return Some(ty);
1626            }
1627        }
1628    }
1629    None
1630}
1631
1632#[cfg(test)]
1633mod tests;