Skip to main content

miniextendr_macros/
type_inspect.rs

1//! Lightweight type-introspection helpers shared by parsing and codegen.
2
3/// Returns the `n`-th generic type argument from a path segment.
4pub(crate) fn nth_type_argument(seg: &syn::PathSegment, n: usize) -> Option<&syn::Type> {
5    if let syn::PathArguments::AngleBracketed(ab) = &seg.arguments {
6        let mut count = 0;
7        for arg in ab.args.iter() {
8            if let syn::GenericArgument::Type(ty) = arg {
9                if count == n {
10                    return Some(ty);
11                }
12                count += 1;
13            }
14        }
15    }
16    None
17}
18
19/// Returns the first generic type argument from a path segment.
20pub(crate) fn first_type_argument(seg: &syn::PathSegment) -> Option<&syn::Type> {
21    nth_type_argument(seg, 0)
22}
23
24/// Returns the second generic type argument from a path segment.
25pub(crate) fn second_type_argument(seg: &syn::PathSegment) -> Option<&syn::Type> {
26    nth_type_argument(seg, 1)
27}
28
29/// Peel a return-visibility marker (`Invisible<T>` / `Visible<T>`, matched
30/// on the last path segment like `Dots` / `Missing`).
31///
32/// Returns `(Some(true), &T)` for `Invisible<T>`, `(Some(false), &T)` for
33/// `Visible<T>`, and `(None, ty)` for anything else, including a bare
34/// `Invisible` with no type argument (left alone; the fail-safe direction is
35/// "not a marker", and `IntoR` on the marker types keeps the conversion
36/// correct). Nested markers are the caller's error to report; see
37/// [`visibility_marker_error`].
38pub(crate) fn peel_visibility_marker(ty: &syn::Type) -> (Option<bool>, &syn::Type) {
39    let syn::Type::Path(p) = ty else {
40        return (None, ty);
41    };
42    let Some(seg) = p.path.segments.last() else {
43        return (None, ty);
44    };
45    let invisible = match seg.ident.to_string().as_str() {
46        "Invisible" => true,
47        "Visible" => false,
48        _ => return (None, ty),
49    };
50    match first_type_argument(seg) {
51        Some(inner) => (Some(invisible), inner),
52        None => (None, ty),
53    }
54}
55
56/// [`peel_visibility_marker`] over a whole `syn::ReturnType`: returns the
57/// marker's decision and an owned return type with the marker removed, so the
58/// rest of the analysis (`Option`/`Result` shapes, `Self`, thread strategy)
59/// sees exactly what it would without the marker.
60pub(crate) fn peel_return_visibility(output: &syn::ReturnType) -> (Option<bool>, syn::ReturnType) {
61    match output {
62        syn::ReturnType::Type(arrow, ty) => {
63            let (marker, inner) = peel_visibility_marker(ty);
64            match marker {
65                Some(_) => (
66                    marker,
67                    syn::ReturnType::Type(*arrow, Box::new(inner.clone())),
68                ),
69                None => (None, output.clone()),
70            }
71        }
72        syn::ReturnType::Default => (None, output.clone()),
73    }
74}
75
76/// Model `#[miniextendr(serialize)]` exactly like a declared `AsSerialize<T>`
77/// return, after peeling an outer visibility marker. In particular, `Option`
78/// and `Result` inside it are serde data, not boundary control flow.
79pub(crate) fn serialize_return_type(output: &syn::ReturnType, serialize: bool) -> syn::ReturnType {
80    if !serialize {
81        return output.clone();
82    }
83    let ty: syn::Type = match output {
84        syn::ReturnType::Default => ::syn::__private::parse_quote({
        let mut _s = ::quote::__private::TokenStream::new();
        ::quote::__private::push_group(&mut _s,
            ::quote::__private::Delimiter::Parenthesis,
            ::quote::__private::TokenStream::new());
        _s
    })syn::parse_quote!(()),
85        syn::ReturnType::Type(_, ty) => (**ty).clone(),
86    };
87    ::syn::__private::parse_quote({
        let mut _s = ::quote::__private::TokenStream::new();
        ::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, "serde");
        ::quote::__private::push_colon2(&mut _s);
        ::quote::__private::push_ident(&mut _s, "AsSerialize");
        ::quote::__private::push_lt(&mut _s);
        ::quote::ToTokens::to_tokens(&ty, &mut _s);
        ::quote::__private::push_gt(&mut _s);
        _s
    })syn::parse_quote!(-> ::miniextendr_api::serde::AsSerialize<#ty>)
88}
89
90/// Prepare the value to match the type used by return analysis. Both functions
91/// and method/shim paths unwrap visibility before applying serde transport.
92pub(crate) fn prepare_return_value(
93    call: proc_macro2::TokenStream,
94    visibility_marker: Option<bool>,
95    serialize: bool,
96) -> proc_macro2::TokenStream {
97    let value = if visibility_marker.is_some() {
98        {
    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(&call, &mut _s);
            _s
        });
    ::quote::__private::push_dot(&mut _s);
    ::quote::__private::parse(&mut _s, "0");
    _s
}quote::quote! { (#call).0 }
99    } else {
100        call
101    };
102    if serialize {
103        {
    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, "serde");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "AsSerialize");
    ::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
        });
    _s
}quote::quote! { ::miniextendr_api::serde::AsSerialize(#value) }
104    } else {
105        value
106    }
107}
108
109/// Resolve the wrapper's visibility from the three sources, most explicit
110/// first: a return-type marker, then the `invisible` / `visible` attribute,
111/// then the shape default. A marker and an attribute that disagree are an
112/// error at `span`.
113pub(crate) fn resolve_visibility(
114    marker: Option<bool>,
115    attr: Option<bool>,
116    shape_default: bool,
117    span: proc_macro2::Span,
118) -> syn::Result<bool> {
119    match (marker, attr) {
120        (Some(m), Some(a)) if m != a => Err(syn::Error::new(
121            span,
122            "the return type's visibility marker and the `invisible` / `visible` attribute disagree; keep one of them (or make them agree)",
123        )),
124        (Some(m), _) => Ok(m),
125        (None, Some(a)) => Ok(a),
126        (None, None) => Ok(shape_default),
127    }
128}
129
130/// The error for a marker that cannot be honoured: a nested marker
131/// (`Invisible<Visible<T>>`), a marker in argument position, or, the mirror
132/// case, a parameter marker (`Checked<T>` / `Unchecked<T>`) in return
133/// position (also inside a visibility marker).
134pub(crate) fn visibility_marker_error(ty: &syn::Type, what: &str) -> Option<syn::Error> {
135    let (marker, inner) = peel_visibility_marker(ty);
136    if what == "return"
137        && let Some((param_marker, _)) = outer_param_marker(inner)
138    {
139        return Some(syn::Error::new_spanned(
140            ty,
141            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}<T>` marks a parameter only; it cannot be used as a return type (return the inner `T`)",
                param_marker.name()))
    })format!(
142                "`{}<T>` marks a parameter only; it cannot be used as a return type (return the \
143                 inner `T`)",
144                param_marker.name()
145            ),
146        ));
147    }
148    marker?;
149    if what == "argument" {
150        return Some(syn::Error::new_spanned(
151            ty,
152            "`Invisible<T>` / `Visible<T>` mark the return type only; they cannot be used as a parameter type",
153        ));
154    }
155    if peel_visibility_marker(inner).0.is_some() {
156        return Some(syn::Error::new_spanned(
157            ty,
158            "visibility markers cannot be nested; use a single `Invisible<T>` or `Visible<T>` around the return type",
159        ));
160    }
161    None
162}
163
164// region: condition-call markers (#1566)
165
166/// Detect a condition-call marker parameter type: `Call` selects `wrapper`
167/// attribution, `CallerCall` selects `caller`. Matched on the last path
168/// segment like the visibility markers; a segment carrying generic arguments
169/// (`Call<T>`) is some other type. References and wrappers (`&Call`,
170/// `Option<Call>`) are not markers: the C wrapper binds the marker by value
171/// from its hidden call slot.
172pub(crate) fn call_marker(ty: &syn::Type) -> Option<crate::r_wrapper_builder::CallAttribution> {
173    let syn::Type::Path(p) = ty else {
174        return None;
175    };
176    let seg = p.path.segments.last()?;
177    if !#[allow(non_exhaustive_omitted_patterns)] match seg.arguments {
    syn::PathArguments::None => true,
    _ => false,
}matches!(seg.arguments, syn::PathArguments::None) {
178        return None;
179    }
180    match seg.ident.to_string().as_str() {
181        "Call" => Some(crate::r_wrapper_builder::CallAttribution::Wrapper),
182        "CallerCall" => Some(crate::r_wrapper_builder::CallAttribution::Caller),
183        _ => None,
184    }
185}
186
187// endregion
188
189// region: argument-count marker (#1860)
190
191/// Detect the argument-count marker parameter type, `NArgs`: matched on the
192/// last path segment like [`call_marker`], with no generic arguments.
193/// References and wrappers (`&NArgs`, `Option<NArgs>`) are not the marker.
194///
195/// The parameter is no R formal: the R wrapper passes `nargs()` at its
196/// position in the `.Call()` (`RArgumentBuilder::build_call_args_vec`), and the
197/// C wrapper converts it like any parameter (`TryFromSexp for NArgs`).
198pub(crate) fn is_nargs_marker(ty: &syn::Type) -> bool {
199    let syn::Type::Path(p) = ty else {
200        return false;
201    };
202    p.path
203        .segments
204        .last()
205        .is_some_and(|seg| seg.ident == "NArgs" && seg.arguments.is_none())
206}
207
208// endregion
209
210// region: RNG guard parameter (#2002)
211
212/// Detect the RNG guard parameter type, `&RngGuard` (a shared reference to a
213/// path whose last segment is `RngGuard`, with no generic arguments, any
214/// lifetime). Under `#[miniextendr(rng)]` the parameter is no R formal: the
215/// wrapper has loaded R's RNG state and passes its guard at that position.
216pub(crate) fn is_rng_guard_param(ty: &syn::Type) -> bool {
217    let syn::Type::Reference(reference) = ty else {
218        return false;
219    };
220    reference.mutability.is_none()
221        && #[allow(non_exhaustive_omitted_patterns)] match reference.elem.as_ref() {
    syn::Type::Path(p) if
        p.qself.is_none() &&
            p.path.segments.last().is_some_and(|seg|
                    seg.ident == "RngGuard" && seg.arguments.is_none()) => true,
    _ => false,
}matches!(reference.elem.as_ref(), syn::Type::Path(p) if p.qself.is_none() && p
222            .path
223            .segments
224            .last()
225            .is_some_and(|seg| seg.ident == "RngGuard" && seg.arguments.is_none()))
226}
227
228/// Whether `ty` names `RngGuard` anywhere: a parameter that does without
229/// being [`is_rng_guard_param`] (`&mut RngGuard`, `RngGuard` by value,
230/// `Option<&RngGuard>`) is a shape the wrapper cannot fill.
231pub(crate) fn mentions_rng_guard(ty: &syn::Type) -> bool {
232    match ty {
233        syn::Type::Path(p) => p.path.segments.iter().any(|seg| {
234            seg.ident == "RngGuard"
235                || match &seg.arguments {
236                    syn::PathArguments::AngleBracketed(ab) => ab.args.iter().any(
237                        |arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
    syn::GenericArgument::Type(t) if mentions_rng_guard(t) => true,
    _ => false,
}matches!(arg, syn::GenericArgument::Type(t) if mentions_rng_guard(t)),
238                    ),
239                    _ => false,
240                }
241        }),
242        syn::Type::Reference(r) => mentions_rng_guard(&r.elem),
243        syn::Type::Paren(p) => mentions_rng_guard(&p.elem),
244        syn::Type::Group(g) => mentions_rng_guard(&g.elem),
245        syn::Type::Tuple(t) => t.elems.iter().any(mentions_rng_guard),
246        syn::Type::Array(a) => mentions_rng_guard(&a.elem),
247        syn::Type::Slice(s) => mentions_rng_guard(&s.elem),
248        _ => false,
249    }
250}
251
252/// The argument expression for an `&RngGuard` parameter: a borrow of a guard
253/// made at the call, which the wrapper has loaded the state for and saves
254/// itself (the guard saves nothing when it drops). No binding, so no user
255/// parameter name can capture it.
256pub(crate) fn rng_guard_arg() -> proc_macro2::TokenStream {
257    {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_and(&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, "rng");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "RngGuard");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "__mx_loaded_by_wrapper");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            _s
        });
    _s
}quote::quote! {
258        &unsafe { ::miniextendr_api::rng::RngGuard::__mx_loaded_by_wrapper() }
259    }
260}
261
262// endregion
263
264// region: borrowed vector views (#1427)
265
266/// Conversions selected from the rooted call argument rather than a raw SEXP.
267/// The Cow vector cases are character vectors, not arbitrary lists of views.
268pub(crate) fn is_rooted_view(ty: &syn::Type) -> bool {
269    let syn::Type::Path(path) = ty else {
270        return false;
271    };
272    if path.qself.is_some() {
273        return false;
274    }
275    let Some(seg) = path.path.segments.last() else {
276        return false;
277    };
278    if seg.ident == "StrVec" || seg.ident == "RCow" || seg.ident == "Cow" {
279        return true;
280    }
281    seg.ident == "Vec"
282        && first_type_argument(seg).is_some_and(|elem| {
283            let elem = option_inner_type(elem).unwrap_or(elem);
284            #[allow(non_exhaustive_omitted_patterns)] match elem {
    syn::Type::Path(p) if
        p.qself.is_none() &&
            p.path.segments.last().is_some_and(|s| s.ident == "Cow") => true,
    _ => false,
}matches!(elem, syn::Type::Path(p) if p.qself.is_none() && p.path.segments.last()
285            .is_some_and(|s| s.ident == "Cow"))
286        })
287}
288
289/// Explicit shared reference forms whose main-thread conversions borrow a root:
290/// the references, their `Option`s, and `Vec`s of either (nested `Vec`s too).
291/// Mutable and custom references keep their own conversion path.
292pub(crate) fn is_rooted_reference(ty: &syn::Type) -> bool {
293    let ty = option_inner_type(ty).unwrap_or(ty);
294    if let syn::Type::Path(path) = ty
295        && path.qself.is_none()
296        && let Some(segment) = path.path.segments.last()
297        && segment.ident == "Vec"
298    {
299        return first_type_argument(segment).is_some_and(is_rooted_reference);
300    }
301    let syn::Type::Reference(reference) = ty else {
302        return false;
303    };
304    if reference.mutability.is_some() {
305        return false;
306    }
307    match reference.elem.as_ref() {
308        syn::Type::Slice(_) => true,
309        syn::Type::Path(path) if path.qself.is_none() => {
310            path.path.segments.last().is_some_and(|seg| {
311                seg.arguments.is_none()
312                    && #[allow(non_exhaustive_omitted_patterns)] match seg.ident.to_string().as_str()
    {
    "i32" | "f64" | "u8" | "RLogical" | "Rcomplex" | "str" => true,
    _ => false,
}matches!(
313                        seg.ident.to_string().as_str(),
314                        "i32" | "f64" | "u8" | "RLogical" | "Rcomplex" | "str"
315                    )
316            })
317        }
318        _ => false,
319    }
320}
321
322/// A `'static` borrowed parameter (`StrVec<'static>`, `Cow<'static, str>`,
323/// `&'static [T]`, `Option<&'static str>`) can never be bound: its root is the
324/// call's argument slot, or a copy that ends with the call. Returns the
325/// statement that binds `ident` with a `compile_error!` naming the fix,
326/// spanned at the lifetime, in place of a borrow-checker error about a
327/// generated temporary. The binding keeps the code
328/// that uses `ident` free of follow-on errors; it does not diverge, so that
329/// code draws no unreachable warning.
330pub(crate) fn static_rooted_view_binding(
331    ident: &syn::Ident,
332    ty: &syn::Type,
333) -> Option<proc_macro2::TokenStream> {
334    let lifetime = static_lifetime(ty)?;
335    Some({
    let mut _s = ::quote::__private::TokenStream::new();
    let _span: ::quote::__private::Span =
        ::quote::__private::get_span(lifetime.span()).__into_span();
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "core");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "compile_error");
    ::quote::__private::push_bang_spanned(&mut _s, _span);
    ::quote::__private::push_group_spanned(&mut _s, _span,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            let _span: ::quote::__private::Span =
                ::quote::__private::get_span(_span).__into_span();
            ::quote::__private::parse_spanned(&mut _s, _span,
                "\"this parameter borrows the call\'s argument and cannot be `\'static`; write `\'_` or \\\n             elide the lifetime, or take an owned type (`ProtectedStrVec`, `Vec`, `String`) to \\\n             keep the data after the call\"");
            _s
        });
    ::quote::__private::push_semi_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "let");
    ::quote::ToTokens::to_tokens(&ident, &mut _s);
    ::quote::__private::push_colon_spanned(&mut _s, _span);
    ::quote::ToTokens::to_tokens(&ty, &mut _s);
    ::quote::__private::push_eq_spanned(&mut _s, _span);
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "core");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "option");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "Option");
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_lt_spanned(&mut _s, _span);
    ::quote::ToTokens::to_tokens(&ty, &mut _s);
    ::quote::__private::push_gt_spanned(&mut _s, _span);
    ::quote::__private::push_colon2_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "None");
    ::quote::__private::push_dot_spanned(&mut _s, _span);
    ::quote::__private::push_ident_spanned(&mut _s, _span, "unwrap");
    ::quote::__private::push_group_spanned(&mut _s, _span,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let _: ::quote::__private::Span =
                ::quote::__private::get_span(_span).__into_span();
            ::quote::__private::TokenStream::new()
        });
    ::quote::__private::push_semi_spanned(&mut _s, _span);
    _s
}quote::quote_spanned! {lifetime.span()=>
336        ::core::compile_error!(
337            "this parameter borrows the call's argument and cannot be `'static`; write `'_` or \
338             elide the lifetime, or take an owned type (`ProtectedStrVec`, `Vec`, `String`) to \
339             keep the data after the call"
340        );
341        let #ident: #ty = ::core::option::Option::<#ty>::None.unwrap();
342    })
343}
344
345/// The first `'static` lifetime written anywhere in `ty`.
346pub(crate) fn static_lifetime(ty: &syn::Type) -> Option<&syn::Lifetime> {
347    let is_static = |lt: &&syn::Lifetime| lt.ident == "static";
348    match ty {
349        syn::Type::Reference(r) => r
350            .lifetime
351            .as_ref()
352            .filter(is_static)
353            .or_else(|| static_lifetime(&r.elem)),
354        syn::Type::Path(p) => p.path.segments.iter().find_map(|seg| {
355            let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
356                return None;
357            };
358            args.args.iter().find_map(|arg| match arg {
359                syn::GenericArgument::Lifetime(lt) => Some(lt).filter(is_static),
360                syn::GenericArgument::Type(ty) => static_lifetime(ty),
361                _ => None,
362            })
363        }),
364        syn::Type::Slice(s) => static_lifetime(&s.elem),
365        syn::Type::Array(a) => static_lifetime(&a.elem),
366        syn::Type::Paren(p) => static_lifetime(&p.elem),
367        syn::Type::Group(g) => static_lifetime(&g.elem),
368        syn::Type::Tuple(t) => t.elems.iter().find_map(static_lifetime),
369        _ => None,
370    }
371}
372
373// endregion
374
375// region: unforced dots (#1892)
376
377/// Detect the unforced-dots parameter type, `LazyDots`: matched on the last
378/// path segment like the other markers, bare or with lifetime arguments only
379/// (`LazyDots<'_>`). Only the whole type by value is the parameter; any other
380/// shape (`&LazyDots`, `Option<LazyDots>`, `Missing<LazyDots>`) is refused by
381/// the callers through [`mentions_lazy_dots`].
382///
383/// The parameter is R's `...` at its position: the R wrapper passes
384/// `environment()` there (`RArgumentBuilder::build_call_args_vec`), and the C
385/// wrapper binds it with `LazyDots::from_wrapper_arg`.
386pub(crate) fn is_lazy_dots_marker(ty: &syn::Type) -> bool {
387    let syn::Type::Path(p) = ty else {
388        return false;
389    };
390    p.path.segments.last().is_some_and(|seg| {
391        seg.ident == "LazyDots"
392            && match &seg.arguments {
393                syn::PathArguments::None => true,
394                syn::PathArguments::AngleBracketed(ab) => ab
395                    .args
396                    .iter()
397                    .all(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
    syn::GenericArgument::Lifetime(_) => true,
    _ => false,
}matches!(arg, syn::GenericArgument::Lifetime(_))),
398                syn::PathArguments::Parenthesized(_) => false,
399            }
400    })
401}
402
403/// Whether `ty` names `LazyDots` anywhere, at any depth.
404pub(crate) fn mentions_lazy_dots(ty: &syn::Type) -> bool {
405    match ty {
406        syn::Type::Path(p) => p.path.segments.iter().any(|seg| {
407            seg.ident == "LazyDots"
408                || match &seg.arguments {
409                    syn::PathArguments::AngleBracketed(ab) => ab.args.iter().any(
410                        |arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
    syn::GenericArgument::Type(t) if mentions_lazy_dots(t) => true,
    _ => false,
}matches!(arg, syn::GenericArgument::Type(t) if mentions_lazy_dots(t)),
411                    ),
412                    _ => false,
413                }
414        }),
415        syn::Type::Reference(r) => mentions_lazy_dots(&r.elem),
416        syn::Type::Paren(p) => mentions_lazy_dots(&p.elem),
417        syn::Type::Group(g) => mentions_lazy_dots(&g.elem),
418        syn::Type::Tuple(t) => t.elems.iter().any(mentions_lazy_dots),
419        syn::Type::Array(a) => mentions_lazy_dots(&a.elem),
420        syn::Type::Slice(s) => mentions_lazy_dots(&s.elem),
421        _ => false,
422    }
423}
424
425// endregion
426
427// region: unevaluated-argument markers (#1835)
428
429/// Which unevaluated-argument marker a parameter takes.
430#[derive(#[automatically_derived]impl ::core::fmt::Debug for UnevaluatedKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                UnevaluatedKind::Quoted => "Quoted",
                UnevaluatedKind::Quosure => "Quosure",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for UnevaluatedKind {
}
#[automatically_derived]impl ::core::clone::Clone for UnevaluatedKind {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for UnevaluatedKind { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    UnevaluatedKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for UnevaluatedKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for UnevaluatedKind { }Eq)]
431pub(crate) enum UnevaluatedKind {
432    /// `Quoted`: base R's `substitute(x)` and `parent.frame()`.
433    Quoted,
434    /// `Quosure`: `rlang::enquo(x)`.
435    Quosure,
436}
437
438impl UnevaluatedKind {
439    /// The marker's type name, for diagnostics.
440    pub(crate) fn name(self) -> &'static str {
441        match self {
442            Self::Quoted => "Quoted",
443            Self::Quosure => "Quosure",
444        }
445    }
446
447    /// The `.Call()` argument the R wrapper passes for parameter `p`: the
448    /// missing-argument sentinel, as for `Missing<T>`, else the capture. Never
449    /// forces `p`.
450    pub(crate) fn r_call_arg(self, p: &str) -> String {
451        let capture = match self {
452            Self::Quoted => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("list(substitute({0}), parent.frame())",
                p))
    })format!("list(substitute({p}), parent.frame())"),
