rune/modules/
result.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! The [`Result`] type.

use core::cmp::Ordering;
use core::hash::Hasher as _;

use crate as rune;
use crate::alloc::fmt::TryWrite;
use crate::alloc::prelude::*;
use crate::runtime::{
    ControlFlow, EnvProtocolCaller, Formatter, Function, Hasher, Panic, Protocol, Value, VmResult,
};
use crate::{ContextError, Module};

/// The [`Result`] type.
///
/// This module deals with the fundamental [`Result`] type in Rune.
#[rune::module(::std::result)]
pub fn module() -> Result<Module, ContextError> {
    let mut m = Module::from_meta(self::module_meta)?;

    // Sorted for ease of finding
    let mut result = m
        .ty::<Result<Value, Value>>()?
        .static_docs(&["Result is a type that represents either success (Ok) or failure (Err)."])?
        .make_enum(&["Ok", "Err"])?;

    result
        .variant_mut(0)?
        .make_unnamed(1)?
        .constructor(Result::Ok)?
        .static_docs(&["Contains the success value"])?;

    result
        .variant_mut(1)?
        .make_unnamed(1)?
        .constructor(Result::Err)?
        .static_docs(&["Contains the error value"])?;

    m.associated_function(
        &Protocol::IS_VARIANT,
        |this: &Result<Value, Value>, index: usize| match (this, index) {
            (Result::Ok(_), 0) => true,
            (Result::Err(_), 1) => true,
            _ => false,
        },
    )?;

    m.index_function(
        &Protocol::GET,
        0,
        |this: &Result<Value, Value>| match this {
            Result::Ok(value) => VmResult::Ok(value.clone()),
            Result::Err(value) => VmResult::Ok(value.clone()),
        },
    )?;

    m.function_meta(ok)?;
    m.function_meta(is_ok)?;
    m.function_meta(is_err)?;
    m.function_meta(unwrap)?;
    m.function_meta(unwrap_or)?;
    m.function_meta(unwrap_or_else)?;
    m.function_meta(expect)?;
    m.function_meta(and_then)?;
    m.function_meta(map)?;

    m.function_meta(clone__meta)?;
    m.implement_trait::<Result<Value, Value>>(rune::item!(::std::clone::Clone))?;

    m.function_meta(partial_eq__meta)?;
    m.implement_trait::<Result<Value, Value>>(rune::item!(::std::cmp::PartialEq))?;

    m.function_meta(eq__meta)?;
    m.implement_trait::<Result<Value, Value>>(rune::item!(::std::cmp::Eq))?;

    m.function_meta(partial_cmp__meta)?;
    m.implement_trait::<Result<Value, Value>>(rune::item!(::std::cmp::PartialOrd))?;

    m.function_meta(cmp__meta)?;
    m.implement_trait::<Result<Value, Value>>(rune::item!(::std::cmp::Ord))?;

    m.function_meta(hash__meta)?;
    m.function_meta(debug_fmt__meta)?;

    m.function_meta(result_try__meta)?;
    Ok(m)
}

/// Converts from `Result` to `Option`.
///
/// # Examples
///
/// ```rune
/// let a = Ok(2);
/// let b = Err(3);
///
/// assert_eq!(a.ok(), Some(2));
/// assert_eq!(b.ok(), None);
/// ```
#[rune::function(instance)]
fn ok(result: &Result<Value, Value>) -> Option<Value> {
    result.as_ref().ok().cloned()
}

/// Returns `true` if the result is [`Ok`].
///
/// # Examples
///
/// ```rune
/// let x = Ok(-3);
/// assert_eq!(x.is_ok(), true);
///
/// let x = Err("Some error message");
/// assert_eq!(x.is_ok(), false);
/// ```
#[rune::function(instance)]
fn is_ok(result: &Result<Value, Value>) -> bool {
    result.is_ok()
}

/// Returns `true` if the result is [`Err`].
///
/// # Examples
///
/// ```rune
/// let x = Ok(-3);
/// assert_eq!(x.is_err(), false);
///
/// let x = Err("Some error message");
/// assert_eq!(x.is_err(), true);
/// ```
#[rune::function(instance)]
fn is_err(result: &Result<Value, Value>) -> bool {
    result.is_err()
}

