Skip to main content

rune/runtime/
control_flow.rs

1use core::ops;
2
3use crate as rune;
4use crate::alloc;
5use crate::alloc::clone::TryClone;
6use crate::alloc::fmt::TryWrite;
7use crate::Any;
8
9use super::{
10    EnvProtocolCaller, Formatter, FromValue, ProtocolCaller, RuntimeError, ToValue, Value, VmError,
11};
12
13/// Used to tell an operation whether it should exit early or go on as usual.
14///
15/// This acts as the basis of the `TRY` protocol in Rune.
16///
17/// # Examples
18///
19/// ```rune
20/// use std::ops::ControlFlow;
21///
22/// let c = ControlFlow::Continue(42);
23/// assert_eq!(c.0, 42);
24/// assert_eq!(c, ControlFlow::Continue(42));
25/// ```
26#[derive(Debug, Clone, TryClone, Any)]
27#[try_clone(crate)]
28#[rune(item = ::std::ops)]
29pub enum ControlFlow {
30    /// Move on to the next phase of the operation as normal.
31    #[rune(constructor)]
32    Continue(#[rune(get, set, dismantle)] Value),
33    /// Exit the operation without running subsequent phases.
34    #[rune(constructor)]
35    Break(#[rune(get, set, dismantle)] Value),
36}
37
38impl ControlFlow {
39    /// Test two control flows for partial equality.
40    ///
41    /// # Examples
42    ///
43    /// ```rune
44    /// use std::ops::{partial_eq, ControlFlow};
45    ///
46    /// assert_eq! {
47    ///     partial_eq(ControlFlow::Continue(true), ControlFlow::Continue(true)),
48    ///     true
49    /// };
50    /// assert_eq! {
51    ///     partial_eq(ControlFlow::Continue(true), ControlFlow::Break(false)),
52    ///     false
53    /// };
54    /// assert_eq! {
55    ///     partial_eq(ControlFlow::Break(false), ControlFlow::Continue(true)),
56    ///     false
57    /// };
58    /// ```
59    #[rune::function(keep, protocol = PARTIAL_EQ)]
60    pub(crate) fn partial_eq(&self, other: &Self) -> Result<bool, VmError> {
61        Self::partial_eq_with(self, other, &mut EnvProtocolCaller)
62    }
63
64    pub(crate) fn partial_eq_with(
65        &self,
66        other: &Self,
67        caller: &mut dyn ProtocolCaller,
68    ) -> Result<bool, VmError> {
69        match (self, other) {
70            (ControlFlow::Continue(a), ControlFlow::Continue(b)) => {
71                Value::partial_eq_with(a, b, caller)
72            }
73            (ControlFlow::Break(a), ControlFlow::Break(b)) => Value::partial_eq_with(a, b, caller),
74            _ => Ok(false),
75        }
76    }
77
78    /// Test two control flows for total equality.
79    ///
80    /// # Examples
81    ///
82    /// ```rune
83    /// use std::ops::{eq, ControlFlow};
84    ///
85    /// assert_eq! {
86    ///     eq(ControlFlow::Continue(true), ControlFlow::Continue(true)),
87    ///     true
88    /// };
89    /// assert_eq! {
90    ///     eq(ControlFlow::Continue(true), ControlFlow::Break(false)),
91    ///     false
92    /// };
93    /// assert_eq! {
94    ///     eq(ControlFlow::Break(false), ControlFlow::Continue(true)),
95    ///     false
96    /// };
97    /// ```
98    #[rune::function(keep, protocol = EQ)]
99    pub(crate) fn eq(&self, other: &ControlFlow) -> Result<bool, VmError> {
100        self.eq_with(other, &mut EnvProtocolCaller)
101    }
102
103    pub(crate) fn eq_with(
104        &self,
105        other: &ControlFlow,
106        caller: &mut dyn ProtocolCaller,
107    ) -> Result<bool, VmError> {
108        match (self, other) {
109            (ControlFlow::Continue(a), ControlFlow::Continue(b)) => Value::eq_with(a, b, caller),
110            (ControlFlow::Break(a), ControlFlow::Break(b)) => Value::eq_with(a, b, caller),
111            _ => Ok(false),
112        }
113    }
114
115    /// Debug print the control flow.
116    ///
117    /// # Examples
118    ///
119    /// ```rune
120    /// use std::ops::ControlFlow;
121    ///
122    /// let string = format!("{:?}", ControlFlow::Continue(true));
123    /// ```
124    #[rune::function(keep, protocol = DEBUG_FMT)]
125    pub(crate) fn debug_fmt(&self, f: &mut Formatter) -> Result<(), VmError> {
126        Self::debug_fmt_with(self, f, &mut EnvProtocolCaller)
127    }
128
129    pub(crate) fn debug_fmt_with(
130        &self,
131        f: &mut Formatter,
132        caller: &mut dyn ProtocolCaller,
133    ) -> Result<(), VmError> {
134        match self {
135            ControlFlow::Continue(value) => {
136                write!(f, "Continue(")?;
137                Value::debug_fmt_with(value, f, caller)?;
138                write!(f, ")")?;
139            }
140            ControlFlow::Break(value) => {
141                write!(f, "Break(")?;
142                Value::debug_fmt_with(value, f, caller)?;
143                write!(f, ")")?;
144            }
145        }
146
147        Ok(())
148    }
149
150    /// Clone the control flow.
151    ///
152    /// # Examples
153    ///
154    /// ```rune
155    /// use std::ops::ControlFlow;
156    ///
157    /// let flow = ControlFlow::Continue("Hello World");
158    /// let flow2 = flow.clone();
159    ///
160    /// assert_eq!(flow, flow2);
161    /// ```
162    #[rune::function(keep, protocol = CLONE)]
163    pub(crate) fn clone(&self) -> alloc::Result<Self> {
164        self.try_clone()
165    }
166}
167
168impl<B, C> ToValue for ops::ControlFlow<B, C>
169where
170    B: ToValue,
171    C: ToValue,
172{
173    #[inline]
174    fn to_value(self) -> Result<Value, RuntimeError> {
175        let value = match self {
176            ops::ControlFlow::Continue(value) => ControlFlow::Continue(C::to_value(value)?),
177            ops::ControlFlow::Break(value) => ControlFlow::Break(B::to_value(value)?),
178        };
179
180        Ok(Value::try_from(value)?)
181    }
182}
183
184impl<B, C> FromValue for ops::ControlFlow<B, C>
185where
186    B: FromValue,
187    C: FromValue,
188{
189    #[inline]
190    fn from_value(value: Value) -> Result<Self, RuntimeError> {
191        Ok(match &*value.borrow_ref::<ControlFlow>()? {
192            ControlFlow::Continue(value) => {
193                ops::ControlFlow::Continue(C::from_value(value.clone())?)
194            }
195            ControlFlow::Break(value) => ops::ControlFlow::Break(B::from_value(value.clone())?),
196        })
197    }
198}