1//! Conversions whose borrowed result cannot outlive an R root.
23use super::{
4NativeBorrow, SexpError, SexpTypeError, TryFromSexp, map_strsxp_with, map_vecsxp_batched,
5try_charsxp_to_cow, try_charsxp_to_str,
6};
7use crate::{RCow, RNativeType, Root, SEXP, SEXPTYPE, SexpExt, StrVec};
8use std::borrow::Cow;
910/// 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.
63type Error;
6465/// Native storage borrowed by this conversion, for wrapper alias checks.
66#[doc(hidden)]
67const NATIVE_BORROW: Option<NativeBorrow> = None;
6869/// Convert without allowing an R-backed borrow to outlive `root`.
70fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error>;
71}
7273/// 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{
81type Error = <&'static T as TryFromSexp>::Error;
82const NATIVE_BORROW: Option<NativeBorrow> = <&'static T as TryFromSexp>::NATIVE_BORROW;
8384fn 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.
87unsafe { <&'static T as TryFromSexp>::__mx_try_from_rooted(root) }
88 }
89}
9091/// `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
97Option<&'static T>: TryFromSexp,
98{
99type Error = <Option<&'static T> as TryFromSexp>::Error;
100const NATIVE_BORROW: Option<NativeBorrow> = <Option<&'static T> as TryFromSexp>::NATIVE_BORROW;
101102fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
103// The result is narrowed to the lifetime of this root.
104unsafe { <Option<&'static T> as TryFromSexp>::__mx_try_from_rooted(root) }
105 }
106}
107108impl<'a> TryFromRoot<'a> for StrVec<'a> {
109type Error = SexpError;
110111fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
112StrVec::try_from_root(root)
113 }
114}
115116impl<'a, T: RNativeType> TryFromRoot<'a> for RCow<'a, T> {
117type Error = SexpTypeError;
118const NATIVE_BORROW: Option<NativeBorrow> = RCow::<'a, T>::NATIVE_BORROW;
119120fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
121RCow::try_from_root(root)
122 }
123}
124125impl<'a, T: RNativeType> TryFromRoot<'a> for Cow<'a, [T]> {
126type Error = SexpTypeError;
127const NATIVE_BORROW: Option<NativeBorrow> = <&[T] as TryFromRoot<'a>>::NATIVE_BORROW;
128129fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
130 <&[T]>::try_from_root(root).map(Cow::Borrowed)
131 }
132}
133134impl<'a> TryFromRoot<'a> for Cow<'a, str> {
135type Error = SexpError;
136137fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
138 <&str>::try_from_root(root).map(Cow::Borrowed)
139 }
140}
141142/// 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.
150const NATIVE_BORROW: Option<NativeBorrow>;
151152/// Convert every element, retaining each one an ALTREP accessor returns.
153fn vec_from_root(root: Root<'a>) -> Result<Vec<Self>, SexpError>;
154}
155156impl<'a, E: RootedVecElement<'a>> TryFromRoot<'a> for Vec<E> {
157type Error = SexpError;
158const NATIVE_BORROW: Option<NativeBorrow> = E::NATIVE_BORROW;
159160fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
161 E::vec_from_root(root)
162 }
163}
164165/// `NULL` is `None`; anything else converts as the `Vec`.
166impl<'a, E: RootedVecElement<'a>> TryFromRoot<'a> for Option<Vec<E>> {
167type Error = SexpError;
168const NATIVE_BORROW: Option<NativeBorrow> = E::NATIVE_BORROW;
169170fn try_from_root(root: Root<'a>) -> Result<Self, Self::Error> {
171if root.get().type_of() == SEXPTYPE::NILSXP {
172Ok(None)
173 } else {
174 E::vec_from_root(root).map(Some)
175 }
176 }
177}
178179/// 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;)*) => {$(
185impl<$life> RootedVecElement<$life> for $element {
186const NATIVE_BORROW: Option<NativeBorrow> = None;
187188fn vec_from_root(root: Root<$life>) -> Result<Vec<Self>, SexpError> {
189 map_strsxp_with(root.get(), |value, _| {
190if value == SEXP::na_string() {
191Ok($na)
192 } else if value == SEXP::blank_string() {
193Ok($blank)
194 } else {
195// An ALTSTRING accessor need not retain this CHARSXP.
196let $value = unsafe { root.protect_child(value) }.get();
197$borrow
198}
199 })
200 }
201 }
202 )*};
203}
204205impl<'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) }, "", "";
207Option<&'a str> => |value| unsafe { try_charsxp_to_str(value) }.map(Some), None, Some("");
208Cow<'a, str> => |value| unsafe { try_charsxp_to_cow(value) }, Cow::Borrowed(""), Cow::Borrowed("");
209Option<Cow<'a, str>> => |value| unsafe { try_charsxp_to_cow(value) }.map(Some), None, Some(Cow::Borrowed(""));
210}211212/// 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
216T::Error: Into<SexpError>,
217{
218map_vecsxp_batched(root.get(), |value| {
219 T::try_from_root(unsafe { root.protect_child(value) }).map_err(Into::into)
220 })
221}
222223/// 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),* $(,)?) => {$(
227impl<$life, $param: $bound> RootedVecElement<$life> for $element
228where
229$element: TryFromRoot<$life>,
230 <$element as TryFromRoot<$life>>::Error: Into<SexpError>,
231 {
232const NATIVE_BORROW: Option<NativeBorrow> =
233 NativeBorrow::in_list(<$element as TryFromRoot<$life>>::NATIVE_BORROW);
234235fn vec_from_root(root: Root<$life>) -> Result<Vec<Self>, SexpError> {
236 rooted_list(root)
237 }
238 }
239 )*};
240}
241242impl<'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>>);