/// Returns the contained [`Ok`] value, consuming the `self` value.
///
/// Because this function may panic, its use is generally discouraged. Instead,
/// prefer to use pattern matching and handle the [`Err`] case explicitly, or
/// call [`unwrap_or`], [`unwrap_or_else`], or [`unwrap_or_default`].
///
/// [`unwrap_or`]: Result::unwrap_or
/// [`unwrap_or_else`]: Result::unwrap_or_else
/// [`unwrap_or_default`]: Result::unwrap_or_default
///
/// # Panics
///
/// Panics if the value is an [`Err`], with a panic message provided by the
/// [`Err`]'s value.
///
/// # Examples
///
/// Basic usage:
///
/// ```rune
/// let x = Ok(2);
/// assert_eq!(x.unwrap(), 2);
/// ```
///
/// ```rune,should_panic
/// let x = Err("emergency failure");
/// x.unwrap(); // panics with `emergency failure`
/// ```
#[rune::function(instance)]
fn unwrap(result: &Result<Value, Value>) -> VmResult<Value> {
    match result {
        Ok(value) => VmResult::Ok(value.clone()),
        Err(err) => {
            let mut m = String::new();
            vm_try!(vm_write!(
                m,
                "Called `Result::unwrap()` on an `Err` value: "
            ));
            vm_try!(Formatter::format_with(&mut m, |f| err.debug_fmt(f)));
            VmResult::err(Panic::custom(m))
        }
    }
}

/// Returns the contained [`Ok`] value or a provided default.
///
/// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
/// the result of a function call, it is recommended to use [`unwrap_or_else`],
/// which is lazily evaluated.
///
/// [`unwrap_or_else`]: Result::unwrap_or_else
///
/// # Examples
///
/// ```rune
/// let default_value = 2;
/// let x = Ok(9);
/// assert_eq!(x.unwrap_or(default_value), 9);
///
/// let x = Err("error");
/// assert_eq!(x.unwrap_or(default_value), default_value);
/// ```
#[rune::function(instance)]
fn unwrap_or(this: &Result<Value, Value>, default: Value) -> Value {
    match this {
        Ok(value) => value.clone(),
        Err(_) => default.clone(),
    }
}

/// Returns the contained [`Ok`] value or computes it from a closure.
///
///
/// # Examples
///
/// ```rune
/// fn count(x) {
///     x.len()
/// }
///
/// assert_eq!(Ok(2).unwrap_or_else(count), 2);
/// assert_eq!(Err("foo").unwrap_or_else(count), 3);
/// ```
#[rune::function(instance)]
fn unwrap_or_else(this: &Result<Value, Value>, default: Function) -> VmResult<Value> {
    match this {
        Ok(value) => VmResult::Ok(value.clone()),
        Err(error) => default.call((error,)),
    }
}

/// Returns the contained [`Ok`] value, consuming the `self` value.
///
/// Because this function may panic, its use is generally discouraged. Instead,
/// prefer to use pattern matching and handle the [`Err`] case explicitly, or
/// call [`unwrap_or`], [`unwrap_or_else`], or [`unwrap_or_default`].
///
/// [`unwrap_or`]: Result::unwrap_or
/// [`unwrap_or_else`]: Result::unwrap_or_else
/// [`unwrap_or_default`]: Result::unwrap_or_default
///
/// # Panics
///
/// Panics if the value is an [`Err`], with a panic message including the passed
/// message, and the content of the [`Err`].
///
/// # Examples
///
/// ```rune,should_panic
/// let x = Err("emergency failure");
/// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
/// ```
///
/// # Recommended Message Style
///
/// We recommend that `expect` messages are used to describe the reason you
/// _expect_ the `Result` should be `Ok`. If you're having trouble remembering
/// how to phrase expect error messages remember to focus on the word "should"
/// as in "env variable should be set by blah" or "the given binary should be
/// available and executable by the current user".
#[rune::function(instance)]
fn expect(result: &Result<Value, Value>, message: Value) -> VmResult<Value> {
    match result {
        Ok(value) => VmResult::Ok(value.clone()),
        Err(err) => {
            let mut s = String::new();
            vm_try!(Formatter::format_with(&mut s, |f| {
                vm_try!(message.display_fmt(f));
                vm_try!(f.try_write_str(": "));
                vm_try!(err.debug_fmt(f));
                VmResult::Ok(())
            }));
            VmResult::err(Panic::custom(s))
        }
    }
}

/// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
///
/// This function can be used for control flow based on `Result` values.
///
/// # Examples
///
/// ```rune
/// fn sq_then_to_string(x) {
///     x.checked_mul(x).ok_or("overflowed")
/// }
///
/// assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4));
/// assert_eq!(Ok(u64::MAX).and_then(sq_then_to_string), Err("overflowed"));
/// assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number"));
/// ```
#[rune::function(instance)]
fn and_then(this: &Result<Value, Value>, op: Function) -> VmResult<Result<Value, Value>> {
    match this {
        Ok(v) => VmResult::Ok(vm_try!(op.call((v,)))),
        Err(e) => VmResult::Ok(Err(e.clone())),
    }
}

/// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
/// contained [`Ok`] value, leaving an [`Err`] value untouched.
///
/// This function can be used to compose the results of two functions.
///
/// # Examples
///
/// Print the numbers on each line of a string multiplied by two.
///
/// ```rune
/// let lines = ["1", "2", "3", "4"];
/// let out = [];
///
/// for num in lines {
///     out.push(i64::parse(num).map(|i| i * 2)?);
/// }
///
/// assert_eq!(out, [2, 4, 6, 8]);
/// ```
#[rune::function(instance)]
fn map(this: &Result<Value, Value>, then: Function) -> VmResult<Result<Value, Value>> {
    match this {
        Ok(v) => VmResult::Ok(Ok(vm_try!(then.call((v,))))),
        Err(e) => VmResult::Ok(Err(e.clone())),
    }
}

/// Clone the result.
///
/// # Examples
///
/// ```rune
/// let a = Ok(b"hello world");
/// let b = a.clone();
///
/// a?.extend(b"!");
///
/// assert_eq!(a, Ok(b"hello world!"));
/// assert_eq!(b, Ok(b"hello world"));
/// ```
#[rune::function(keep, instance, protocol = CLONE)]
fn clone(this: &Result<Value, Value>) -> VmResult<Result<Value, Value>> {
    VmResult::Ok(match this {
        Ok(ok) => Ok(vm_try!(ok.clone_with(&mut EnvProtocolCaller))),
        Err(err) => Err(vm_try!(err.clone_with(&mut EnvProtocolCaller))),
    })
}

/// Test two results for partial equality.
///
/// # Examples
///
/// ```rune
/// assert_eq!(Ok(b"a") == Ok(b"a"), true);
/// assert_eq!(Ok(b"a") == Ok(b"ab"), false);
/// assert_eq!(Ok(b"ab") == Ok(b"a"), false);
/// ```
///
/// Using explicit functions:
///
/// ```rune
/// use std::ops::partial_eq;
///
/// assert_eq!(partial_eq(Ok(b"a"), Ok(b"a")), true);
/// assert_eq!(partial_eq(Ok(b"a"), Ok(b"ab")), false);
/// assert_eq!(partial_eq(Ok(b"ab"), Ok(b"a")), false);
/// ```
#[rune::function(keep, instance, protocol = PARTIAL_EQ)]
#[inline]
fn partial_eq(this: &Result<Value, Value>, rhs: &Result<Value, Value>) -> VmResult<bool> {
    match (this, rhs) {
        (Ok(a), Ok(b)) => Value::partial_eq(a, b),
        (Err(a), Err(b)) => Value::partial_eq(a, b),
        _ => VmResult::Ok(false),
    }
}

/// Test two results for total equality.
///
/// # Examples
///
/// ```rune
/// use std::ops::eq;
///
/// assert_eq!(eq(Ok(b"a"), Ok(b"a")), true);
/// assert_eq!(eq(Ok(b"a"), Ok(b"ab")), false);
/// assert_eq!(eq(Ok(b"ab"), Ok(b"a")), false);
/// ```
#[rune::function(keep, instance, protocol = EQ)]
#[inline]
fn eq(this: &Result<Value, Value>, rhs: &Result<Value, Value>) -> VmResult<bool> {
    match (this, rhs) {
        (Ok(a), Ok(b)) => Value::eq(a, b),
        (Err(a), Err(b)) => Value::eq(a, b),
        _ => VmResult::Ok(false),
    }
}

