Skip to main content

miniextendr_api/from_r/
prepared.rs

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`]).
13
14use crate::SEXP;
15use crate::from_r::{NativeBorrow, TryFromSexp};
16
17/// 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}
24
25impl Arms {
26    /// No `Either` above the borrowing leaf.
27    pub const LEAF: Self = Self { bits: 0, depth: 0 };
28
29    /// 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.
31    pub const fn under(self, right: bool) -> Option<Self> {
32        if self.depth == u64::BITS {
33            return None;
34        }
35        Some(Self {
36            bits: (self.bits << 1) | if right { 1 } else { 0 },
37            depth: self.depth + 1,
38        })
39    }
40
41    /// Whether the outermost arm is the right one, and the path below it.
42    pub const fn pop(self) -> (bool, Self) {
43        (
44            self.bits & 1 == 1,
45            Self {
46                bits: self.bits >> 1,
47                depth: self.depth.saturating_sub(1),
48            },
49        )
50    }
51}
52
53/// 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.
64    Unprepared,
65    /// Converted during preparation and borrows nothing native: the value
66    /// is the argument.
67    Ready(T),
68    /// Failed during preparation. The error is reported where the argument
69    /// converts, so the order of argument errors does not change.
70    Failed(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.
73    Deferred {
74        /// What the selected arm borrows.
75        borrow: Option<NativeBorrow>,
76        /// The arms from the argument's type down to the borrowing leaf.
77        arms: 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).
82    Undecided(Option<NativeBorrow>),
83}
84
85impl<T: TryFromSexp> Prepared<T> {
86    /// A borrowing leaf whose checks passed: its conversion will succeed and
87    /// borrow what `T::NATIVE_BORROW` says.
88    pub fn deferred() -> Self {
89        Self::Deferred {
90            borrow: T::NATIVE_BORROW,
91            arms: Arms::LEAF,
92        }
93    }
94}
95
96impl<T, E> Prepared<T, E> {
97    /// An owned conversion's result.
98    pub fn from_result(result: Result<T, E>) -> Self {
99        match result {
100            Ok(value) => Self::Ready(value),
101            Err(error) => Self::Failed(error),
102        }
103    }
104
105    /// What the argument borrows for the second pass of the check, given its
106    /// declared metadata.
107    pub fn borrow(&self, declared: Option<NativeBorrow>) -> Option<NativeBorrow> {
108        match self {
109            Self::Unprepared => declared,
110            Self::Ready(_) | Self::Failed(_) => None,
111            Self::Deferred { borrow, .. } | Self::Undecided(borrow) => *borrow,
112        }
113    }
114
115    /// 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.
118    pub fn map<U: TryFromSexp>(
119        self,
120        value: impl FnOnce(T) -> U,
121        error: impl FnOnce(E) -> U::Error,
122    ) -> Prepared<U> {
123        match self {
124            Self::Unprepared => Prepared::Unprepared,
125            Self::Ready(v) => Prepared::Ready(value(v)),
126            Self::Failed(e) => Prepared::Failed(error(e)),
127            Self::Deferred { borrow, arms } => Prepared::Deferred { borrow, arms },
128            Self::Undecided(borrow) => Prepared::Undecided(borrow),
129        }
130    }
131
132    /// This preparation as one arm of an `Either` (`right` for the right
133    /// arm), whose own metadata is `either`.
134    pub fn arm<U: TryFromSexp>(
135        self,
136        right: bool,
137        value: impl FnOnce(T) -> U,
138        either: Option<NativeBorrow>,
139    ) -> Prepared<U> {
140        match self {
141            Self::Ready(v) => Prepared::Ready(value(v)),
142            Self::Deferred { borrow, arms } => match arms.under(right) {
143                Some(arms) => Prepared::Deferred { borrow, arms },
144                None => Prepared::Undecided(either),
145            },
146            Self::Undecided(borrow) => Prepared::Undecided(borrow),
147            Self::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}
153
154/// 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> {
160    match 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}
167
168/// 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> {
171    match check {
172        Ok(()) => Prepared::deferred(),
173        Err(error) => Prepared::Failed(error),
174    }
175}
176
177#[cfg(test)]
178mod tests;