1//! Preparing an argument whose native borrow depends on the arm its
2//! conversion takes (#1504).
3//!
4//! An `Either` borrows through whichever arm converts first, and only the
5//! conversion can tell which. A generated wrapper's alias check first takes
6//! both arms ([`NativeBorrow::either`]); when that union meets another
7//! argument, the wrapper prepares the argument
8//! ([`TryFromSexp::__mx_prepare`]): the conversion runs once, up to the point
9//! where it would build a native reference. An owned arm's value is kept, so
10//! it converts once. A borrowing arm records what it borrows and the arms
11//! that lead to it, and builds its reference only after the check passes
12//! ([`TryFromSexp::__mx_materialize`], through [`convert`]).
1314use crate::SEXP;
15use crate::from_r::{NativeBorrow, TryFromSexp};
1617/// The arms a prepared conversion took through nested `Either`s, outermost
18/// first: bit `k` is the arm at depth `k` (set for the right arm).
19#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Arms {
}
#[automatically_derived]impl ::core::clone::Clone for Arms {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<u64>;
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for Arms { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Arms {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Arms bits depth", &self.bits, &&self.depth)
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Arms { }
#[automatically_derived]impl ::core::cmp::PartialEq for Arms {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.bits == other.bits && self.depth == other.depth
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Arms {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u64>;
let _: ::core::cmp::AssertParamIsEq<u32>;
}
}Eq)]
20pub struct Arms {
21 bits: u64,
22 depth: u32,
23}
2425impl Arms {
26/// No `Either` above the borrowing leaf.
27pub const LEAF: Self = Self { bits: 0, depth: 0 };
2829/// This path under one more `Either` whose arm is the right one when
30 /// `right`. `None` past 64 levels, which the caller treats as undecided.
31pub const fn under(self, right: bool) -> Option<Self> {
32if self.depth == u64::BITS {
33return None;
34 }
35Some(Self {
36 bits: (self.bits << 1) | if right { 1 } else { 0 },
37 depth: self.depth + 1,
38 })
39 }
4041/// Whether the outermost arm is the right one, and the path below it.
42pub const fn pop(self) -> (bool, Self) {
43 (
44self.bits & 1 == 1,
45Self {
46 bits: self.bits >> 1,
47 depth: self.depth.saturating_sub(1),
48 },
49 )
50 }
51}
5253/// An argument's conversion as a generated wrapper's alias check leaves it:
54/// `T`'s, whose conversion error is `E`.
55///
56/// The type has no `TryFromSexp` bound, so a wrapper can declare and read
57/// the state of an argument whose type has no conversion without a second
58/// error: [`convert`] reports it, at the type.
59#[doc(hidden)]
60#[must_use]
61pub enum Prepared<T, E = <T as TryFromSexp>::Error> {
62/// Not prepared: it converts after the check, which takes its declared
63 /// metadata.
64Unprepared,
65/// Converted during preparation and borrows nothing native: the value
66 /// is the argument.
67Ready(T),
68/// Failed during preparation. The error is reported where the argument
69 /// converts, so the order of argument errors does not change.
70Failed(E),
71/// A borrowing arm will convert: `borrow` is all it borrows, `arms` the
72 /// way to it. Its reference is built after the check.
73Deferred {
74/// What the selected arm borrows.
75borrow: Option<NativeBorrow>,
76/// The arms from the argument's type down to the borrowing leaf.
77arms: Arms,
78 },
79/// The arm could not be learned without building a reference: it
80 /// converts after the check, which takes `borrow` (every arm it may
81 /// still take).
82Undecided(Option<NativeBorrow>),
83}
8485impl<T: TryFromSexp> Prepared<T> {
86/// A borrowing leaf whose checks passed: its conversion will succeed and
87 /// borrow what `T::NATIVE_BORROW` says.
88pub fn deferred() -> Self {
89Self::Deferred {
90 borrow: T::NATIVE_BORROW,
91 arms: Arms::LEAF,
92 }
93 }
94}
9596impl<T, E> Prepared<T, E> {
97/// An owned conversion's result.
98pub fn from_result(result: Result<T, E>) -> Self {
99match result {
100Ok(value) => Self::Ready(value),
101Err(error) => Self::Failed(error),
102 }
103 }
104105/// What the argument borrows for the second pass of the check, given its
106 /// declared metadata.
107pub fn borrow(&self, declared: Option<NativeBorrow>) -> Option<NativeBorrow> {
108match self {
109Self::Unprepared => declared,
110Self::Ready(_) | Self::Failed(_) => None,
111Self::Deferred { borrow, .. } | Self::Undecided(borrow) => *borrow,
112 }
113 }
114115/// The preparation of a type that wraps `T`: `value` and `error` build
116 /// its value and error, and its `__mx_materialize` must follow the same
117 /// arms through `T`'s.
118pub fn map<U: TryFromSexp>(
119self,
120 value: impl FnOnce(T) -> U,
121 error: impl FnOnce(E) -> U::Error,
122 ) -> Prepared<U> {
123match self {
124Self::Unprepared => Prepared::Unprepared,
125Self::Ready(v) => Prepared::Ready(value(v)),
126Self::Failed(e) => Prepared::Failed(error(e)),
127Self::Deferred { borrow, arms } => Prepared::Deferred { borrow, arms },
128Self::Undecided(borrow) => Prepared::Undecided(borrow),
129 }
130 }
131132/// This preparation as one arm of an `Either` (`right` for the right
133 /// arm), whose own metadata is `either`.
134pub fn arm<U: TryFromSexp>(
135self,
136 right: bool,
137 value: impl FnOnce(T) -> U,
138 either: Option<NativeBorrow>,
139 ) -> Prepared<U> {
140match self {
141Self::Ready(v) => Prepared::Ready(value(v)),
142Self::Deferred { borrow, arms } => match arms.under(right) {
143Some(arms) => Prepared::Deferred { borrow, arms },
144None => Prepared::Undecided(either),
145 },
146Self::Undecided(borrow) => Prepared::Undecided(borrow),
147Self::Unprepared | Self::Failed(_) => {
148{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("an arm\'s failure is handled before it is wrapped")));
}unreachable!("an arm's failure is handled before it is wrapped")149 }
150 }
151 }
152}
153154/// Convert an argument that a generated wrapper's alias check may have
155/// prepared. Call it only after the check: a deferred arm builds its
156/// reference here.
157#[doc(hidden)]
158#[inline]
159pub fn convert<T: TryFromSexp>(prepared: Prepared<T>, sexp: SEXP) -> Result<T, T::Error> {
160match prepared {
161 Prepared::Unprepared | Prepared::Undecided(_) => T::try_from_sexp(sexp),
162 Prepared::Ready(value) => Ok(value),
163 Prepared::Failed(error) => Err(error),
164 Prepared::Deferred { arms, .. } => T::__mx_materialize(sexp, arms),
165 }
166}
167168/// The preparation of a native reference conversion whose checks `check`
169/// runs: a passed check defers the reference, a failed one is the error.
170pub(crate) fn native_leaf<T: TryFromSexp>(check: Result<(), T::Error>) -> Prepared<T> {
171match check {
172Ok(()) => Prepared::deferred(),
173Err(error) => Prepared::Failed(error),
174 }
175}
176177#[cfg(test)]
178mod tests;