/// Perform a partial ordered comparison between two results.
///
/// # Examples
///
/// ```rune
/// assert!(Ok(b"a") < Ok(b"ab"));
/// assert!(Ok(b"ab") > Ok(b"a"));
/// assert!(Ok(b"a") == Ok(b"a"));
/// ```
///
/// Using explicit functions:
///
/// ```rune
/// use std::cmp::Ordering;
/// use std::ops::partial_cmp;
///
/// assert_eq!(partial_cmp(Ok(b"a"), Ok(b"ab")), Some(Ordering::Less));
/// assert_eq!(partial_cmp(Ok(b"ab"), Ok(b"a")), Some(Ordering::Greater));
/// assert_eq!(partial_cmp(Ok(b"a"), Ok(b"a")), Some(Ordering::Equal));
/// ```
#[rune::function(keep, instance, protocol = PARTIAL_CMP)]
#[inline]
fn partial_cmp(
    this: &Result<Value, Value>,
    rhs: &Result<Value, Value>,
) -> VmResult<Option<Ordering>> {
    match (this, rhs) {
        (Ok(a), Ok(b)) => Value::partial_cmp(a, b),
        (Err(a), Err(b)) => Value::partial_cmp(a, b),
        (Ok(..), Err(..)) => VmResult::Ok(Some(Ordering::Greater)),
        (Err(..), Ok(..)) => VmResult::Ok(Some(Ordering::Less)),
    }
}

/// Perform a totally ordered comparison between two results.
///
/// # Examples
///
/// ```rune
/// use std::cmp::Ordering;
/// use std::ops::cmp;
///
/// assert_eq!(cmp(Ok(b"a"), Ok(b"ab")), Ordering::Less);
/// assert_eq!(cmp(Ok(b"ab"), Ok(b"a")), Ordering::Greater);
/// assert_eq!(cmp(Ok(b"a"), Ok(b"a")), Ordering::Equal);
/// ```
#[rune::function(keep, instance, protocol = CMP)]
#[inline]
fn cmp(this: &Result<Value, Value>, rhs: &Result<Value, Value>) -> VmResult<Ordering> {
    match (this, rhs) {
        (Ok(a), Ok(b)) => Value::cmp(a, b),
        (Err(a), Err(b)) => Value::cmp(a, b),
        (Ok(..), Err(..)) => VmResult::Ok(Ordering::Greater),
        (Err(..), Ok(..)) => VmResult::Ok(Ordering::Less),
    }
}

/// Hash the result.
///
/// # Examples
///
/// ```rune
/// use std::ops::hash;
///
/// let a = Ok("hello");
/// let b = Ok("hello");
///
/// assert_eq!(hash(a), hash(b));
/// ```
#[rune::function(keep, instance, protocol = HASH)]
fn hash(this: &Result<Value, Value>, hasher: &mut Hasher) -> VmResult<()> {
    match this {
        Ok(value) => {
            hasher.write_u64(0);
            vm_try!(value.hash(hasher));
        }
        Err(value) => {
            hasher.write_u64(1);
            vm_try!(value.hash(hasher));
        }
    }

    VmResult::Ok(())
}

/// Write a debug representation of a result.
///
/// # Examples
///
/// ```rune
/// println!("{:?}", Ok("Hello"));
/// println!("{:?}", Err("Hello"));
/// ```
#[rune::function(keep, instance, protocol = DEBUG_FMT)]
#[inline]
fn debug_fmt(this: &Result<Value, Value>, f: &mut Formatter) -> VmResult<()> {
    match this {
        Ok(value) => {
            vm_try!(f.try_write_str("Ok("));
            vm_try!(value.debug_fmt(f));
            vm_try!(f.try_write_str(")"));
        }
        Err(value) => {
            vm_try!(f.try_write_str("Err("));
            vm_try!(value.debug_fmt(f));
            vm_try!(f.try_write_str(")"));
        }
    }

    VmResult::Ok(())
}

/// Using [`Result`] with the try protocol.
///
/// # Examples
///
/// ```rune
/// fn maybe_add_one(value) {
///     Ok(value? + 1)
/// }
///
/// assert_eq!(maybe_add_one(Ok(4)), Ok(5));
/// assert_eq!(maybe_add_one(Err("not a number")), Err("not a number"));
/// ```
#[rune::function(keep, instance, protocol = TRY)]
pub(crate) fn result_try(this: &Result<Value, Value>) -> VmResult<ControlFlow> {
    VmResult::Ok(match this {
        Ok(value) => ControlFlow::Continue(value.clone()),
        Err(error) => ControlFlow::Break(vm_try!(Value::try_from(Err(error.clone())))),
    })
}