Skip to main content

miniextendr_api/
newtype.rs

1//! Container conversions for newtypes and string-parsed types.
2//!
3//! `#[derive(TryFromSexp)]` / `#[derive(IntoR)]` on a single-field newtype
4//! (`struct UserId(Uuid)`) emit the scalar forwarding impls *and* a small marker
5//! impl from this module. The container blankets here then light up
6//! `Vec<UserId>`, `Option<UserId>`, and `Vec<Option<UserId>>` automatically — the
7//! newtype inherits the inner type's exact SEXPTYPE checks, NA policy, error
8//! text and `TryFromSexp::CHARACTER_ONLY` in every shape.
9//!
10//! A type parsed from an R string gets the same three shapes from
11//! [`try_from_sexp_via_str_parse!`](crate::try_from_sexp_via_str_parse), which
12//! implements [`TryFromSexpElement`] with
13//! [`ParsedRStr`](crate::from_r::ParsedRStr) as the inner type (#1766).
14//!
15//! # The containers forward; a check refuses
16//!
17//! The containers never call the element's own `TryFromSexp::try_from_sexp`.
18//! `Option<T>` reads `Option<T::Inner>`, `Vec<T>` reads `Vec<T::Inner>` and
19//! `Vec<Option<T>>` reads `Vec<Option<T::Inner>>`, each wrapping what it
20//! read with [`TryFromSexpElement::from_inner`]. So an element's scalar
21//! `try_from_sexp` must be the inner type's followed by `from_inner`, which
22//! is what the derive emits, and refusing values a type's inner type
23//! accepts belongs in [`TryFromSexpElement::check_sexp`], not in
24//! `try_from_sexp`. The check runs on the R value before it is read, in the
25//! scalar `try_from_sexp`, on any input but `NULL` and a plain `NA` for
26//! `Option<T>` (both are "not given", #2305), and for `Vec<T>` /
27//! `Vec<Option<T>>` where R keeps the element's class.
28//! `#[derive(TryFromSexp)]` takes it as `#[try_from_sexp(validate = path)]`
29//! (#1815).
30//!
31//! # Where a `Vec`'s check runs: the inner container decides
32//!
33//! An atomic vector keeps one class for all its elements, on the vector; a
34//! list of R objects keeps a class on each element. So the `Vec` blankets
35//! don't run the check themselves: they pass `T::check_sexp` to the inner
36//! container's hidden
37//! [`TryFromSexp::__mx_try_from_sexp_with_check`]
38//! (#1837). Its default runs the check once on the whole input, which every
39//! atomic inner container keeps. `Vec<List>` and `Vec<Option<List>>` override
40//! it to run the check on each element (but `NULL`) and to report every
41//! failing element in one error, with its position. The blankets override it
42//! too, adding their own check after the one they are given, so a newtype of a
43//! newtype over `List` checks each element, outer check first, as its scalar
44//! does.
45//!
46//! This keeps one blanket per container slot and one element trait: the
47//! choice follows the inner type, through an impl that only `miniextendr-api`
48//! can write (`Vec<List>`), not a second marker trait a downstream type could
49//! implement next to `TryFromSexpElement`. The `Option<T>` blanket runs the
50//! check itself: a scalar keeps its class on itself whatever its inner type.
51//!
52//! # Why the markers live here and not in the derive
53//!
54//! A downstream crate cannot write `impl TryFromSexp for Vec<MyNewtype>`: `Vec` /
55//! `Option` are not `#[fundamental]`, so the local newtype is "covered" and the
56//! orphan rule (E0117) forbids it. The container impls must live in
57//! `miniextendr-api`, keyed on a marker trait the derive *can* legally implement
58//! downstream (foreign trait + local `Self`). The blankets below are those
59//! container impls (#844).
60//!
61//! [`TryFromSexpElement`] / [`IntoRNewtype`] / [`IntoRVecElement`] are
62//! **plumbing**: they are emitted by the derives and by
63//! `try_from_sexp_via_str_parse!`, not implemented by hand. Implementing them
64//! manually is supported but unusual. A hand-written [`TryFromSexpElement`]
65//! also needs a `TryFromSexp` impl on the type for `Option<T>` to convert (the
66//! derive and the macro emit both), and that impl must keep the forwarding
67//! rule above: call [`TryFromSexpElement::check_sexp`], then convert the inner
68//! type and wrap it, and nothing else, since no container ever runs it.
69//!
70//! # One element trait per direction
71//!
72//! Each `TryFromSexp` container slot (`Vec<T>`, `Option<T>`, `Vec<Option<T>>`)
73//! holds exactly one blanket, keyed on [`TryFromSexpElement`]. A second blanket
74//! on another public trait (say, a parse trait) would collide with it (E0119):
75//! a downstream type could implement both, so coherence cannot prove them
76//! disjoint. So every non-built-in element goes through this one trait, and
77//! what differs is the inner type the containers read first: the newtype's
78//! field type, or `ParsedRStr<T>` for a string-parsed type, whose container
79//! impls in `from_r` hold the NA policy and the batched element errors.
80//!
81//! Every container's error is [`SexpError`]: the inner container's error
82//! converts into it, and so does a check's refusal
83//! ([`SexpError::Condition`], carrying
84//! its own classes). The inner containers that exist are all `miniextendr-api`
85//! impls (the orphan rule keeps the rest out), and each one's error is a
86//! `SexpError` or converts into one.
87//!
88//! The blankets bound the inner type through the hidden `VecInner` /
89//! `OptionInner` / `VecOptionInner` helpers rather than
90//! `Vec<T::Inner>: TryFromSexp`. For a type that is not an element,
91//! `T::Inner` cannot be normalized; with the projection as the bound's self
92//! type, the solver gives up on it at once and reports
93//! `T: TryFromSexpElement` as unsatisfied (E0277). Spelled
94//! `Vec<T::Inner>: TryFromSexp`, the same bound sent the solver through
95//! every `Vec<_>` impl (`Vec<Vec<_>>` nests one level per step) until it
96//! overflowed (E0275, #1682).
97//!
98//! # The asymmetries
99//!
100//! Five of the six container shapes are granted. Two are not, for two different
101//! coherence reasons:
102//!
103//! - **`IntoR for Vec<T>` (granted, but shared).** This slot has exactly one
104//!   blanket and `MatchArg` already needs it (`Vec<MyEnum>` → STRSXP). Rather
105//!   than a second, conflicting `Vec<T>` blanket (E0119), both paths funnel
106//!   through [`IntoRVecElement`]: `MatchArg` types reach it via a bridge blanket
107//!   in `match_arg.rs`, newtypes via a concrete impl emitted by
108//!   `#[derive(IntoR)]`. A type that is *both* a `MatchArg` enum and an `IntoR`
109//!   newtype is a coherence error — don't derive both on one type.
110//! - **`IntoR for Option<T>` (not granted).** A bare `Option<T>` blanket
111//!   collides with the pre-existing `impl<T: Copy + IntoR> IntoR for Option<&T>`:
112//!   `&T` is `#[fundamental]`, so a downstream crate could impl `IntoRNewtype`
113//!   for `&LocalType` and coherence cannot prove the two disjoint. Return
114//!   `Option<Inner>` (`opt.map(|x| x.0)`) instead. See the note on the missing
115//!   blanket below.
116//!
117//! `TryFromSexp for Vec<T>` / `Option<T>` / `Vec<Option<T>>` and `IntoR for
118//! Vec<Option<T>>` are coherence-free: no other blanket occupies those slots.
119//! The concrete `TryFromSexp for Vec<List>` / `Vec<Option<List>>` impls sit
120//! beside them because `List` is not a `TryFromSexpElement`, and no other
121//! crate can make it one (both are `miniextendr-api`'s).
122
123use crate::SEXP;
124use crate::from_r::{ElementCheck, NativeBorrow, SexpError, TryFromSexp, no_element_check};
125use crate::into_r::IntoR;
126
127// region: marker traits (emitted by the derives, not hand-written)
128
129/// The element side of the `TryFromSexp` impls for `Vec<T>`, `Option<T>` and
130/// `Vec<Option<T>>` (R → Rust).
131///
132/// Each container of `Self` is read as the same container of
133/// [`Inner`](Self::Inner), then every element is wrapped with
134/// [`from_inner`](Self::from_inner): `Vec<Self>` reads `Vec<Self::Inner>`,
135/// `Option<Self>` reads `Option<Self::Inner>`, and `Vec<Option<Self>>` reads
136/// `Vec<Option<Self::Inner>>`. Each shape exists when the inner container
137/// converts, independently of the other two, and keeps its NA policy and
138/// metadata (`NATIVE_BORROW`, `CHARACTER_ONLY`); its error converts into
139/// [`SexpError`].
140///
141/// # Forwarding
142///
143/// No container calls `<Self as TryFromSexp>::try_from_sexp`. They read the
144/// inner type and wrap it, so the element's own `try_from_sexp`, when it has
145/// one, must do the same: [`check_sexp`](Self::check_sexp), then the inner
146/// type's conversion, then [`from_inner`](Self::from_inner). Anything else
147/// it did would hold for a scalar argument and silently not for
148/// `Option<Self>`, `Vec<Self>` or `Vec<Option<Self>>`. A value the inner type
149/// accepts but `Self` refuses is refused in `check_sexp`, which every shape
150/// runs.
151///
152/// Emitted by `#[derive(TryFromSexp)]` (the inner type is the newtype's field;
153/// `#[try_from_sexp(validate = path)]` gives the check) and by
154/// [`try_from_sexp_via_str_parse!`](crate::try_from_sexp_via_str_parse)
155/// (the inner type is [`ParsedRStr<Self>`](crate::from_r::ParsedRStr)). See
156/// the module docs for why both share this one trait.
157#[diagnostic::on_unimplemented(
158    message = "this `Vec` or `Option` of `{Self}` has no conversion from R",
159    label = "`{Self}` does not implement `TryFromSexpElement`",
160    note = "`Vec<T>`, `Option<T>` and `Vec<Option<T>>` convert from R for the built-in types, `#[derive(TryFromSexp)]` newtypes over a type whose container converts, and types given `try_from_sexp_via_str_parse!`"
161)]
162pub trait TryFromSexpElement: Sized {
163    /// The type whose containers are read first.
164    type Inner;
165
166    /// Wrap an inner value into `Self`.
167    fn from_inner(inner: Self::Inner) -> Self;
168
169    /// Refuse an R value before it is read: `Err` for a value the inner type
170    /// would accept but `Self` must not, such as a number that carries a unit
171    /// class (`difftime`, `Date`, `POSIXct`).
172    ///
173    /// Called with the input of every shape, before its inner conversion: by
174    /// the scalar `TryFromSexp` (the derive's calls it), for `Option<Self>`
175    /// on any input but `NULL` and a plain `NA`, which stay "not given"
176    /// (#2305), and for `Vec<Self>` and `Vec<Option<Self>>` where R keeps
177    /// the element's class: once on the whole vector for an atomic inner
178    /// type, on each element (but `NULL`) for a list of R objects
179    /// (`Self::Inner` is `List`, or a newtype over it). It sees the value as
180    /// R holds it, attributes and all, before anything is read from it.
181    ///
182    /// Return an [`RError`](crate::condition::RError), or any
183    /// [`RConditionData`](crate::condition::RConditionData) type, with `?`
184    /// or `.into()` to give the refusal its own classes and fields
185    /// ([`SexpError::Condition`]). As an
186    /// argument error it keeps the wrapper's context: `'<p>' must be
187    /// <expected>: <message>`, the classes before the crate's
188    /// `conversion_error_class`, `e$param` and `e$rust_type`. A plain
189    /// `SexpError` (`SexpError::InvalidValue`) works too, with no classes.
190    ///
191    /// The default accepts every value; it is what the derive emits without
192    /// `validate` and what a string-parsed type has.
193    #[inline]
194    fn check_sexp(_sexp: SEXP) -> Result<(), SexpError> {
195        Ok(())
196    }
197}
198
199/// Unwrap a forwarding newtype into its inner value (Rust → R side).
200///
201/// Emitted by `#[derive(IntoR)]`. Powers the `IntoR` container blankets for
202/// `Option<T>` / `Vec<Option<T>>` in this module.
203pub trait IntoRNewtype {
204    /// The wrapped inner type, whose conversions are forwarded to.
205    type Inner;
206
207    /// Unwrap the newtype into its inner value.
208    fn into_inner(self) -> Self::Inner;
209}
210
211/// How a `Vec<Self>` becomes a single R vector SEXP.
212///
213/// This is the shared element-marker behind the **one** `impl<T: …> IntoR for
214/// Vec<T>` blanket slot. Implemented concretely per type — by `#[derive(IntoR)]`
215/// for newtypes (forwarding to `Vec<Inner>`), and by the `MatchArg` bridge in
216/// `match_arg.rs` for `match.arg` enums (STRSXP by variant name). See the module
217/// docs for why this cannot be two competing blankets.
218pub trait IntoRVecElement: Sized {
219    /// Convert all elements into one R vector SEXP.
220    fn elements_into_sexp(values: Vec<Self>) -> SEXP;
221}
222
223// endregion
224
225// region: container helpers (bound on the inner type itself, #1682)
226
227/// `Vec<Self>: TryFromSexp` with an error that converts into [`SexpError`],
228/// with `Self` as the bound's self type.
229///
230/// Plumbing for the `Vec<T>` blanket below: see the module docs (#1682).
231#[doc(hidden)]
232pub trait VecInner: Sized {
233    /// `<Vec<Self> as TryFromSexp>::NATIVE_BORROW`.
234    const VEC_NATIVE_BORROW: Option<NativeBorrow>;
235    /// `<Vec<Self> as TryFromSexp>::CHARACTER_ONLY`.
236    const VEC_CHARACTER_ONLY: bool;
237    /// `<Vec<Self> as TryFromSexp>::__mx_try_from_sexp_with_check`: the
238    /// vector, with `check` run where `Vec<Self>` keeps an element's class.
239    fn vec_try_from_sexp(sexp: SEXP, check: &ElementCheck<'_>) -> Result<Vec<Self>, SexpError>;
240    /// `<Vec<Self> as TryFromSexp>::__mx_try_from_sexp_unchecked_with_check`.
241    ///
242    /// # Safety
243    ///
244    /// As [`TryFromSexp::try_from_sexp_unchecked`].
245    unsafe fn vec_try_from_sexp_unchecked(
246        sexp: SEXP,
247        check: &ElementCheck<'_>,
248    ) -> Result<Vec<Self>, SexpError>;
249}
250
251impl<I> VecInner for I
252where
253    Vec<I>: TryFromSexp,
254    <Vec<I> as TryFromSexp>::Error: Into<SexpError>,
255{
256    const VEC_NATIVE_BORROW: Option<NativeBorrow> = <Vec<I> as TryFromSexp>::NATIVE_BORROW;
257    const VEC_CHARACTER_ONLY: bool = <Vec<I> as TryFromSexp>::CHARACTER_ONLY;
258
259    #[inline]
260    fn vec_try_from_sexp(sexp: SEXP, check: &ElementCheck<'_>) -> Result<Vec<Self>, SexpError> {
261        <Vec<I> as TryFromSexp>::__mx_try_from_sexp_with_check(sexp, check)
262    }
263
264    #[inline]
265    unsafe fn vec_try_from_sexp_unchecked(
266        sexp: SEXP,
267        check: &ElementCheck<'_>,
268    ) -> Result<Vec<Self>, SexpError> {
269        unsafe { <Vec<I> as TryFromSexp>::__mx_try_from_sexp_unchecked_with_check(sexp, check) }
270    }
271}
272
273/// `Option<Self>: TryFromSexp` with an error that converts into
274/// [`SexpError`], with `Self` as the bound's self type.
275///
276/// Plumbing for the `Option<T>` blanket below: see the module docs (#1682).
277#[doc(hidden)]
278pub trait OptionInner: Sized {
279    /// `<Option<Self> as TryFromSexp>::NATIVE_BORROW`.
280    const OPTION_NATIVE_BORROW: Option<NativeBorrow>;
281    /// `<Option<Self> as TryFromSexp>::CHARACTER_ONLY`.
282    const OPTION_CHARACTER_ONLY: bool;
283    /// `<Option<Self> as TryFromSexp>::try_from_sexp`, its error as a
284    /// [`SexpError`].
285    fn option_try_from_sexp(sexp: SEXP) -> Result<Option<Self>, SexpError>;
286    /// `<Option<Self> as TryFromSexp>::try_from_sexp_unchecked`, its error as
287    /// a [`SexpError`].
288    ///
289    /// # Safety
290    ///
291    /// As [`TryFromSexp::try_from_sexp_unchecked`].
292    unsafe fn option_try_from_sexp_unchecked(sexp: SEXP) -> Result<Option<Self>, SexpError>;
293}
294
295impl<I> OptionInner for I
296where
297    Option<I>: TryFromSexp,
298    <Option<I> as TryFromSexp>::Error: Into<SexpError>,
299{
300    const OPTION_NATIVE_BORROW: Option<NativeBorrow> = <Option<I> as TryFromSexp>::NATIVE_BORROW;
301    const OPTION_CHARACTER_ONLY: bool = <Option<I> as TryFromSexp>::CHARACTER_ONLY;
302
303    #[inline]
304    fn option_try_from_sexp(sexp: SEXP) -> Result<Option<Self>, SexpError> {
305        <Option<I> as TryFromSexp>::try_from_sexp(sexp).map_err(Into::into)
306    }
307
308    #[inline]
309    unsafe fn option_try_from_sexp_unchecked(sexp: SEXP) -> Result<Option<Self>, SexpError> {
310        unsafe { <Option<I> as TryFromSexp>::try_from_sexp_unchecked(sexp) }.map_err(Into::into)
311    }
312}
313
314/// `Vec<Option<Self>>: TryFromSexp` with an error that converts into
315/// [`SexpError`], with `Self` as the bound's self type.
316///
317/// Plumbing for the `Vec<Option<T>>` blanket below: see the module docs
318/// (#1682).
319#[doc(hidden)]
320pub trait VecOptionInner: Sized {
321    /// `<Vec<Option<Self>> as TryFromSexp>::NATIVE_BORROW`.
322    const VEC_OPTION_NATIVE_BORROW: Option<NativeBorrow>;
323    /// `<Vec<Option<Self>> as TryFromSexp>::CHARACTER_ONLY`.
324    const VEC_OPTION_CHARACTER_ONLY: bool;
325    /// `<Vec<Option<Self>> as TryFromSexp>::__mx_try_from_sexp_with_check`:
326    /// the vector, with `check` run where `Vec<Option<Self>>` keeps an
327    /// element's class.
328    fn vec_option_try_from_sexp(
329        sexp: SEXP,
330        check: &ElementCheck<'_>,
331    ) -> Result<Vec<Option<Self>>, SexpError>;
332    /// `<Vec<Option<Self>> as TryFromSexp>::__mx_try_from_sexp_unchecked_with_check`.
333    ///
334    /// # Safety
335    ///
336    /// As [`TryFromSexp::try_from_sexp_unchecked`].
337    unsafe fn vec_option_try_from_sexp_unchecked(
338        sexp: SEXP,
339        check: &ElementCheck<'_>,
340    ) -> Result<Vec<Option<Self>>, SexpError>;
341}
342
343impl<I> VecOptionInner for I
344where
345    Vec<Option<I>>: TryFromSexp,
346    <Vec<Option<I>> as TryFromSexp>::Error: Into<SexpError>,
347{
348    const VEC_OPTION_NATIVE_BORROW: Option<NativeBorrow> =
349        <Vec<Option<I>> as TryFromSexp>::NATIVE_BORROW;
350    const VEC_OPTION_CHARACTER_ONLY: bool = <Vec<Option<I>> as TryFromSexp>::CHARACTER_ONLY;
351
352    #[inline]
353    fn vec_option_try_from_sexp(
354        sexp: SEXP,
355        check: &ElementCheck<'_>,
356    ) -> Result<Vec<Option<Self>>, SexpError> {
357        <Vec<Option<I>> as TryFromSexp>::__mx_try_from_sexp_with_check(sexp, check)
358    }
359
360    #[inline]
361    unsafe fn vec_option_try_from_sexp_unchecked(
362        sexp: SEXP,
363        check: &ElementCheck<'_>,
364    ) -> Result<Vec<Option<Self>>, SexpError> {
365        unsafe {
366            <Vec<Option<I>> as TryFromSexp>::__mx_try_from_sexp_unchecked_with_check(sexp, check)
367        }
368    }
369}
370
371// endregion
372
373// region: IntoR for Vec<T> — the unified element-marker blanket
374
375/// The single `IntoR for Vec<T>` blanket, shared by `MatchArg` enums and
376/// `#[derive(IntoR)]` newtypes via [`IntoRVecElement`]. Coexists with the
377/// concrete `impl IntoR for Vec<i32>` (etc.) impls: `IntoRVecElement` is
378/// crate-local, so coherence proves the foreign R-native types do not implement
379/// it.
380impl<T: IntoRVecElement> IntoR for Vec<T> {
381    type Error = std::convert::Infallible;
382
383    #[inline]
384    fn try_into_sexp(self) -> Result<SEXP, Self::Error> {
385        Ok(self.into_sexp())
386    }
387
388    #[inline]
389    unsafe fn try_into_sexp_unchecked(self) -> Result<SEXP, Self::Error> {
390        self.try_into_sexp()
391    }
392
393    #[inline]
394    fn into_sexp(self) -> SEXP {
395        T::elements_into_sexp(self)
396    }
397}
398
399// endregion
400
401// region: TryFromSexp container blankets (R → Rust)
402
403// The `Vec` blankets hand `T::check_sexp`, after the check of any enclosing
404// newtype, to the inner container's `__mx_try_from_sexp_with_check`, which
405// runs it where that container keeps an element's class: once on the whole
406// input for an atomic vector, on each element for a list of R objects
407// (#1837). They then wrap what was read with `T::from_inner`. `Option<T>`
408// runs the check itself, on a non-`NULL` input. None calls
409// `T::try_from_sexp`: see "Forwarding" on `TryFromSexpElement`.
410
411impl<T: TryFromSexpElement> TryFromSexp for Vec<T>
412where
413    T::Inner: VecInner,
414{
415    type Error = SexpError;
416    const NATIVE_BORROW: Option<NativeBorrow> = <T::Inner as VecInner>::VEC_NATIVE_BORROW;
417    const CHARACTER_ONLY: bool = <T::Inner as VecInner>::VEC_CHARACTER_ONLY;
418
419    #[inline]
420    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
421        Self::__mx_try_from_sexp_with_check(sexp, &no_element_check)
422    }
423
424    #[inline]
425    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
426        unsafe { Self::__mx_try_from_sexp_unchecked_with_check(sexp, &no_element_check) }
427    }
428
429    #[inline]
430    fn __mx_try_from_sexp_with_check(
431        sexp: SEXP,
432        check: &ElementCheck<'_>,
433    ) -> Result<Self, SexpError> {
434        let check = |x: SEXP| {
435            check(x)?;
436            T::check_sexp(x)
437        };
438        Ok(<T::Inner as VecInner>::vec_try_from_sexp(sexp, &check)?
439            .into_iter()
440            .map(T::from_inner)
441            .collect())
442    }
443
444    #[inline]
445    unsafe fn __mx_try_from_sexp_unchecked_with_check(
446        sexp: SEXP,
447        check: &ElementCheck<'_>,
448    ) -> Result<Self, SexpError> {
449        let check = |x: SEXP| {
450            check(x)?;
451            T::check_sexp(x)
452        };
453        Ok(
454            unsafe { <T::Inner as VecInner>::vec_try_from_sexp_unchecked(sexp, &check) }?
455                .into_iter()
456                .map(T::from_inner)
457                .collect(),
458        )
459    }
460}
461
462// `T: TryFromSexp` lets `__mx_has_na` ask the element itself
463// (`TryFromSexpElement` has no inner accessor, and an override cannot add a
464// bound, E0276). The derive and the str-parse macro always emit both impls.
465impl<T: TryFromSexpElement + TryFromSexp> TryFromSexp for Option<T>
466where
467    T::Inner: OptionInner,
468{
469    type Error = SexpError;
470    const NATIVE_BORROW: Option<NativeBorrow> = <T::Inner as OptionInner>::OPTION_NATIVE_BORROW;
471    const CHARACTER_ONLY: bool = <T::Inner as OptionInner>::OPTION_CHARACTER_ONLY;
472    // `NULL` (`None`) is "not given" and passes `no_na`.
473    #[inline]
474    fn __mx_has_na(&self) -> bool {
475        self.as_ref().is_some_and(T::__mx_has_na)
476    }
477
478    // `NULL` and a plain `NA` (#2305) are "not given" too, so the check sees
479    // only a value. The inner `Option` decides what a plain `NA` reads as:
480    // `None` for a scalar, a refusal for a vector.
481    #[inline]
482    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
483        if !crate::from_r::is_null_or_plain_na(sexp) {
484            T::check_sexp(sexp)?;
485        }
486        Ok(<T::Inner as OptionInner>::option_try_from_sexp(sexp)?.map(T::from_inner))
487    }
488
489    #[inline]
490    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
491        if !unsafe { crate::from_r::is_null_or_plain_na_unchecked(sexp) } {
492            T::check_sexp(sexp)?;
493        }
494        Ok(
495            unsafe { <T::Inner as OptionInner>::option_try_from_sexp_unchecked(sexp) }?
496                .map(T::from_inner),
497        )
498    }
499}
500
501impl<T: TryFromSexpElement> TryFromSexp for Vec<Option<T>>
502where
503    T::Inner: VecOptionInner,
504{
505    type Error = SexpError;
506    const NATIVE_BORROW: Option<NativeBorrow> =
507        <T::Inner as VecOptionInner>::VEC_OPTION_NATIVE_BORROW;
508    const CHARACTER_ONLY: bool = <T::Inner as VecOptionInner>::VEC_OPTION_CHARACTER_ONLY;
509
510    #[inline]
511    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
512        Self::__mx_try_from_sexp_with_check(sexp, &no_element_check)
513    }
514
515    #[inline]
516    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
517        unsafe { Self::__mx_try_from_sexp_unchecked_with_check(sexp, &no_element_check) }
518    }
519
520    #[inline]
521    fn __mx_try_from_sexp_with_check(
522        sexp: SEXP,
523        check: &ElementCheck<'_>,
524    ) -> Result<Self, SexpError> {
525        let check = |x: SEXP| {
526            check(x)?;
527            T::check_sexp(x)
528        };
529        Ok(
530            <T::Inner as VecOptionInner>::vec_option_try_from_sexp(sexp, &check)?
531                .into_iter()
532                .map(|opt| opt.map(T::from_inner))
533                .collect(),
534        )
535    }
536
537    #[inline]
538    unsafe fn __mx_try_from_sexp_unchecked_with_check(
539        sexp: SEXP,
540        check: &ElementCheck<'_>,
541    ) -> Result<Self, SexpError> {
542        let check = |x: SEXP| {
543            check(x)?;
544            T::check_sexp(x)
545        };
546        Ok(unsafe {
547            <T::Inner as VecOptionInner>::vec_option_try_from_sexp_unchecked(sexp, &check)
548        }?
549        .into_iter()
550        .map(|opt| opt.map(T::from_inner))
551        .collect())
552    }
553}
554
555// endregion
556
557// region: IntoR container blankets (Rust → R) for Vec<Option>
558
559// NOTE: there is deliberately no `impl<T: IntoRNewtype> IntoR for Option<T>`.
560// That bare `Option<T>` blanket collides (E0119) with the pre-existing
561// `impl<T: Copy + IntoR> IntoR for Option<&T>` (into_r/large_integers.rs): `&T`
562// is `#[fundamental]`, so a downstream crate *could* implement `IntoRNewtype`
563// for `&LocalType`, and coherence cannot prove the two disjoint. Returning a
564// `Option<MyNewtype>` to R is the one shape the derive does not grant — map to
565// the inner first (`opt.map(|x| x.0)` → `Option<Inner>`), which mirrors the
566// NULL-vs-NA guidance already on the `Option<&T>` impl. See issue #844.
567
568impl<T: IntoRNewtype> IntoR for Vec<Option<T>>
569where
570    Vec<Option<T::Inner>>: IntoR,
571{
572    type Error = <Vec<Option<T::Inner>> as IntoR>::Error;
573
574    #[inline]
575    fn try_into_sexp(self) -> Result<SEXP, Self::Error> {
576        self.into_iter()
577            .map(|opt| opt.map(T::into_inner))
578            .collect::<Vec<Option<T::Inner>>>()
579            .try_into_sexp()
580    }
581
582    #[inline]
583    unsafe fn try_into_sexp_unchecked(self) -> Result<SEXP, Self::Error> {
584        unsafe {
585            self.into_iter()
586                .map(|opt| opt.map(T::into_inner))
587                .collect::<Vec<Option<T::Inner>>>()
588                .try_into_sexp_unchecked()
589        }
590    }
591
592    #[inline]
593    fn into_sexp(self) -> SEXP {
594        self.into_iter()
595            .map(|opt| opt.map(T::into_inner))
596            .collect::<Vec<Option<T::Inner>>>()
597            .into_sexp()
598    }
599
600    #[inline]
601    unsafe fn into_sexp_unchecked(self) -> SEXP {
602        unsafe {
603            self.into_iter()
604                .map(|opt| opt.map(T::into_inner))
605                .collect::<Vec<Option<T::Inner>>>()
606                .into_sexp_unchecked()
607        }
608    }
609}
610
611// endregion