Skip to main content

rib/interpreter/
interpreter_result.rs

1use crate::interpreter::interpreter_stack_value::RibInterpreterStackValue;
2use crate::wit_type::tuple;
3use crate::wit_type::WitType;
4use crate::{GetLiteralValue, LiteralValue};
5use crate::{Value, ValueAndType};
6use std::fmt::{Display, Formatter};
7
8#[derive(Debug, Clone, PartialEq)]
9pub enum RibResult {
10    Unit,
11    Val(ValueAndType),
12}
13
14impl Display for RibResult {
15    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
16        let wasm_wave = match self {
17            RibResult::Unit => ValueAndType::new(Value::Tuple(vec![]), tuple(vec![])).to_string(),
18            RibResult::Val(value_and_type) => value_and_type.to_string(),
19        };
20
21        write!(f, "{wasm_wave}")
22    }
23}
24
25impl RibResult {
26    pub fn from_rib_interpreter_stack_value(
27        stack_value: &RibInterpreterStackValue,
28    ) -> Option<RibResult> {
29        match stack_value {
30            RibInterpreterStackValue::Unit => Some(RibResult::Unit),
31            RibInterpreterStackValue::Val(value_and_type) => {
32                Some(RibResult::Val(value_and_type.clone()))
33            }
34            RibInterpreterStackValue::Iterator(_) => None,
35            RibInterpreterStackValue::Sink(_, _) => None,
36        }
37    }
38
39    pub fn get_bool(&self) -> Option<bool> {
40        match self {
41            RibResult::Val(ValueAndType {
42                value: Value::Bool(bool),
43                ..
44            }) => Some(*bool),
45            RibResult::Val(_) => None,
46            RibResult::Unit => None,
47        }
48    }
49    pub fn get_val(&self) -> Option<ValueAndType> {
50        match self {
51            RibResult::Val(val) => Some(val.clone()),
52            RibResult::Unit => None,
53        }
54    }
55
56    pub fn get_literal(&self) -> Option<LiteralValue> {
57        self.get_val().and_then(|x| x.get_literal())
58    }
59
60    pub fn get_record(&self) -> Option<Vec<(String, ValueAndType)>> {
61        self.get_val().and_then(|x| match x {
62            ValueAndType {
63                value: Value::Record(field_values),
64                typ: WitType::Record(typ),
65            } => Some(
66                field_values
67                    .into_iter()
68                    .zip(typ.fields)
69                    .map(|(value, typ)| (typ.name, ValueAndType::new(value, typ.typ)))
70                    .collect(),
71            ),
72            _ => None,
73        })
74    }
75}