Skip to main content

miniextendr_api/from_r/
rooted.rs

1//! Conversions whose borrowed result cannot outlive an R root.
2
3use super::{
4    NativeBorrow, SexpError, SexpTypeError, TryFromSexp, map_strsxp_with, map_vecsxp_batched,
5    try_charsxp_to_cow, try_charsxp_to_str,
6};
7use crate::{RCow, RNativeType, Root, SEXP, SEXPTYPE, SexpExt, StrVec};
8use std::borrow::Cow;
9
10/// Convert an R value while retaining its root's lifetime in the result.
11///
12/// This conversion carries the root lifetime that raw [`TryFromSexp`]
13/// cannot express.
14/// Generated wrappers use the rooted `.Call` argument for `StrVec`, `RCow`,
15/// and `Cow` inputs (including the character-vector Cow containers). Wrappers
16/// and trait shims also use it for explicit shared native references and
17/// optional shared references.
18/// Nested shared-reference `Vec` inputs retain every list element in the root's
19/// protection scope, even when an ALTREP accessor does not cache that element.
20/// Reference aliases and custom reference converters select this path with
21/// `#[miniextendr(convert)]` on the parameter, or `#[miniextendr(convert(param))]`
22/// on an inherent or trait impl method. Other aliases can use this trait
23/// explicitly in the function body.
24///
25/// A root proves liveness, not exclusive access: this trait does not provide
26/// mutable references to R storage. Shared native borrows still participate
27/// in a wrapper's alias checks against its other, mutable arguments.
28///
29/// ```compile_fail
30/// use miniextendr_api::{Root, TryFromRoot};
31/// use std::borrow::Cow;
32/// fn escape<'a>(root: Root<'a>) -> Cow<'static, [i32]> {
33///     Cow::try_from_root(root).unwrap()
34/// }
35/// ```
36/// ```compile_fail
37/// use miniextendr_api::{Root, TryFromRoot};
38/// use std::borrow::Cow;
39/// fn escape<'a>(root: Root<'a>) -> Vec<Option<Cow<'static, str>>> {
40///     Vec::try_from_root(root).unwrap()
41/// }
42/// ```
43/// ```compile_fail
44/// use miniextendr_api::{Root, TryFromRoot};
45/// fn escape<'a>(root: Root<'a>) -> &'static [i32] {
46///     <&[i32]>::try_from_root(root).unwrap()
47/// }
48/// ```
49/// ```compile_fail
50/// use miniextendr_api::{Root, TryFromRoot};
51/// fn escape<'a>(root: Root<'a>) -> Option<&'static str> {
52///     <Option<&str>>::try_from_root(root).unwrap()
53/// }
54/// ```
55/// ```compile_fail
56/// use miniextendr_api::{Root, TryFromRoot};
57/// fn escape<'a>(root: Root<'a>) -> Vec<Vec<&'static [i32]>> {
58///     Vec::try_from_root(root).unwrap()
59/// }
60/// ```
61pub trait TryFromRoot<'a>: Sized {
62    /// The error reported when the R representation is not accepted.
63    type Error;
64
65    /// Native storage borrowed by this conversion, for wrapper alias checks.
66    #[doc(hidden)]
67    const NATIVE_BORROW: Option<NativeBorrow> = None;
68
69    /// Convert without allowing an R-backed borrow to outlive `root`.
70    fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error>;
71}
72
73/// A shared reference converts as its raw `'static` form does, with the same
74/// checks, errors and alias metadata, and so does a custom `TryFromSexp` impl
75/// for a reference to the user's own type. Only the lifetime changes: the
76/// result borrows from the root, not from `'static`.
77impl<'a, T: ?Sized + 'static> TryFromRoot<'a> for &'a T
78where
79    &'static T: TryFromSexp,
80{
81    type Error = <&'static T as TryFromSexp>::Error;
82    const NATIVE_BORROW: Option<NativeBorrow> = <&'static T as TryFromSexp>::NATIVE_BORROW;
83
84    fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
85        // Narrow the raw reference to 'a. String converters also retain the
86        // CHARSXP, which an ALTREP parent need not keep after Elt returns.
87        unsafe { <&'static T as TryFromSexp>::__mx_try_from_rooted(root) }
88    }
89}
90
91/// `NULL` (and, for strings, `NA_character_` or a plain `NA`, #2305) is
92/// `None`, as in the raw conversion. A native element borrow
93/// (`Option<&i32>`, ...) reads only `NULL` as `None`: it points at the
94/// element, `NA` included.
95impl<'a, T: ?Sized + 'static> TryFromRoot<'a> for Option<&'a T>
96where
97    Option<&'static T>: TryFromSexp,
98{
99    type Error = <Option<&'static T> as TryFromSexp>::Error;
100    const NATIVE_BORROW: Option<NativeBorrow> = <Option<&'static T> as TryFromSexp>::NATIVE_BORROW;
101
102    fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
103        // The result is narrowed to the lifetime of this root.
104        unsafe { <Option<&'static T> as TryFromSexp>::__mx_try_from_rooted(root) }
105    }
106}
107
108impl<'a> TryFromRoot<'a> for StrVec<'a> {
109    type Error = SexpError;
110
111    fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
112        StrVec::try_from_root(root)
113    }
114}
115
116impl<'a, T: RNativeType> TryFromRoot<'a> for RCow<'a, T> {
117    type Error = SexpTypeError;
118    const NATIVE_BORROW: Option<NativeBorrow> = RCow::<'a, T>::NATIVE_BORROW;
119
120    fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
121        RCow::try_from_root(root)
122    }
123}
124
125impl<'a, T: RNativeType> TryFromRoot<'a> for Cow<'a, [T]> {
126    type Error = SexpTypeError;
127    const NATIVE_BORROW: Option<NativeBorrow> = <&[T] as TryFromRoot<'a>>::NATIVE_BORROW;
128
129    fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
130        <&[T]>::try_from_root(root).map(Cow::Borrowed)
131    }
132}
133
134impl<'a> TryFromRoot<'a> for Cow<'a, str> {
135    type Error = SexpError;
136
137    fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
138        <&str>::try_from_root(root).map(Cow::Borrowed)
139    }
140}
141
142/// An element type of a `Vec` that converts through [`TryFromRoot`]. The
143/// element decides what the vector reads: character elements read a `STRSXP`,
144/// the others read a list. One `Vec<E>` impl over this trait, rather than one
145/// impl per element shape, keeps a nested `Vec<Vec<..>>` from sending type
146/// inference into unbounded recursion when the element type is not yet known.
147#[doc(hidden)]
148pub trait RootedVecElement<'a>: Sized {
149    /// Native storage the vector borrows, for wrapper alias checks.
150    const NATIVE_BORROW: Option<NativeBorrow>;
151
152    /// Convert every element, retaining each one an ALTREP accessor returns.
153    fn vec_from_root(root: Root<'a>) -> Result<Vec<Self>, SexpError>;
154}
155
156impl<'a, E: RootedVecElement<'a>> TryFromRoot<'a> for Vec<E> {
157    type Error = SexpError;
158    const NATIVE_BORROW: Option<NativeBorrow> = E::NATIVE_BORROW;
159
160    fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
161        E::vec_from_root(root)
162    }
163}
164
165/// `NULL` is `None`; anything else converts as the `Vec`.
166impl<'a, E: RootedVecElement<'a>> TryFromRoot<'a> for Option<Vec<E>> {
167    type Error = SexpError;
168    const NATIVE_BORROW: Option<NativeBorrow> = E::NATIVE_BORROW;
169
170    fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
171        if root.get().type_of() == SEXPTYPE::NILSXP {
172            Ok(None)
173        } else {
174            E::vec_from_root(root).map(Some)
175        }
176    }
177}
178
179/// Character elements keep the raw conversions' NA handling: `NA` reads as
180/// `""` for the plain forms and as `None` for the optional ones. `$borrow`
181/// reads one non-`NA` element and may refuse it (a string marked as bytes);
182/// the walk reports every refused element in one error.
183macro_rules! character_elements {
184    ($life:lifetime; $($element:ty => |$value:ident| $borrow:expr, $na:expr, $blank:expr;)*) => {$(
185        impl<$life> RootedVecElement<$life> for $element {
186            const NATIVE_BORROW: Option<NativeBorrow> = None;
187
188            fn vec_from_root(root: Root<$life>) -> Result<Vec<Self>, SexpError> {
189                map_strsxp_with(root.get(), |value, _| {
190                    if value == SEXP::na_string() {
191                        Ok($na)
192                    } else if value == SEXP::blank_string() {
193                        Ok($blank)
194                    } else {
195                        // An ALTSTRING accessor need not retain this CHARSXP.
196                        let $value = unsafe { root.protect_child(value) }.get();
197                        $borrow
198                    }
199                })
200            }
201        }
202    )*};
203}
204
205impl<'a> RootedVecElement<'a> for &'a str {
    const NATIVE_BORROW: Option<NativeBorrow> = None;
    fn vec_from_root(root: Root<'a>) -> Result<Vec<Self>, SexpError> {
        map_strsxp_with(root.get(),
            |value, _|
                {
                    if value == SEXP::na_string() {
                        Ok("")
                    } else if value == SEXP::blank_string() {
                        Ok("")
                    } else {
                        let value = unsafe { root.protect_child(value) }.get();
                        unsafe { try_charsxp_to_str(value) }
                    }
                })
    }
}
impl<'a> RootedVecElement<'a> for Option<&'a str> {
    const NATIVE_BORROW: Option<NativeBorrow> = None;
    fn vec_from_root(root: Root<'a>) -> Result<Vec<Self>, SexpError> {
        map_strsxp_with(root.get(),
            |value, _|
                {
                    if value == SEXP::na_string() {
                        Ok(None)
                    } else if value == SEXP::blank_string() {
                        Ok(Some(""))
                    } else {
                        let value = unsafe { root.protect_child(value) }.get();
                        unsafe { try_charsxp_to_str(value) }.map(Some)
                    }
                })
    }
}
impl<'a> RootedVecElement<'a> for Cow<'a, str> {
    const NATIVE_BORROW: Option<NativeBorrow> = None;
    fn vec_from_root(root: Root<'a>) -> Result<Vec<Self>, SexpError> {
        map_strsxp_with(root.get(),
            |value, _|
                {
                    if value == SEXP::na_string() {
                        Ok(Cow::Borrowed(""))
                    } else if value == SEXP::blank_string() {
                        Ok(Cow::Borrowed(""))
                    } else {
                        let value = unsafe { root.protect_child(value) }.get();
                        unsafe { try_charsxp_to_cow(value) }
                    }
                })
    }
}
impl<'a> RootedVecElement<'a> for Option<Cow<'a, str>> {
    const NATIVE_BORROW: Option<NativeBorrow> = None;
    fn vec_from_root(root: Root<'a>) -> Result<Vec<Self>, SexpError> {
        map_strsxp_with(root.get(),
            |value, _|
                {
                    if value == SEXP::na_string() {
                        Ok(None)
                    } else if value == SEXP::blank_string() {
                        Ok(Some(Cow::Borrowed("")))
                    } else {
                        let value = unsafe { root.protect_child(value) }.get();
                        unsafe { try_charsxp_to_cow(value) }.map(Some)
                    }
                })
    }
}character_elements! {'a;
206    &'a str => |value| unsafe { try_charsxp_to_str(value) }, "", "";
207    Option<&'a str> => |value| unsafe { try_charsxp_to_str(value) }.map(Some), None, Some("");
208    Cow<'a, str> => |value| unsafe { try_charsxp_to_cow(value) }, Cow::Borrowed(""), Cow::Borrowed("");
209    Option<Cow<'a, str>> => |value| unsafe { try_charsxp_to_cow(value) }.map(Some), None, Some(Cow::Borrowed(""));
210}
211
212/// Each element gets its own root before conversion or the next Elt callback.
213/// Merely rooting an ALTREP list does not retain transient Elt results.
214fn rooted_list<'a, T: TryFromRoot<'a>>(root: Root<'a>) -> Result<Vec<T>, SexpError>
215where
216    T::Error: Into<SexpError>,
217{
218    map_vecsxp_batched(root.get(), |value| {
219        T::try_from_root(unsafe { root.protect_child(value) }).map_err(Into::into)
220    })
221}
222
223/// List elements: native references (for the native types that have a raw
224/// reference conversion), and vectors of any element, nested to any depth.
225macro_rules! list_elements {
226    ($life:lifetime, $param:ident: $bound:path; $($element:ty),* $(,)?) => {$(
227        impl<$life, $param: $bound> RootedVecElement<$life> for $element
228        where
229            $element: TryFromRoot<$life>,
230            <$element as TryFromRoot<$life>>::Error: Into<SexpError>,
231        {
232            const NATIVE_BORROW: Option<NativeBorrow> =
233                NativeBorrow::in_list(<$element as TryFromRoot<$life>>::NATIVE_BORROW);
234
235            fn vec_from_root(root: Root<$life>) -> Result<Vec<Self>, SexpError> {
236                rooted_list(root)
237            }
238        }
239    )*};
240}
241
242impl<'a, T: RNativeType> RootedVecElement<'a> for &'a T where
    &'a T: TryFromRoot<'a>, <&'a T as TryFromRoot<'a>>::Error: Into<SexpError>
    {
    const NATIVE_BORROW: Option<NativeBorrow> =
        NativeBorrow::in_list(<&'a T as TryFromRoot<'a>>::NATIVE_BORROW);
    fn vec_from_root(root: Root<'a>) -> Result<Vec<Self>, SexpError> {
        rooted_list(root)
    }
}
impl<'a, T: RNativeType> RootedVecElement<'a> for Option<&'a T> where
    Option<&'a T>: TryFromRoot<'a>,
    <Option<&'a T> as TryFromRoot<'a>>::Error: Into<SexpError> {
    const NATIVE_BORROW: Option<NativeBorrow> =
        NativeBorrow::in_list(<Option<&'a T> as
                TryFromRoot<'a>>::NATIVE_BORROW);
    fn vec_from_root(root: Root<'a>) -> Result<Vec<Self>, SexpError> {
        rooted_list(root)
    }
}
impl<'a, T: RNativeType> RootedVecElement<'a> for &'a [T] where
    &'a [T]: TryFromRoot<'a>,
    <&'a [T] as TryFromRoot<'a>>::Error: Into<SexpError> {
    const NATIVE_BORROW: Option<NativeBorrow> =
        NativeBorrow::in_list(<&'a [T] as TryFromRoot<'a>>::NATIVE_BORROW);
    fn vec_from_root(root: Root<'a>) -> Result<Vec<Self>, SexpError> {
        rooted_list(root)
    }
}
impl<'a, T: RNativeType> RootedVecElement<'a> for Option<&'a [T]> where
    Option<&'a [T]>: TryFromRoot<'a>,
    <Option<&'a [T]> as TryFromRoot<'a>>::Error: Into<SexpError> {
    const NATIVE_BORROW: Option<NativeBorrow> =
        NativeBorrow::in_list(<Option<&'a [T]> as
                TryFromRoot<'a>>::NATIVE_BORROW);
    fn vec_from_root(root: Root<'a>) -> Result<Vec<Self>, SexpError> {
        rooted_list(root)
    }
}list_elements!('a, T: RNativeType; &'a T, Option<&'a T>, &'a [T], Option<&'a [T]>);
243impl<'a, E: RootedVecElement<'a>> RootedVecElement<'a> for Vec<E> where
    Vec<E>: TryFromRoot<'a>,
    <Vec<E> as TryFromRoot<'a>>::Error: Into<SexpError> {
    const NATIVE_BORROW: Option<NativeBorrow> =
        NativeBorrow::in_list(<Vec<E> as TryFromRoot<'a>>::NATIVE_BORROW);
    fn vec_from_root(root: Root<'a>) -> Result<Vec<Self>, SexpError> {
        rooted_list(root)
    }
}
impl<'a, E: RootedVecElement<'a>> RootedVecElement<'a> for Option<Vec<E>>
    where Option<Vec<E>>: TryFromRoot<'a>,
    <Option<Vec<E>> as TryFromRoot<'a>>::Error: Into<SexpError> {
    const NATIVE_BORROW: Option<NativeBorrow> =
        NativeBorrow::in_list(<Option<Vec<E>> as
                TryFromRoot<'a>>::NATIVE_BORROW);
    fn vec_from_root(root: Root<'a>) -> Result<Vec<Self>, SexpError> {
        rooted_list(root)
    }
}list_elements!('a, E: RootedVecElement<'a>; Vec<E>, Option<Vec<E>>);