453            Self::Quosure => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rlang::enquo({0})", p))
    })format!("rlang::enquo({p})"),
454        };
455        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if (missing({0})) quote(expr=) else {1}",
                p, capture))
    })format!("if (missing({p})) quote(expr=) else {capture}")
456    }
457
458    /// The marker's path in `miniextendr_api`.
459    pub(crate) fn api_path(self) -> proc_macro2::TokenStream {
460        match self {
461            Self::Quoted => {
    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, "Quoted");
    _s
}quote::quote!(::miniextendr_api::Quoted),
462            Self::Quosure => {
    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, "Quosure");
    _s
}quote::quote!(::miniextendr_api::Quosure),
463        }
464    }
465
466    /// The marker a path segment names: `Quoted` / `Quosure`, bare or with
467    /// lifetime arguments only (`Quoted<'_>`).
468    fn of_segment(seg: &syn::PathSegment) -> Option<Self> {
469        let lifetimes_only = match &seg.arguments {
470            syn::PathArguments::None => true,
471            syn::PathArguments::AngleBracketed(ab) => ab
472                .args
473                .iter()
474                .all(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
    syn::GenericArgument::Lifetime(_) => true,
    _ => false,
}matches!(arg, syn::GenericArgument::Lifetime(_))),
475            syn::PathArguments::Parenthesized(_) => false,
476        };
477        if !lifetimes_only {
478            return None;
479        }
480        match seg.ident.to_string().as_str() {
481            "Quoted" => Some(Self::Quoted),
482            "Quosure" => Some(Self::Quosure),
483            _ => None,
484        }
485    }
486}
487
488/// An unevaluated-argument parameter: `Quoted` / `Quosure`, or either inside
489/// `Missing<..>` (`optional`).
490#[derive(#[automatically_derived]impl ::core::fmt::Debug for UnevaluatedParam {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "UnevaluatedParam kind optional", &self.kind, &&self.optional)
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for UnevaluatedParam {
}
#[automatically_derived]impl ::core::clone::Clone for UnevaluatedParam {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<UnevaluatedKind>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for UnevaluatedParam { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    UnevaluatedParam {
}
#[automatically_derived]impl ::core::cmp::PartialEq for UnevaluatedParam {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.optional == other.optional && self.kind == other.kind
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for UnevaluatedParam {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<UnevaluatedKind>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq)]
491pub(crate) struct UnevaluatedParam {
492    pub(crate) kind: UnevaluatedKind,
493    /// `Missing<Quoted>` / `Missing<Quosure>`: an omitted argument is
494    /// `Missing::Absent` instead of an error.
495    pub(crate) optional: bool,
496}
497
498/// Detect an unevaluated-argument parameter type, matched on the last path
499/// segment like the other markers: `Quoted`, `Quosure`, or one of them as the
500/// type argument of `Missing<..>`. Any other position (`Option<Quoted>`,
501/// `&Quoted`) is not one; [`mentions_unevaluated_marker`] lets the caller
502/// refuse it.
503pub(crate) fn unevaluated_param(ty: &syn::Type) -> Option<UnevaluatedParam> {
504    let marker = |ty: &syn::Type| match ty {
505        syn::Type::Path(p) => p.path.segments.last().and_then(UnevaluatedKind::of_segment),
506        _ => None,
507    };
508    if let Some(kind) = marker(ty) {
509        return Some(UnevaluatedParam {
510            kind,
511            optional: false,
512        });
513    }
514    let inner = crate::miniextendr_fn::get_missing_inner_type(ty)?;
515    marker(inner).map(|kind| UnevaluatedParam {
516        kind,
517        optional: true,
518    })
519}
520
521/// Whether `ty` names `Quoted` / `Quosure` anywhere, at any depth.
522pub(crate) fn mentions_unevaluated_marker(ty: &syn::Type) -> bool {
523    match ty {
524        syn::Type::Path(p) => p.path.segments.iter().any(|seg| {
525            #[allow(non_exhaustive_omitted_patterns)] match seg.ident.to_string().as_str()
    {
    "Quoted" | "Quosure" => true,
    _ => false,
}matches!(seg.ident.to_string().as_str(), "Quoted" | "Quosure")
526                || match &seg.arguments {
527                    syn::PathArguments::AngleBracketed(ab) => ab.args.iter().any(|arg| {
528                        #[allow(non_exhaustive_omitted_patterns)] match arg {
    syn::GenericArgument::Type(t) if mentions_unevaluated_marker(t) => true,
    _ => false,
}matches!(arg, syn::GenericArgument::Type(t) if mentions_unevaluated_marker(t))
529                    }),
530                    _ => false,
531                }
532        }),
533        syn::Type::Reference(r) => mentions_unevaluated_marker(&r.elem),
534        syn::Type::Paren(p) => mentions_unevaluated_marker(&p.elem),
535        syn::Type::Group(g) => mentions_unevaluated_marker(&g.elem),
536        syn::Type::Tuple(t) => t.elems.iter().any(mentions_unevaluated_marker),
537        syn::Type::Array(a) => mentions_unevaluated_marker(&a.elem),
538        syn::Type::Slice(s) => mentions_unevaluated_marker(&s.elem),
539        _ => false,
540    }
541}
542
543// endregion
544
545// region: parameter markers (#1566 §2)
546
547/// A by-value parameter marker the macro peels from a parameter type before
548/// any R-side analysis: the parameter converts as the inner type, and the C
549/// wrapper wraps the value ([`ParamMarker::wrap`]) before the call.
550#[derive(#[automatically_derived]impl ::core::fmt::Debug for ParamMarker {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ParamMarker::Checked => "Checked",
                ParamMarker::Unchecked => "Unchecked",
                ParamMarker::NonNa => "NonNa",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ParamMarker {
}
#[automatically_derived]impl ::core::clone::Clone for ParamMarker {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ParamMarker { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ParamMarker {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ParamMarker {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ParamMarker { }Eq)]
551pub(crate) enum ParamMarker {
552    /// `Checked<T>`: keep the parameter's type-derived R-side checks.
553    Checked,
554    /// `Unchecked<T>`: drop them.
555    Unchecked,
556    /// `NonNa<T>`: the parameter's `no_na` check, written in the type; the C
557    /// wrapper also checks the argument before converting it.
558    NonNa,
559}
560
561/// The decision family a [`ParamMarker`] belongs to: a parameter carries at
562/// most one marker per family.
563#[derive(#[automatically_derived]impl ::core::fmt::Debug for ParamMarkerFamily {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ParamMarkerFamily::Preconditions => "Preconditions",
                ParamMarkerFamily::NoNa => "NoNa",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ParamMarkerFamily {
}
#[automatically_derived]impl ::core::clone::Clone for ParamMarkerFamily {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ParamMarkerFamily { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ParamMarkerFamily {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ParamMarkerFamily {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ParamMarkerFamily { }Eq)]
564pub(crate) enum ParamMarkerFamily {
565    /// `Checked` / `Unchecked`: the type-derived R-side checks.
566    Preconditions,
567    /// `NonNa`: the `no_na` check.
568    NoNa,
569}
570
571impl ParamMarker {
572    /// The marker for a path segment's name, if it is one.
573    fn from_ident(ident: &syn::Ident) -> Option<Self> {
574        match ident.to_string().as_str() {
575            "Checked" => Some(Self::Checked),
576            "Unchecked" => Some(Self::Unchecked),
577            "NonNa" => Some(Self::NonNa),
578            _ => None,
579        }
580    }
581
582    /// The type's name as written in source.
583    pub(crate) fn name(self) -> &'static str {
584        match self {
585            Self::Checked => "Checked",
586            Self::Unchecked => "Unchecked",
587            Self::NonNa => "NonNa",
588        }
589    }
590
591    /// Which decision the marker makes.
592    pub(crate) fn family(self) -> ParamMarkerFamily {
593        match self {
594            Self::Checked | Self::Unchecked => ParamMarkerFamily::Preconditions,
595            Self::NonNa => ParamMarkerFamily::NoNa,
596        }
597    }
598
599    /// The C wrapper's rebinding of the converted `value` as the marked
600    /// type. A `NonNa` is built unchecked: the wrapper refused an argument
601    /// holding an `NA` before converting it.
602    pub(crate) fn wrap(self, value: &syn::Ident) -> proc_macro2::TokenStream {
603        match self {
604            Self::Checked => {
    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, "Checked");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "from_inner");
    ::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
        });
    _s
}quote::quote!(::miniextendr_api::Checked::from_inner(#value)),
605            Self::Unchecked => {
    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, "Unchecked");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "from_inner");
    ::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
        });
    _s
}quote::quote!(::miniextendr_api::Unchecked::from_inner(#value)),
606            // SAFETY (of the emitted `unsafe`): the C wrapper ran the
607            // marker's `__mx_any_na` check on the argument before converting
608            // it, and returned the argument error when it held an `NA`.
609            Self::NonNa => {
610                {
    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, "NonNa");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "new_unchecked");
            ::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
                });
            _s
        });
    _s
}quote::quote!(unsafe { ::miniextendr_api::NonNa::new_unchecked(#value) })
611            }
612        }
613    }
614
615    /// The precondition decision: `Some(true)` keeps the type-derived
616    /// checks, `Some(false)` drops them; `None` for a marker of another
617    /// family.
618    pub(crate) fn preconditions(self) -> Option<bool> {
619        match self {
620            Self::Checked => Some(true),
621            Self::Unchecked => Some(false),
622            Self::NonNa => None,
623        }
624    }
625
626    /// The method attribute an impl spells for the marker of a trait
627    /// method's parameter `param`: `preconditions(x)`, `no_preconditions(x)`
628    /// or `no_na(x)`.
629    pub(crate) fn impl_keyword(self, param: &str) -> String {
630        match self {
631            Self::Checked => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("preconditions({0})", param))
    })format!("preconditions({param})"),
