rune/runtime/
control_flow.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
use core::ops;

use crate as rune;
use crate::alloc::clone::TryClone;
use crate::alloc::fmt::TryWrite;
use crate::Any;

use super::{
    EnvProtocolCaller, Formatter, FromValue, ProtocolCaller, RuntimeError, ToValue, Value, VmResult,
};

/// Used to tell an operation whether it should exit early or go on as usual.
///
/// This acts as the basis of the [`TRY`] protocol in Rune.
///
/// [`TRY`]: crate::runtime::Protocol::TRY
///
/// # Examples
///
/// ```rune
/// use std::ops::ControlFlow;
///
/// let c = ControlFlow::Continue(42);
/// assert_eq!(c.0, 42);
/// assert_eq!(c, ControlFlow::Continue(42));
/// ```
#[derive(Debug, Clone, TryClone, Any)]
#[try_clone(crate)]
#[rune(item = ::std::ops)]
pub enum ControlFlow {
    /// Move on to the next phase of the operation as normal.
    #[rune(constructor)]
    Continue(#[rune(get, set)] Value),
    /// Exit the operation without running subsequent phases.
    #[rune(constructor)]
    Break(#[rune(get, set)] Value),
}

impl ControlFlow {
    /// Test two control flows for partial equality.
    ///
    /// # Examples
    ///
    /// ```rune
    /// use std::ops::{partial_eq, ControlFlow};
    ///
    /// assert_eq! {
    ///     partial_eq(ControlFlow::Continue(true), ControlFlow::Continue(true)),
    ///     true
    /// };
    /// assert_eq! {
    ///     partial_eq(ControlFlow::Continue(true), ControlFlow::Break(false)),
    ///     false
    /// };
    /// assert_eq! {
    ///     partial_eq(ControlFlow::Break(false), ControlFlow::Continue(true)),
    ///     false
    /// };
    /// ```
    #[rune::function(keep, protocol = PARTIAL_EQ)]
    pub(crate) fn partial_eq(&self, other: &Self) -> VmResult<bool> {
        Self::partial_eq_with(self, other, &mut EnvProtocolCaller)
    }

    pub(crate) fn partial_eq_with(
        &self,
        other: &Self,
        caller: &mut dyn ProtocolCaller,
    ) -> VmResult<bool> {
        match (self, other) {
            (ControlFlow::Continue(a), ControlFlow::Continue(b)) => {
                Value::partial_eq_with(a, b, caller)
            }
            (ControlFlow::Break(a), ControlFlow::Break(b)) => Value::partial_eq_with(a, b, caller),
            _ => VmResult::Ok(false),
        }
    }

    /// Test two control flows for total equality.
    ///
    /// # Examples
    ///
    /// ```rune
    /// use std::ops::{eq, ControlFlow};
    ///
    /// assert_eq! {
    ///     eq(ControlFlow::Continue(true), ControlFlow::Continue(true)),
    ///     true
    /// };
    /// assert_eq! {
    ///     eq(ControlFlow::Continue(true), ControlFlow::Break(false)),
    ///     false
    /// };
    /// assert_eq! {
    ///     eq(ControlFlow::Break(false), ControlFlow::Continue(true)),
    ///     false
    /// };
    /// ```
    #[rune::function(keep, protocol = EQ)]
    pub(crate) fn eq(&self, other: &ControlFlow) -> VmResult<bool> {
        self.eq_with(other, &mut EnvProtocolCaller)
    }

    pub(crate) fn eq_with(
        &self,
        other: &ControlFlow,
        caller: &mut dyn ProtocolCaller,
    ) -> VmResult<bool> {
        match (self, other) {
            (ControlFlow::Continue(a), ControlFlow::Continue(b)) => Value::eq_with(a, b, caller),
            (ControlFlow::Break(a), ControlFlow::Break(b)) => Value::eq_with(a, b, caller),
            _ => VmResult::Ok(false),
        }
    }

    /// Debug print the control flow.
    ///
    /// # Examples
    ///
    /// ```rune
    /// use std::ops::ControlFlow;
    ///
    /// let string = format!("{:?}", ControlFlow::Continue(true));
    /// ```
    #[rune::function(keep, protocol = DEBUG_FMT)]
    pub(crate) fn debug_fmt(&self, f: &mut Formatter) -> VmResult<()> {
        Self::debug_fmt_with(self, f, &mut EnvProtocolCaller)
    }

    pub(crate) fn debug_fmt_with(
        &self,
        f: &mut Formatter,
        caller: &mut dyn ProtocolCaller,
    ) -> VmResult<()> {
        match self {
            ControlFlow::Continue(value) => {
                vm_try!(vm_write!(f, "Continue("));
                vm_try!(Value::debug_fmt_with(value, f, caller));
                vm_try!(vm_write!(f, ")"));
            }
            ControlFlow::Break(value) => {
                vm_try!(vm_write!(f, "Break("));
                vm_try!(Value::debug_fmt_with(value, f, caller));
                vm_try!(vm_write!(f, ")"));
            }
        }

        VmResult::Ok(())
    }

    /// Clone the control flow.
    ///
    /// # Examples
    ///
    /// ```rune
    /// use std::ops::ControlFlow;
    ///
    /// let flow = ControlFlow::Continue("Hello World");
    /// let flow2 = flow.clone();
    ///
    /// assert_eq!(flow, flow2);
    /// ```
    #[rune::function(keep, protocol = CLONE)]
    pub(crate) fn clone(&self) -> VmResult<Self> {
        VmResult::Ok(vm_try!(self.try_clone()))
    }
}

impl<B, C> ToValue for ops::ControlFlow<B, C>
where
    B: ToValue,
    C: ToValue,
{
    #[inline]
    fn to_value(self) -> Result<Value, RuntimeError> {
        let value = match self {
            ops::ControlFlow::Continue(value) => ControlFlow::Continue(C::to_value(value)?),
            ops::ControlFlow::Break(value) => ControlFlow::Break(B::to_value(value)?),
        };

        Ok(Value::try_from(value)?)
    }
}

impl<B, C> FromValue for ops::ControlFlow<B, C>
where
    B: FromValue,
    C: FromValue,
{
    #[inline]
    fn from_value(value: Value) -> Result<Self, RuntimeError> {
        Ok(match &*value.borrow_ref::<ControlFlow>()? {
            ControlFlow::Continue(value) => {
                ops::ControlFlow::Continue(C::from_value(value.clone())?)
            }
            ControlFlow::Break(value) => ops::ControlFlow::Break(B::from_value(value.clone())?),
        })
    }
}