Skip to main content

cps_try/
lib.rs

1//! A stable implementation of Rust's `Try` and `FromResidual`.
2//!
3//! This crate provides the trait machinery necessary to desugar the `?` operator
4//! on stable Rust across [`Result`], [`Option`], [`ControlFlow`], [`Poll`], and layered
5//! types (e.g. `Poll<Result<T, E>>`, `Poll<Option<Result<T, E>>>`).
6//!
7//! ### The `?` Desugaring Pattern
8//! ```rust
9//! # fn func() -> Result<(), Box<dyn std::error::Error>> {
10//! # let expr = Result::<(), &'static str>::Err("failed");
11//! match cps_try::branch(expr) {
12//!     std::ops::ControlFlow::Continue(val) => val,
13//!     std::ops::ControlFlow::Break(residual) => return cps_try::from_residual(residual),
14//! };
15//! # Ok(())
16//! # }
17//! ```
18//! Because `return from_residual(residual)` is evaluated in return position,
19//! Rust's standard type inference resolves the target return type **automatically**
20//! without requiring any explicit type annotations.
21#![no_std]
22
23#[cfg(test)]
24extern crate std;
25
26use core::ops::ControlFlow;
27use core::task::Poll;
28
29// ---------------------------------------------------------------------------
30// Residual Types
31// ---------------------------------------------------------------------------
32
33/// The residual type representing a failed [`Result`].
34#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
35pub struct ResultResidual<E>(pub E);
36
37/// The residual type representing a [`None`] value for [`Option`].
38#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
39pub struct OptionResidual;
40
41/// The residual type representing an early break for [`ControlFlow`].
42#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
43pub struct ControlFlowResidual<B>(pub B);
44
45// ---------------------------------------------------------------------------
46// Core Traits
47// ---------------------------------------------------------------------------
48
49/// Splitting an expression into a success value or an early-exit residual.
50pub trait Try: Sized {
51    /// The type of the value produced when execution continues successfully.
52    type Output;
53
54    /// The residual type passed to [`FromResidual::from_residual`] on early exit.
55    type Residual;
56
57    /// Splits `self` into either a continuation output or an early-exit residual.
58    ///
59    /// Following RFC 3058, this returns [`ControlFlow`] which has identical ABI
60    /// and zero-cost machine representation to [`Result`] while cleanly modeling
61    /// early returns for non-error types like [`Option`] and [`Poll`].
62    fn branch(self) -> ControlFlow<Self::Residual, Self::Output>;
63}
64
65/// Constructing a return type from an early-exit residual.
66pub trait FromResidual<Residual = <Self as Try>::Residual> {
67    /// Constructs `Self` from the given residual.
68    fn from_residual(residual: Residual) -> Self;
69}
70
71// ---------------------------------------------------------------------------
72// Helper Functions
73// ---------------------------------------------------------------------------
74
75/// Branch a `Try` expression into [`ControlFlow`].
76#[inline(always)]
77pub fn branch<T: Try>(val: T) -> ControlFlow<T::Residual, T::Output> {
78    val.branch()
79}
80
81/// Convert an early-exit residual into the target return type.
82///
83/// Thanks to Rust's return-type inference, calling `return from_residual(residual)`
84/// automatically infers `Target` from the enclosing function's signature.
85#[inline(always)]
86pub fn from_residual<Target: FromResidual<R>, R>(residual: R) -> Target {
87    Target::from_residual(residual)
88}
89
90// ---------------------------------------------------------------------------
91// Implementations: Result
92// ---------------------------------------------------------------------------
93
94impl<T, E> Try for Result<T, E> {
95    type Output = T;
96    type Residual = ResultResidual<E>;
97
98    #[inline(always)]
99    fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
100        match self {
101            Ok(v) => ControlFlow::Continue(v),
102            Err(e) => ControlFlow::Break(ResultResidual(e)),
103        }
104    }
105}
106
107impl<T, E, F: From<E>> FromResidual<ResultResidual<E>> for Result<T, F> {
108    #[inline(always)]
109    fn from_residual(residual: ResultResidual<E>) -> Self {
110        Err(From::from(residual.0))
111    }
112}
113
114// ---------------------------------------------------------------------------
115// Implementations: Option
116// ---------------------------------------------------------------------------
117
118impl<T> Try for Option<T> {
119    type Output = T;
120    type Residual = OptionResidual;
121
122    #[inline(always)]
123    fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
124        match self {
125            Some(v) => ControlFlow::Continue(v),
126            None => ControlFlow::Break(OptionResidual),
127        }
128    }
129}
130
131impl<T> FromResidual<OptionResidual> for Option<T> {
132    #[inline(always)]
133    fn from_residual(_residual: OptionResidual) -> Self {
134        None
135    }
136}
137
138// ---------------------------------------------------------------------------
139// Implementations: ControlFlow
140// ---------------------------------------------------------------------------
141
142impl<B, C> Try for ControlFlow<B, C> {
143    type Output = C;
144    type Residual = ControlFlowResidual<B>;
145
146    #[inline(always)]
147    fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
148        match self {
149            ControlFlow::Continue(c) => ControlFlow::Continue(c),
150            ControlFlow::Break(b) => ControlFlow::Break(ControlFlowResidual(b)),
151        }
152    }
153}
154
155impl<B, C, B2: From<B>> FromResidual<ControlFlowResidual<B>> for ControlFlow<B2, C> {
156    #[inline(always)]
157    fn from_residual(residual: ControlFlowResidual<B>) -> Self {
158        ControlFlow::Break(From::from(residual.0))
159    }
160}
161
162// ---------------------------------------------------------------------------
163// Implementations: Poll and Layered Combinations
164// ---------------------------------------------------------------------------
165
166impl<T, E> Try for Poll<Result<T, E>> {
167    type Output = Poll<T>;
168    type Residual = ResultResidual<E>;
169
170    #[inline(always)]
171    fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
172        match self {
173            Poll::Ready(Ok(v)) => ControlFlow::Continue(Poll::Ready(v)),
174            Poll::Ready(Err(e)) => ControlFlow::Break(ResultResidual(e)),
175            Poll::Pending => ControlFlow::Continue(Poll::Pending),
176        }
177    }
178}
179
180impl<T, E, F: From<E>> FromResidual<ResultResidual<E>> for Poll<Result<T, F>> {
181    #[inline(always)]
182    fn from_residual(residual: ResultResidual<E>) -> Self {
183        Poll::Ready(Err(From::from(residual.0)))
184    }
185}
186
187impl<T> Try for Poll<Option<T>> {
188    type Output = Poll<T>;
189    type Residual = OptionResidual;
190
191    #[inline(always)]
192    fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
193        match self {
194            Poll::Ready(Some(v)) => ControlFlow::Continue(Poll::Ready(v)),
195            Poll::Ready(None) => ControlFlow::Break(OptionResidual),
196            Poll::Pending => ControlFlow::Continue(Poll::Pending),
197        }
198    }
199}
200
201impl<T> FromResidual<OptionResidual> for Poll<Option<T>> {
202    #[inline(always)]
203    fn from_residual(_residual: OptionResidual) -> Self {
204        Poll::Ready(None)
205    }
206}
207
208// Interop: using `result?` inside a function returning `Option<Result<T, F>>`
209impl<T, E, F: From<E>> FromResidual<ResultResidual<E>> for Option<Result<T, F>> {
210    #[inline(always)]
211    fn from_residual(residual: ResultResidual<E>) -> Self {
212        Some(Err(From::from(residual.0)))
213    }
214}
215
216// Interop: using `result?` inside a function returning `Poll<Option<Result<T, F>>>`
217impl<T, E, F: From<E>> FromResidual<ResultResidual<E>> for Poll<Option<Result<T, F>>> {
218    #[inline(always)]
219    fn from_residual(residual: ResultResidual<E>) -> Self {
220        Poll::Ready(Some(Err(From::from(residual.0))))
221    }
222}
223
224// ---------------------------------------------------------------------------
225// Convenience Desugaring Macro
226// ---------------------------------------------------------------------------
227
228/// Desugars the `?` operator on stable Rust.
229#[macro_export]
230macro_rules! try_op {
231    ($expr:expr) => {
232        match $crate::branch($expr) {
233            ::core::ops::ControlFlow::Continue(val) => val,
234            ::core::ops::ControlFlow::Break(residual) => {
235                return $crate::from_residual(residual);
236            }
237        }
238    };
239}
240
241// ---------------------------------------------------------------------------
242// Tests
243// ---------------------------------------------------------------------------
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248    use core::error::Error;
249    use std::boxed::Box;
250    use std::string::{String, ToString};
251
252    fn parse_int(s: &str) -> Result<i32, core::num::ParseIntError> {
253        s.parse::<i32>()
254    }
255
256    #[test]
257    fn test_result_type_inference_with_error_conversion() {
258        fn run() -> Result<i32, Box<dyn Error>> {
259            let x = try_op!(parse_int("42"));
260            Ok(x * 2)
261        }
262
263        assert_eq!(run().unwrap(), 84);
264
265        fn run_err() -> Result<i32, Box<dyn Error>> {
266            let _ = try_op!(parse_int("not a number"));
267            Ok(0)
268        }
269
270        assert!(run_err().is_err());
271    }
272
273    #[test]
274    fn test_option_desugaring() {
275        fn find_even(v: Option<i32>) -> Option<i32> {
276            let val = try_op!(v);
277            if val % 2 == 0 { Some(val) } else { None }
278        }
279
280        assert_eq!(find_even(Some(4)), Some(4));
281        assert_eq!(find_even(Some(3)), None);
282        assert_eq!(find_even(None), None);
283    }
284
285    #[test]
286    fn test_control_flow_desugaring() {
287        fn search(step: i32) -> ControlFlow<&'static str, i32> {
288            if step > 10 {
289                ControlFlow::Break("limit reached")
290            } else {
291                ControlFlow::Continue(step + 1)
292            }
293        }
294
295        fn run(start: i32) -> ControlFlow<&'static str, i32> {
296            let a = try_op!(search(start));
297            let b = try_op!(search(a));
298            ControlFlow::Continue(b)
299        }
300
301        assert_eq!(run(0), ControlFlow::Continue(2));
302        assert_eq!(run(10), ControlFlow::Break("limit reached"));
303    }
304
305    #[test]
306    fn test_poll_result_desugaring() {
307        fn poll_fn(ready: bool) -> Poll<Result<i32, &'static str>> {
308            if ready {
309                Poll::Ready(Ok(10))
310            } else {
311                Poll::Pending
312            }
313        }
314
315        fn run_poll(ready: bool) -> Poll<Result<i32, String>> {
316            // `try_op!` unwraps `Poll::Ready(Ok(10))` into `Poll::Ready(10)` or handles Pending
317            let poll_val = try_op!(poll_fn(ready));
318            match poll_val {
319                Poll::Ready(v) => Poll::Ready(Ok(v * 2)),
320                Poll::Pending => Poll::Pending,
321            }
322        }
323
324        assert_eq!(run_poll(true), Poll::Ready(Ok(20)));
325        assert_eq!(run_poll(false), Poll::Pending);
326    }
327
328    #[test]
329    fn test_result_inside_poll_result_interop() {
330        // Here we test using `?` on a plain `Result` inside a function returning `Poll<Result>`!
331        fn poll_with_sync_check(input: Result<i32, &'static str>) -> Poll<Result<i32, String>> {
332            let val = try_op!(input);
333            Poll::Ready(Ok(val + 1))
334        }
335
336        assert_eq!(poll_with_sync_check(Ok(5)), Poll::Ready(Ok(6)));
337        assert_eq!(
338            poll_with_sync_check(Err("fail")),
339            Poll::Ready(Err("fail".to_string()))
340        );
341    }
342}