Skip to main content

rune/modules/
result.rs

1//! The [`Result`] type.
2
3use core::cmp::Ordering;
4use core::hash::Hasher as _;
5
6use crate as rune;
7use crate::alloc::fmt::TryWrite;
8use crate::alloc::prelude::*;
9use crate::runtime::{
10    ControlFlow, EnvProtocolCaller, Formatter, Function, Hasher, Panic, Protocol, Value, VmError,
11};
12use crate::{hash_in, ContextError, Hash, Module};
13
14/// The [`Result`] type.
15///
16/// This module deals with the fundamental [`Result`] type in Rune.
17#[rune::module(::std::result)]
18pub fn module() -> Result<Module, ContextError> {
19    let mut m = Module::from_meta(self::module__meta)?;
20
21    // Sorted for ease of finding
22    let mut result = m
23        .ty::<Result<Value, Value>>()?
24        .static_docs(&["Result is a type that represents either success (Ok) or failure (Err)."])?
25        .make_enum(&["Ok", "Err"])?;
26
27    result
28        .variant_mut(0)?
29        .make_unnamed(1)?
30        .constructor(Result::Ok)?
31        .static_docs(&["Contains the success value"])?;
32
33    result
34        .variant_mut(1)?
35        .make_unnamed(1)?
36        .constructor(Result::Err)?
37        .static_docs(&["Contains the error value"])?;
38
39    m.function_meta(is_variant__meta)?;
40
41    m.index_function(
42        &Protocol::GET,
43        0,
44        |this: &Result<Value, Value>| match this {
45            Result::Ok(value) => value.clone(),
46            Result::Err(value) => value.clone(),
47        },
48    )?;
49
50    m.function_meta(ok)?;
51    m.function_meta(is_ok)?;
52    m.function_meta(is_err)?;
53    m.function_meta(unwrap)?;
54    m.function_meta(unwrap_or)?;
55    m.function_meta(unwrap_or_else)?;
56    m.function_meta(expect)?;
57    m.function_meta(and_then)?;
58    m.function_meta(map)?;
59
60    m.function_meta(clone__meta)?;
61    m.implement_trait::<Result<Value, Value>>(rune::item!(::std::clone::Clone))?;
62
63    m.function_meta(partial_eq__meta)?;
64    m.implement_trait::<Result<Value, Value>>(rune::item!(::std::cmp::PartialEq))?;
65
66    m.function_meta(eq__meta)?;
67    m.implement_trait::<Result<Value, Value>>(rune::item!(::std::cmp::Eq))?;
68
69    m.function_meta(partial_cmp__meta)?;
70    m.implement_trait::<Result<Value, Value>>(rune::item!(::std::cmp::PartialOrd))?;
71
72    m.function_meta(cmp__meta)?;
73    m.implement_trait::<Result<Value, Value>>(rune::item!(::std::cmp::Ord))?;
74
75    m.function_meta(hash__meta)?;
76    m.function_meta(debug_fmt__meta)?;
77
78    m.function_meta(result_try__meta)?;
79    Ok(m)
80}
81
82#[rune::function(instance, keep, protocol = IS_VARIANT)]
83#[inline]
84pub(crate) fn is_variant(this: &Result<Value, Value>, variant_hash: Hash) -> bool {
85    match (this, variant_hash) {
86        (Ok(..), hash_in!(crate, ::std::result::Result::Ok)) => true,
87        (Err(..), hash_in!(crate, ::std::result::Result::Err)) => true,
88        _ => false,
89    }
90}
91
92/// Converts from [`Result`] to [`Option`].
93///
94/// # Examples
95///
96/// ```rune
97/// let a = Ok(2);
98/// let b = Err(3);
99///
100/// assert_eq!(a.ok(), Some(2));
101/// assert_eq!(b.ok(), None);
102/// ```
103#[rune::function(instance)]
104fn ok(result: &Result<Value, Value>) -> Option<Value> {
105    result.as_ref().ok().cloned()
106}
107
108/// Returns `true` if the result is [`Ok`].
109///
110/// # Examples
111///
112/// ```rune
113/// let x = Ok(-3);
114/// assert_eq!(x.is_ok(), true);
115///
116/// let x = Err("Some error message");
117/// assert_eq!(x.is_ok(), false);
118/// ```
119#[rune::function(instance)]
120fn is_ok(result: &Result<Value, Value>) -> bool {
121    result.is_ok()
122}
123
124/// Returns `true` if the result is [`Err`].
125///
126/// # Examples
127///
128/// ```rune
129/// let x = Ok(-3);
130/// assert_eq!(x.is_err(), false);
131///
132/// let x = Err("Some error message");
133/// assert_eq!(x.is_err(), true);
134/// ```
135#[rune::function(instance)]
136fn is_err(result: &Result<Value, Value>) -> bool {
137    result.is_err()
138}
139
140/// Returns the contained [`Ok`] value, consuming the `self` value.
141///
142/// Because this function may panic, its use is generally discouraged. Instead,
143/// prefer to use pattern matching and handle the [`Err`] case explicitly, or
144/// call [`unwrap_or`], [`unwrap_or_else`], or `unwrap_or_default`.
145///
146/// [`unwrap_or`]: Result::unwrap_or
147/// [`unwrap_or_else`]: Result::unwrap_or_else
148///
149/// # Panics
150///
151/// Panics if the value is an [`Err`], with a panic message provided by the
152/// [`Err`]'s value.
153///
154/// # Examples
155///
156/// Basic usage:
157///
158/// ```rune
159/// let x = Ok(2);
160/// assert_eq!(x.unwrap(), 2);
161/// ```
162///
163/// ```rune,should_panic
164/// let x = Err("emergency failure");
165/// x.unwrap(); // panics with `emergency failure`
166/// ```
167#[rune::function(instance)]
168fn unwrap(result: &Result<Value, Value>) -> Result<Value, VmError> {
169    match result {
170        Ok(value) => Ok(value.clone()),
171        Err(err) => {
172            let mut m = String::new();
173            write!(m, "Called `Result::unwrap()` on an `Err` value: ")?;
174            Formatter::format_with(&mut m, |f| err.debug_fmt(f))?;
175            Err(VmError::from(Panic::custom(m)))
176        }
177    }
178}
179
180/// Returns the contained [`Ok`] value or a provided default.
181///
182/// Arguments passed to [`unwrap_or`] are eagerly evaluated; if you are passing
183/// the result of a function call, it is recommended to use [`unwrap_or_else`],
184/// which is lazily evaluated.
185///
186/// [`unwrap_or_else`]: Result::unwrap_or_else
187///
188/// # Examples
189///
190/// ```rune
191/// let default_value = 2;
192/// let x = Ok(9);
193/// assert_eq!(x.unwrap_or(default_value), 9);
194///
195/// let x = Err("error");
196/// assert_eq!(x.unwrap_or(default_value), default_value);
197/// ```
198#[rune::function(instance)]
199fn unwrap_or(this: &Result<Value, Value>, default: Value) -> Value {
200    match this {
201        Ok(value) => value.clone(),
202        Err(_) => default.clone(),
203    }
204}
205
206/// Returns the contained [`Ok`] value or computes it from a closure.
207///
208///
209/// # Examples
210///
211/// ```rune
212/// fn count(x) {
213///     x.len()
214/// }
215///
216/// assert_eq!(Ok(2).unwrap_or_else(count), 2);
217/// assert_eq!(Err("foo").unwrap_or_else(count), 3);
218/// ```
219#[rune::function(instance)]
220fn unwrap_or_else(this: &Result<Value, Value>, default: Function) -> Result<Value, VmError> {
221    match this {
222        Ok(value) => Ok(value.clone()),
223        Err(error) => default.call((error,)),
224    }
225}
226
227/// Returns the contained [`Ok`] value, consuming the `self` value.
228///
229/// Because this function may panic, its use is generally discouraged. Instead,
230/// prefer to use pattern matching and handle the [`Err`] case explicitly, or
231/// call [`unwrap_or`], [`unwrap_or_else`], or `unwrap_or_default`.
232///
233/// [`unwrap_or`]: Result::unwrap_or
234/// [`unwrap_or_else`]: Result::unwrap_or_else
235///
236/// # Panics
237///
238/// Panics if the value is an [`Err`], with a panic message including the passed
239/// message, and the content of the [`Err`].
240///
241/// # Examples
242///
243/// ```rune,should_panic
244/// let x = Err("emergency failure");
245/// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
246/// ```
247///
248/// # Recommended Message Style
249///
250/// We recommend that `expect` messages are used to describe the reason you
251/// _expect_ the [`Result`] should be [`Ok`]. If you're having trouble remembering
252/// how to phrase expect error messages remember to focus on the word "should"
253/// as in "env variable should be set by blah" or "the given binary should be
254/// available and executable by the current user".
255#[rune::function(instance)]
256fn expect(result: &Result<Value, Value>, message: Value) -> Result<Value, VmError> {
257    match result {
258        Ok(value) => Ok(value.clone()),
259        Err(err) => {
260            let mut s = String::new();
261            Formatter::format_with(&mut s, |f| {
262                message.display_fmt(f)?;
263                f.try_write_str(": ")?;
264                err.debug_fmt(f)?;
265                Ok::<_, VmError>(())
266            })?;
267            Err(VmError::from(Panic::custom(s)))
268        }
269    }
270}
271
272/// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
273///
274/// This function can be used for control flow based on [`Result`] values.
275///
276/// # Examples
277///
278/// ```rune
279/// fn sq_then_to_string(x) {
280///     x.checked_mul(x).ok_or("overflowed")
281/// }
282///
283/// assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4));
284/// assert_eq!(Ok(u64::MAX).and_then(sq_then_to_string), Err("overflowed"));
285/// assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number"));
286/// ```
287#[rune::function(instance)]
288fn and_then(this: &Result<Value, Value>, op: Function) -> Result<Result<Value, Value>, VmError> {
289    match this {
290        Ok(v) => Ok(op.call((v,))?),
291        Err(e) => Ok(Err(e.clone())),
292    }
293}
294
295/// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
296/// contained [`Ok`] value, leaving an [`Err`] value untouched.
297///
298/// This function can be used to compose the results of two functions.
299///
300/// # Examples
301///
302/// Print the numbers on each line of a string multiplied by two.
303///
304/// ```rune
305/// let lines = ["1", "2", "3", "4"];
306/// let out = [];
307///
308/// for num in lines {
309///     out.push(i64::parse(num).map(|i| i * 2)?);
310/// }
311///
312/// assert_eq!(out, [2, 4, 6, 8]);
313/// ```
314#[rune::function(instance)]
315fn map(this: &Result<Value, Value>, then: Function) -> Result<Result<Value, Value>, VmError> {
316    match this {
317        Ok(v) => Ok(Ok(then.call((v,))?)),
318        Err(e) => Ok(Err(e.clone())),
319    }
320}
321
322/// Clone the result.
323///
324/// # Examples
325///
326/// ```rune
327/// let a = Ok(b"hello world");
328/// let b = a.clone();
329///
330/// a?.extend(b"!");
331///
332/// assert_eq!(a, Ok(b"hello world!"));
333/// assert_eq!(b, Ok(b"hello world"));
334/// ```
335#[rune::function(keep, instance, protocol = CLONE)]
336fn clone(this: &Result<Value, Value>) -> Result<Result<Value, Value>, VmError> {
337    Ok(match this {
338        Ok(ok) => Ok(ok.clone_with(&mut EnvProtocolCaller)?),
339        Err(err) => Err(err.clone_with(&mut EnvProtocolCaller)?),
340    })
341}
342
343/// Test two results for partial equality.
344///
345/// # Examples
346///
347/// ```rune
348/// assert_eq!(Ok(b"a") == Ok(b"a"), true);
349/// assert_eq!(Ok(b"a") == Ok(b"ab"), false);
350/// assert_eq!(Ok(b"ab") == Ok(b"a"), false);
351/// ```
352///
353/// Using explicit functions:
354///
355/// ```rune
356/// use std::ops::partial_eq;
357///
358/// assert_eq!(partial_eq(Ok(b"a"), Ok(b"a")), true);
359/// assert_eq!(partial_eq(Ok(b"a"), Ok(b"ab")), false);
360/// assert_eq!(partial_eq(Ok(b"ab"), Ok(b"a")), false);
361/// ```
362#[rune::function(keep, instance, protocol = PARTIAL_EQ)]
363#[inline]
364fn partial_eq(this: &Result<Value, Value>, rhs: &Result<Value, Value>) -> Result<bool, VmError> {
365    match (this, rhs) {
366        (Ok(a), Ok(b)) => Ok(Value::partial_eq(a, b)?),
367        (Err(a), Err(b)) => Ok(Value::partial_eq(a, b)?),
368        _ => Ok(false),
369    }
370}
371
372/// Test two results for total equality.
373///
374/// # Examples
375///
376/// ```rune
377/// use std::ops::eq;
378///
379/// assert_eq!(eq(Ok(b"a"), Ok(b"a")), true);
380/// assert_eq!(eq(Ok(b"a"), Ok(b"ab")), false);
381/// assert_eq!(eq(Ok(b"ab"), Ok(b"a")), false);
382/// ```
383#[rune::function(keep, instance, protocol = EQ)]
384#[inline]
385fn eq(this: &Result<Value, Value>, rhs: &Result<Value, Value>) -> Result<bool, VmError> {
386    match (this, rhs) {
387        (Ok(a), Ok(b)) => Value::eq(a, b),
388        (Err(a), Err(b)) => Value::eq(a, b),
389        _ => Ok(false),
390    }
391}
392
393/// Perform a partial ordered comparison between two results.
394///
395/// # Examples
396///
397/// ```rune
398/// assert!(Ok(b"a") < Ok(b"ab"));
399/// assert!(Ok(b"ab") > Ok(b"a"));
400/// assert!(Ok(b"a") == Ok(b"a"));
401/// ```
402///
403/// Using explicit functions:
404///
405/// ```rune
406/// use std::cmp::Ordering;
407/// use std::ops::partial_cmp;
408///
409/// assert_eq!(partial_cmp(Ok(b"a"), Ok(b"ab")), Some(Ordering::Less));
410/// assert_eq!(partial_cmp(Ok(b"ab"), Ok(b"a")), Some(Ordering::Greater));
411/// assert_eq!(partial_cmp(Ok(b"a"), Ok(b"a")), Some(Ordering::Equal));
412/// ```
413#[rune::function(keep, instance, protocol = PARTIAL_CMP)]
414#[inline]
415fn partial_cmp(
416    this: &Result<Value, Value>,
417    rhs: &Result<Value, Value>,
418) -> Result<Option<Ordering>, VmError> {
419    match (this, rhs) {
420        (Ok(a), Ok(b)) => Value::partial_cmp(a, b),
421        (Err(a), Err(b)) => Value::partial_cmp(a, b),
422        (Ok(..), Err(..)) => Ok(Some(Ordering::Greater)),
423        (Err(..), Ok(..)) => Ok(Some(Ordering::Less)),
424    }
425}
426
427/// Perform a totally ordered comparison between two results.
428///
429/// # Examples
430///
431/// ```rune
432/// use std::cmp::Ordering;
433/// use std::ops::cmp;
434///
435/// assert_eq!(cmp(Ok(b"a"), Ok(b"ab")), Ordering::Less);
436/// assert_eq!(cmp(Ok(b"ab"), Ok(b"a")), Ordering::Greater);
437/// assert_eq!(cmp(Ok(b"a"), Ok(b"a")), Ordering::Equal);
438/// ```
439#[rune::function(keep, instance, protocol = CMP)]
440#[inline]
441fn cmp(this: &Result<Value, Value>, rhs: &Result<Value, Value>) -> Result<Ordering, VmError> {
442    match (this, rhs) {
443        (Ok(a), Ok(b)) => Value::cmp(a, b),
444        (Err(a), Err(b)) => Value::cmp(a, b),
445        (Ok(..), Err(..)) => Ok(Ordering::Greater),
446        (Err(..), Ok(..)) => Ok(Ordering::Less),
447    }
448}
449
450/// Hash the result.
451///
452/// # Examples
453///
454/// ```rune
455/// use std::ops::hash;
456///
457/// let a = Ok("hello");
458/// let b = Ok("hello");
459///
460/// assert_eq!(hash(a), hash(b));
461/// ```
462#[rune::function(keep, instance, protocol = HASH)]
463fn hash(this: &Result<Value, Value>, hasher: &mut Hasher) -> Result<(), VmError> {
464    match this {
465        Ok(value) => {
466            hasher.write_u64(0);
467            value.hash(hasher)?;
468        }
469        Err(value) => {
470            hasher.write_u64(1);
471            value.hash(hasher)?;
472        }
473    }
474
475    Ok(())
476}
477
478/// Write a debug representation of a result.
479///
480/// # Examples
481///
482/// ```rune
483/// println!("{:?}", Ok("Hello"));
484/// println!("{:?}", Err("Hello"));
485/// ```
486#[rune::function(keep, instance, protocol = DEBUG_FMT)]
487#[inline]
488fn debug_fmt(this: &Result<Value, Value>, f: &mut Formatter) -> Result<(), VmError> {
489    match this {
490        Ok(value) => {
491            f.try_write_str("Ok(")?;
492            value.debug_fmt(f)?;
493            f.try_write_str(")")?;
494        }
495        Err(value) => {
496            f.try_write_str("Err(")?;
497            value.debug_fmt(f)?;
498            f.try_write_str(")")?;
499        }
500    }
501
502    Ok(())
503}
504
505/// Using [`Result`] with the try protocol.
506///
507/// # Examples
508///
509/// ```rune
510/// fn maybe_add_one(value) {
511///     Ok(value? + 1)
512/// }
513///
514/// assert_eq!(maybe_add_one(Ok(4)), Ok(5));
515/// assert_eq!(maybe_add_one(Err("not a number")), Err("not a number"));
516/// ```
517#[rune::function(keep, instance, protocol = TRY)]
518pub(crate) fn result_try(this: &Result<Value, Value>) -> Result<ControlFlow, VmError> {
519    Ok(match this {
520        Ok(value) => ControlFlow::Continue(value.clone()),
521        Err(error) => ControlFlow::Break(Value::try_from(Err(error.clone()))?),
522    })
523}