632            Self::Unchecked => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no_preconditions({0})", param))
    })format!("no_preconditions({param})"),
633            Self::NonNa => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no_na({0})", param))
    })format!("no_na({param})"),
634        }
635    }
636}
637
638/// The marker a type's outermost segment names, with its single type
639/// argument. Matched on the last path segment like [`peel_visibility_marker`];
640/// a bare `Checked` (no type argument) or one with two is not a marker (the
641/// fail-safe direction: the type then fails to convert).
642fn outer_param_marker(ty: &syn::Type) -> Option<(ParamMarker, &syn::Type)> {
643    let syn::Type::Path(p) = ty else {
644        return None;
645    };
646    let seg = p.path.segments.last()?;
647    let marker = ParamMarker::from_ident(&seg.ident)?;
648    let syn::PathArguments::AngleBracketed(ab) = &seg.arguments else {
649        return None;
650    };
651    let mut types = ab.args.iter().filter_map(|arg| match arg {
652        syn::GenericArgument::Type(t) => Some(t),
653        _ => None,
654    });
655    let inner = types.next()?;
656    if types.next().is_some() {
657        return None;
658    }
659    Some((marker, inner))
660}
661
662/// Peel the parameter markers off a parameter type, outermost first: returns
663/// the markers in the order written and the inner type the parameter
664/// converts as. `Checked<Strict<T>>`-style stacks of different families peel
665/// in one pass; two markers of one family (`Checked<Unchecked<T>>`) are an
666/// error, as is a marker nested inside `Option` / `Nullable` / `Missing` /
667/// `Vec` / `&` (at any depth of those), where the conversion has no marker
668/// to unwrap.
669pub(crate) fn peel_param_markers(ty: &syn::Type) -> syn::Result<(Vec<ParamMarker>, &syn::Type)> {
670    let mut markers: Vec<ParamMarker> = Vec::new();
671    let mut inner = ty;
672    while let Some((marker, next)) = outer_param_marker(inner) {
673        if let Some(first) = markers.iter().find(|m| m.family() == marker.family()) {
674            let message = match marker.family() {
675                ParamMarkerFamily::Preconditions => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("at most one precondition marker per parameter: `{0}` already decides this parameter\'s R-side type checks, so drop `{1}`",
                first.name(), marker.name()))
    })format!(
676                    "at most one precondition marker per parameter: `{}` already decides this \
677                     parameter's R-side type checks, so drop `{}`",
678                    first.name(),
679                    marker.name()
680                ),
681                ParamMarkerFamily::NoNa => {
682                    "`NonNa<NonNa<T>>`: one `NonNa` already refuses an `NA`, so drop the \
683                     inner one"
684                        .to_string()
685                }
686            };
687            return Err(syn::Error::new_spanned(ty, message));
688        }
689        markers.push(marker);
690        inner = next;
691    }
692    if markers.contains(&ParamMarker::NonNa)
693        && let Some((_, spelling)) = optional_layer(inner)
694    {
695        return Err(syn::Error::new_spanned(
696            ty,
697            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`NonNa<{0}<T>>`: a value without `NA` leaves `{0}` only `NULL` to mean; take `NonNa<T>`, or `{0}<T>` with `#[miniextendr(no_na)]` to accept `NULL`",
                spelling.name()))
    })format!(
698                "`NonNa<{0}<T>>`: a value without `NA` leaves `{0}` only `NULL` to mean; \
699                 take `NonNa<T>`, or `{0}<T>` with `#[miniextendr(no_na)]` to accept `NULL`",
700                spelling.name()
701            ),
702        ));
703    }
704    if let Some(nested) = nested_param_marker(inner) {
705        return Err(syn::Error::new_spanned(
706            ty,
707            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("put `{0}` outermost: `{0}<Option<T>>`, not `Option<{0}<T>>`; the marker applies to the whole parameter",
                nested.name()))
    })format!(
708                "put `{0}` outermost: `{0}<Option<T>>`, not `Option<{0}<T>>`; the marker \
709                 applies to the whole parameter",
710                nested.name()
711            ),
712        ));
713    }
714    Ok((markers, inner))
715}
716
717/// A marker inside `Option<..>` / `Nullable<..>` / `Missing<..>` / `Vec<..>`
718/// / `&..`, at any depth of those wrappers.
719fn nested_param_marker(ty: &syn::Type) -> Option<ParamMarker> {
720    let arg = match ty {
721        syn::Type::Reference(r) => r.elem.as_ref(),
722        syn::Type::Paren(p) => p.elem.as_ref(),
723        syn::Type::Path(p) => match optional_inner_type(ty) {
724            Some(inner) => inner,
725            None => {
726                let seg = p.path.segments.last()?;
727                if !#[allow(non_exhaustive_omitted_patterns)] match seg.ident.to_string().as_str()
    {
    "Missing" | "Vec" => true,
    _ => false,
}matches!(seg.ident.to_string().as_str(), "Missing" | "Vec") {
728                    return None;
729                }
730                first_type_argument(seg)?
731            }
732        },
733        _ => return None,
734    };
735    match outer_param_marker(arg) {
736        Some((marker, _)) => Some(marker),
737        None => nested_param_marker(arg),
738    }
739}
740
741/// Whether any of `markers` is in `family`, and which.
742pub(crate) fn marker_in_family(
743    markers: &[ParamMarker],
744    family: ParamMarkerFamily,
745) -> Option<ParamMarker> {
746    markers.iter().copied().find(|m| m.family() == family)
747}
748
749// endregion
750
751// region: type rendering for messages
752
753/// Render a type the way it is written in Rust source, for user-facing
754/// messages: `AsFromStrVec<i32>`, `Either<i32, String>`, `&[f64]`,
755/// `&'a str`, `Option<Vec<String>>`.
756///
757/// `quote!(#ty).to_string()` puts a space between every token
758/// (`AsFromStrVec < i32 >`); this walks the tokens and applies the usual
759/// spacing instead: none around `<`, `>`, `::`, after `&` / `*` / `'`, or
760/// inside brackets; a space after `,` / `;`, around `+` / `=` / `->`, between
761/// two words, and between `mut` / `const` / `dyn` / `impl` or a lifetime and
762/// a following bracket group (`&mut [T]`, `&'a [T]`).
763pub(crate) fn type_display(ty: &syn::Type) -> String {
764    let mut out = String::new();
765    write_type_tokens({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&ty, &mut _s);
    _s
}quote::quote!(#ty), &mut out);
766    out
767}
768
769fn write_type_tokens(tokens: proc_macro2::TokenStream, out: &mut String) {
770    use proc_macro2::{Delimiter, Spacing, TokenTree};
771
772    /// What the previous token leaves for the next one to attach to.
773    #[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Prev {
}
#[automatically_derived]impl ::core::clone::Clone for Prev {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Prev { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Prev { }
#[automatically_derived]impl ::core::cmp::PartialEq for Prev {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
774    enum Prev {
775        /// Start of the stream, or a token after which nothing is spaced
776        /// (`<`, `&`, `*`, `::`, a trailing-space punct like `, `).
777        Glue,
778        /// A lifetime's `'`: the next ident attaches.
779        Tick,
780        /// An identifier, literal or closing `>`: a following word is spaced.
781        Word,
782        /// `mut` / `const` / `dyn` / `impl` or a lifetime: a following word
783        /// or group is spaced.
784        Keyword,
785    }
786
787    let mut prev = Prev::Glue;
788    // `-` of a pending `->` and the first `:` of a `::`.
789    let mut pending_arrow = false;
790    let mut pending_path_sep = false;
791    for tt in tokens {
792        match tt {
793            TokenTree::Ident(ident) => {
794                let name = ident.to_string();
795                if #[allow(non_exhaustive_omitted_patterns)] match prev {
    Prev::Word | Prev::Keyword => true,
    _ => false,
}matches!(prev, Prev::Word | Prev::Keyword) {
796                    out.push(' ');
797                }
798                out.push_str(&name);
799                prev = if prev == Prev::Tick
800                    || #[allow(non_exhaustive_omitted_patterns)] match name.as_str() {
    "mut" | "const" | "dyn" | "impl" => true,
    _ => false,
}matches!(name.as_str(), "mut" | "const" | "dyn" | "impl")
801                {
802                    Prev::Keyword
803                } else {
804                    Prev::Word
805                };
806            }
807            TokenTree::Literal(lit) => {
808                if #[allow(non_exhaustive_omitted_patterns)] match prev {
    Prev::Word | Prev::Keyword => true,
    _ => false,
}matches!(prev, Prev::Word | Prev::Keyword) {
809                    out.push(' ');
810                }
811                out.push_str(&lit.to_string());
812                prev = Prev::Word;
813            }
814            TokenTree::Group(group) => {
815                if prev == Prev::Keyword
816                    || (prev == Prev::Word && group.delimiter() == Delimiter::Bracket)
817                {
818                    out.push(' ');
819                }
820                let (open, close) = match group.delimiter() {
821                    Delimiter::Parenthesis => ("(", ")"),
822                    Delimiter::Bracket => ("[", "]"),
823                    Delimiter::Brace => ("{", "}"),
824                    Delimiter::None => ("", ""),
825                };
826                out.push_str(open);
827                write_type_tokens(group.stream(), out);
828                out.push_str(close);
829                prev = Prev::Word;
830            }
831            TokenTree::Punct(punct) => {
832                let c = punct.as_char();
833                match c {
834                    ',' | ';' => {
835                        out.push(c);
836                        out.push(' ');
837                        prev = Prev::Glue;
838                    }
839                    '+' | '=' => {
840                        out.push(' ');
841                        out.push(c);
842                        out.push(' ');
843                        prev = Prev::Glue;
844                    }
845                    '-' if punct.spacing() == Spacing::Joint => {
846                        out.push_str(" -");
847                        pending_arrow = true;
848                    }
849                    '>' if pending_arrow => {
850                        out.push_str("> ");
851                        pending_arrow = false;
852                        prev = Prev::Glue;
853                    }
854                    '>' => {
855                        out.push('>');
856                        prev = Prev::Word;
857                    }
858                    ':' if punct.spacing() == Spacing::Joint => {
859                        out.push(':');
860                        pending_path_sep = true;
861                        prev = Prev::Glue;
862                    }
863                    ':' if pending_path_sep => {
864                        out.push(':');
865                        pending_path_sep = false;
866                        prev = Prev::Glue;
867                    }
868                    ':' => {
869                        // Associated-type bound: `Item: Clone`.
870                        out.push_str(": ");
871                        prev = Prev::Glue;
872                    }
873                    '\'' => {
874                        if #[allow(non_exhaustive_omitted_patterns)] match prev {
    Prev::Word | Prev::Keyword => true,
    _ => false,
}matches!(prev, Prev::Word | Prev::Keyword) {
875                            out.push(' ');
876                        }
877                        out.push('\'');
878                        prev = Prev::Tick;
879                    }
880                    _ => {
881                        out.push(c);
882                        prev = Prev::Glue;
883                    }
884                }
885            }
886        }
887    }
888}
889
890/// `ty` with every lifetime replaced by `'_`, for a `let` binding annotation
891/// in generated code: `&'a [f64]` → `&'_ [f64]`. The binding then names the
892/// target type (so the error type of its conversion is known where the
893/// wrapper inspects it) without depending on the user's lifetime parameters
894/// being in scope.
895pub(crate) fn erase_lifetimes(ty: &syn::Type) -> syn::Type {
896    use proc_macro2::{Group, Ident, TokenStream, TokenTree};
897
898    fn erase(tokens: TokenStream) -> TokenStream {
899        let mut out = Vec::new();
900        let mut iter = tokens.into_iter();
901        while let Some(tt) = iter.next() {
902            match tt {
903                TokenTree::Punct(p) if p.as_char() == '\'' => {
904                    out.push(TokenTree::Punct(p));
905                    if let Some(TokenTree::Ident(lifetime)) = iter.next() {
906                        out.push(TokenTree::Ident(Ident::new("_", lifetime.span())));
907                    }
908                }
909                TokenTree::Group(g) => {
910                    let mut erased = Group::new(g.delimiter(), erase(g.stream()));
911                    erased.set_span(g.span());
912                    out.push(TokenTree::Group(erased));
913                }
914                other => out.push(other),
915            }
916        }
917        out.into_iter().collect()
918    }
919
920    syn::parse2(erase({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&ty, &mut _s);
    _s
}quote::quote!(#ty))).unwrap_or_else(|_| ty.clone())
921}
922
923// endregion
924
925#[cfg(test)]
926mod tests;
927
928/// `true` when the last path segment of `ty` is `Option<...>`.
929pub(crate) fn is_option_type(ty: &syn::Type) -> bool {
930    option_inner_type(ty).is_some()
931}
932
933/// Return `T` for an `Option<T>` type, `None` for anything else.
934///
935/// `Option` only: the callers that build a value of the written type use it.
936/// Code that classifies an argument type reads [`optional_layer`], which
937/// also takes `Nullable<T>`.
938pub(crate) fn option_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
939    let syn::Type::Path(tp) = ty else {
940        return None;
941    };
942    let seg = tp.path.segments.last()?;
943    if seg.ident != "Option" {
944        return None;
945    }
946    first_type_argument(seg)
947}
948
949// region: optional argument types (#2294)
950
951/// How an optional argument type is spelled: `Option<T>`, or
952/// `miniextendr_api::Nullable<T>`, whose `TryFromSexp` forwards to
953/// `Option<T>`'s (`NULL` and `NA` read `None`).
954///
955/// A `Nullable<T>` argument behaves as `Option<T>` (#2294): the R-side
956/// checks, the conversion's wording, `coerce`, `no_na` and the choice
957/// parameters read it through [`optional_layer`]. Code that builds the value
958/// through an `Option` helper (a `coerce` converter, a `match_arg` decoder)
959/// wraps the result for `Nullable` ([`OptionalSpelling::wrap_ok`]).
960#[derive(#[automatically_derived]impl ::core::fmt::Debug for OptionalSpelling {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                OptionalSpelling::Option => "Option",
                OptionalSpelling::Nullable => "Nullable",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for OptionalSpelling {
}
#[automatically_derived]impl ::core::clone::Clone for OptionalSpelling {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for OptionalSpelling { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    OptionalSpelling {
}
#[automatically_derived]impl ::core::cmp::PartialEq for OptionalSpelling {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for OptionalSpelling { }Eq)]
961pub(crate) enum OptionalSpelling {
962    /// `Option<T>`.
963    Option,
964    /// `Nullable<T>`.
965    Nullable,
966}
967
968impl OptionalSpelling {
969    /// The type's name as written in source.
970    pub(crate) fn name(self) -> &'static str {
971        match self {
972            Self::Option => "Option",
973            Self::Nullable => "Nullable",
974        }
975    }
976
977    /// `result`, a `Result<Option<T>, E>` expression, as a
978    /// `Result<Self<T>, E>`: unchanged for `Option`, its `Ok` value wrapped
979    /// in `Nullable` for `Nullable`.
980    pub(crate) fn wrap_ok(self, result: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
981        match self {
982            Self::Option => result,
983            Self::Nullable => {
    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, "map");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::ToTokens::to_tokens(&result, &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, "Nullable");
            _s
        });
    _s
}quote::quote! {
984                ::core::result::Result::map(#result, ::miniextendr_api::Nullable)
985            },
986        }
987    }
988}
989
990/// `(T, spelling)` for an `Option<T>` or `Nullable<T>` type (matched by the
991/// last path segment, like `Missing`), `None` for anything else.
992pub(crate) fn optional_layer(ty: &syn::Type) -> Option<(&syn::Type, OptionalSpelling)> {
993    let syn::Type::Path(tp) = ty else {
994        return None;
995    };
996    let seg = tp.path.segments.last()?;
997    let spelling = if seg.ident == "Option" {
998        OptionalSpelling::Option
999    } else if seg.ident == "Nullable" {
1000        OptionalSpelling::Nullable
1001    } else {
1002        return None;
1003    };
1004    first_type_argument(seg).map(|inner| (inner, spelling))
1005}
1006
1007/// `T` for an `Option<T>` or `Nullable<T>` type, `None` for anything else
1008/// (see [`optional_layer`]).
1009pub(crate) fn optional_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
1010    optional_layer(ty).map(|(inner, _)| inner)
1011}
1012
1013/// `true` when `ty` is `Option<T>` or `Nullable<T>` (see [`optional_layer`]).
1014pub(crate) fn is_optional_type(ty: &syn::Type) -> bool {
1015    optional_layer(ty).is_some()
1016}
1017
1018/// `T` for a `Nullable<T>` type, `None` for anything else (an `Option<T>`
1019/// included).
1020pub(crate) fn nullable_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
1021    optional_layer(ty)
1022        .filter(|(_, spelling)| *spelling == OptionalSpelling::Nullable)
1023        .map(|(inner, _)| inner)
1024}
1025
1026// endregion
1027
1028/// Return `T` for an `ExternalPtr<T>` class handle, `ty` itself otherwise.
1029///
1030/// `IntoR for ExternalPtr<T>` produces the same bare `EXTPTRSXP` as a bare
1031/// `T`, so both return-wrapping paths (inferred and explicit `wrap` /
1032/// `WrapAs*`) name the class through the handle (#1375).
1033pub(crate) fn peel_external_ptr(ty: &syn::Type) -> &syn::Type {
1034    let syn::Type::Path(tp) = ty else {
1035        return ty;
1036    };
1037    match tp.path.segments.last() {
1038        Some(seg) if seg.ident == "ExternalPtr" => first_type_argument(seg).unwrap_or(ty),
1039        _ => ty,
1040    }
1041}
1042
1043// region: choice-parameter layers (`match_arg` / `choices`)
1044
1045/// The wrappers around the value of a `match_arg` / `choices` parameter,
1046/// peeled outermost first: `Missing<..>`, then `Option<..>` (or
1047/// `Nullable<..>`, read as `Option`, #2294), then `Either<T, R>` with the
1048/// choice on the left (a scalar choice, or a `several_ok` list:
1049/// `Either<Vec<T>, R>`, #1612). A plain `T` (or a plain `several_ok`
1050/// container) has none.
1051///
1052/// Each layer changes one contract and leaves the rest to the layer below:
1053/// `Missing` reports an omitted argument as `Missing::Absent` and keeps the
1054/// choice vector as the R formal (#1551), `Option` turns `NULL` into `None`
1055/// (#1473), and `Either` sends every argument that is not character or
1056/// factor to its `R` arm instead of the choice check.
1057#[derive(#[automatically_derived]impl<'a> ::core::fmt::Debug for ChoiceLayers<'a> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "ChoiceLayers missing nullable either_right value", &self.missing,
            &self.nullable, &self.either_right, &&self.value)
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl<'a>
    ::core::clone::TrivialClone for ChoiceLayers<'a> {
}
#[automatically_derived]impl<'a> ::core::clone::Clone for ChoiceLayers<'a> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<Option<OptionalSpelling>>;
        let _: ::core::clone::AssertParamIsClone<Option<&'a syn::Type>>;
        let _: ::core::clone::AssertParamIsClone<&'a syn::Type>;
        *self
    }
}Clone, #[automatically_derived]impl<'a> ::core::marker::Copy for ChoiceLayers<'a> { }Copy)]
1058pub(crate) struct ChoiceLayers<'a> {
1059    /// `Missing<..>` is the outermost wrapper.
1060    pub missing: bool,
1061    /// `Option<..>` or `Nullable<..>` wraps the value (inside `Missing`, if
1062    /// present), spelled as this says.
1063    pub nullable: Option<OptionalSpelling>,
1064    /// `Either<T, R>` wraps the value (inside the others): its `R` arm.
1065    pub either_right: Option<&'a syn::Type>,
1066    /// The type under the layers: the `MatchArg` type (or the string type of a
1067    /// `choices` parameter) for a scalar, the container for `several_ok`.
1068    pub value: &'a syn::Type,
1069}
1070
1071/// Peel the [`ChoiceLayers`] of a choice parameter's type.
1072pub(crate) fn choice_layers(ty: &syn::Type) -> ChoiceLayers<'_> {
1073    let (missing, ty) = match crate::miniextendr_fn::get_missing_inner_type(ty) {
1074        Some(inner) => (true, inner),
1075        None => (false, ty),
1076    };
1077    let (nullable, ty) = match optional_layer(ty) {
1078        Some((inner, spelling)) => (Some(spelling), inner),
1079        None => (None, ty),
1080    };
1081    let (either_right, value) = match either_arms(ty) {
1082        Some((left, right)) => (Some(right), left),
1083        None => (None, ty),
1084    };
1085    ChoiceLayers {
1086        missing,
1087        nullable,
1088        either_right,
1089        value,
1090    }
1091}
1092
1093/// The layer name (`"Missing"` / `"Option"` / `"Nullable"` / `"Either"`)
1094/// when `ty` is itself a layer type, i.e. when it sits where the choice value
1095/// should be. Used to reject layers in an unsupported order, such as
1096/// `Option<Missing<T>>` or `Either<Option<T>, R>`.
1097pub(crate) fn choice_layer_name(ty: &syn::Type) -> Option<&'static str> {
1098    if crate::miniextendr_fn::get_missing_inner_type(ty).is_some() {
1099        Some("Missing")
1100    } else if let Some((_, spelling)) = optional_layer(ty) {
1101        Some(spelling.name())
1102    } else if either_arms(ty).is_some() {
1103        Some("Either")
1104    } else {
1105        None
1106    }
1107}
1108
1109/// `(L, R)` for an `Either<L, R>` type (last path segment `Either` with two
1110/// type arguments), `None` for anything else.
1111pub(crate) fn either_arms(ty: &syn::Type) -> Option<(&syn::Type, &syn::Type)> {
1112    let syn::Type::Path(tp) = ty else {
1113        return None;
1114    };
1115    let seg = tp.path.segments.last()?;
1116    if seg.ident != "Either" {
1117        return None;
1118    }
1119    let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
1120        return None;
1121    };
1122    let mut types = args.args.iter().filter_map(|arg| match arg {
1123        syn::GenericArgument::Type(ty) => Some(ty),
1124        _ => None,
1125    });
1126    match (types.next(), types.next(), types.next()) {
1127        (Some(left), Some(right), None) => Some((left, right)),
1128        _ => None,
1129    }
1130}
1131
1132/// How R documentation names a value of type `ty`, with its article: `"a data
1133/// frame"`, `"a list"`, `"a number"`, `"a character vector"`, ... Used for the
1134/// `R` arm of an `Either<T, R>` choice parameter in its auto-generated
1135/// `@param` line (`One of "a", "b", or a data frame.`). A type without an R
1136/// name falls back to its Rust spelling in code format.
1137pub(crate) fn r_value_noun(ty: &syn::Type) -> String {
1138    let named = match ty {
1139        syn::Type::Reference(r) => match r.elem.as_ref() {
1140            syn::Type::Slice(s) => vector_noun(&s.elem),
1141            elem => return r_value_noun(elem),
1142        },
1143        syn::Type::Slice(s) => vector_noun(&s.elem),
1144        syn::Type::Path(tp) => {
1145            tp.path
1146                .segments
1147                .last()
1148                .and_then(|seg| match seg.ident.to_string().as_str() {
1149                    "DataFrame" | "BuiltDataFrame" => Some("a data frame"),
1150                    "List" | "ListMut" | "NamedList" | "HashMap" | "BTreeMap" => Some("a list"),
1151                    "String" | "str" | "char" | "PathBuf" | "Path" => Some("a string"),
1152                    "f64" | "f32" => Some("a number"),
1153                    "i8" | "i16" | "i32" | "i64" | "isize" | "u16" | "u32" | "u64" | "usize" => {
1154                        Some("an integer")
1155                    }
1156                    "bool" | "Rbool" | "Rboolean" => Some("TRUE or FALSE"),
1157                    "Rcomplex" => Some("a complex number"),
1158                    "ExternalPtr" => Some("an external pointer"),
1159                    "SEXP" => Some("any other R value"),
1160                    "Vec" => first_type_argument(seg).and_then(vector_noun),
1161                    _ => None,
1162                })
1163        }
1164        _ => None,
1165    };
1166    named.map_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a `{0}`", type_display(ty)))
    })format!("a `{}`", type_display(ty)), str::to_string)
1167}
1168
1169/// The R name of a vector with elements of type `elem`, if it has one.
1170fn vector_noun(elem: &syn::Type) -> Option<&'static str> {
1171    let syn::Type::Path(tp) = elem else {
1172        return None;
1173    };
1174    let seg = tp.path.segments.last()?;
1175    match seg.ident.to_string().as_str() {
1176        "f64" | "f32" => Some("a numeric vector"),
1177        "i8" | "i16" | "i32" | "i64" | "isize" | "u16" | "u32" | "u64" | "usize" => {
1178            Some("an integer vector")
1179        }
1180        "String" | "str" => Some("a character vector"),
1181        "bool" | "Rbool" | "Rboolean" => Some("a logical vector"),
1182        "u8" => Some("a raw vector"),
1183        "Option" => first_type_argument(seg).and_then(vector_noun),
1184        _ => None,
1185    }
1186}
1187
1188/// Resolve the `MatchArg`-bound type behind a `match_arg` parameter.
1189///
1190/// The [`ChoiceLayers`] are peeled first. A `several_ok` parameter is then a
1191/// container (`Vec<T>`, `Box<[T]>`, `[T; N]`, `&[T]`), so the element type is
1192/// the one carrying `CHOICES`; a scalar parameter's value is that type itself.
1193/// Anything else is returned unchanged, and the `MatchArg` bound on the
1194/// generated code reports the mistake.
1195///
1196/// Shared by the standalone-fn path (`lib.rs`) and the impl-method path
1197/// (`miniextendr_impl.rs`) so the two cannot resolve the type differently.
1198pub(crate) fn match_arg_choices_ty(param_ty: &syn::Type, several_ok: bool) -> &syn::Type {
1199    let value = choice_layers(param_ty).value;
1200    if several_ok {
1201        classify_several_ok_container(value)
1202            .map(|(_, inner)| inner)
1203            .unwrap_or(value)
1204    } else {
1205        value
1206    }
1207}
1208
1209// endregion
1210
1211/// Container family for a `several_ok` parameter, returned by
1212/// [`classify_several_ok_container`].
1213#[derive(#[automatically_derived]impl ::core::fmt::Debug for SeveralOkContainer {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Vec => ::core::fmt::Formatter::write_str(f, "Vec"),
            Self::BoxedSlice =>
                ::core::fmt::Formatter::write_str(f, "BoxedSlice"),
            Self::Array(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Array",
                    &__self_0),
            Self::BorrowedSlice =>
                ::core::fmt::Formatter::write_str(f, "BorrowedSlice"),
        }
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for SeveralOkContainer {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Vec => SeveralOkContainer::Vec,
            Self::BoxedSlice => SeveralOkContainer::BoxedSlice,
            Self::Array(__self_0) =>
                SeveralOkContainer::Array(::core::clone::Clone::clone(__self_0)),
            Self::BorrowedSlice => SeveralOkContainer::BorrowedSlice,
        }
    }
}Clone)]
1214pub(crate) enum SeveralOkContainer {
1215    /// `Vec<T>`
1216    Vec,
1217    /// `Box<[T]>`
1218    BoxedSlice,
1219    /// `[T; N]` — the `usize` is the fixed array length N
1220    Array(usize),
1221    /// `&[T]` or `&mut [T]` — allocate `Vec<T>` then borrow
1222    BorrowedSlice,
1223}
1224
1225/// Classify a `several_ok` parameter type into one of the four container
1226/// families and extract its inner element type `T`.
1227///
1228/// Returns `Some((container, inner_ty))` or `None` if the type is not one of
1229/// the four accepted container shapes.
1230pub(crate) fn classify_several_ok_container(
1231    ty: &syn::Type,
1232) -> Option<(SeveralOkContainer, &syn::Type)> {
1233    match ty {
1234        // Vec<T>
1235        syn::Type::Path(tp) => {
1236            let seg = tp.path.segments.last()?;
1237            if seg.ident == "Vec" {
1238                let inner = first_type_argument(seg)?;
1239                return Some((SeveralOkContainer::Vec, inner));
1240            }
1241            // Box<[T]>
1242            if seg.ident == "Box"
1243                && let syn::PathArguments::AngleBracketed(ab) = &seg.arguments
1244            {
1245                for arg in &ab.args {
1246                    if let syn::GenericArgument::Type(syn::Type::Slice(s)) = arg {
1247                        return Some((SeveralOkContainer::BoxedSlice, s.elem.as_ref()));
1248                    }
1249                }
1250            }
1251            None
1252        }
1253        // [T; N]
1254        syn::Type::Array(arr) => {
1255            if let syn::Expr::Lit(syn::ExprLit {
1256                lit: syn::Lit::Int(n),
1257                ..
1258            }) = &arr.len
1259            {
1260                let n = n.base10_parse::<usize>().ok()?;
1261                return Some((SeveralOkContainer::Array(n), arr.elem.as_ref()));
1262            }
1263            None
1264        }
1265        // &[T] or &mut [T]
1266        syn::Type::Reference(r) => {
1267            if let syn::Type::Slice(s) = r.elem.as_ref() {
1268                return Some((SeveralOkContainer::BorrowedSlice, s.elem.as_ref()));
1269            }
1270            None
1271        }
1272        _ => None,
1273    }
1274}
1275
1276/// Whether a bare `&Self` / `&mut Self` parameter is mutable.
1277/// `None` means this is not a Self-reference parameter.
1278pub(crate) fn self_ref_mutability(ty: &syn::Type) -> Option<bool> {
1279    if let syn::Type::Reference(reference) = ty
1280        && let syn::Type::Path(path) = reference.elem.as_ref()
1281        && path.path.is_ident("Self")
1282    {
1283        Some(reference.mutability.is_some())
1284    } else {
1285        None
1286    }
1287}