Skip to main content

textwrite/
value.rs

1//! Runtime values for TextWrite.
2
3use std::cell::RefCell;
4use std::rc::Rc;
5
6use crate::ast::Stmt;
7use crate::interp::EnvRef;
8
9/// A user-defined function, with the environment it closed over.
10pub struct Function {
11    pub name: Option<String>,
12    pub params: Vec<String>,
13    pub body: Rc<Vec<Stmt>>,
14    pub env: EnvRef,
15}
16
17impl std::fmt::Debug for Function {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        match &self.name {
20            Some(n) => write!(f, "<fn {n}>"),
21            None => write!(f, "<fn>"),
22        }
23    }
24}
25
26/// Insertion-ordered map entries. Lookup is linear, which is plenty here.
27pub type MapData = Vec<(Rc<str>, Value)>;
28
29/// A TextWrite runtime value.
30#[derive(Clone)]
31pub enum Value {
32    None,
33    Bool(bool),
34    Int(i64),
35    Float(f64),
36    Str(Rc<str>),
37    List(Rc<RefCell<Vec<Value>>>),
38    Map(Rc<RefCell<MapData>>),
39    Func(Rc<Function>),
40    Builtin(&'static str),
41}
42
43impl Value {
44    pub fn str(s: impl Into<String>) -> Value {
45        Value::Str(Rc::from(s.into()))
46    }
47
48    pub fn list(items: Vec<Value>) -> Value {
49        Value::List(Rc::new(RefCell::new(items)))
50    }
51
52    pub fn map(entries: MapData) -> Value {
53        Value::Map(Rc::new(RefCell::new(entries)))
54    }
55
56    pub fn type_name(&self) -> &'static str {
57        match self {
58            Value::None => "none",
59            Value::Bool(_) => "bool",
60            Value::Int(_) => "int",
61            Value::Float(_) => "float",
62            Value::Str(_) => "string",
63            Value::List(_) => "list",
64            Value::Map(_) => "map",
65            Value::Func(_) | Value::Builtin(_) => "function",
66        }
67    }
68
69    pub fn is_truthy(&self) -> bool {
70        match self {
71            Value::None => false,
72            Value::Bool(b) => *b,
73            Value::Int(n) => *n != 0,
74            Value::Float(f) => *f != 0.0,
75            Value::Str(s) => !s.is_empty(),
76            Value::List(l) => !l.borrow().is_empty(),
77            Value::Map(m) => !m.borrow().is_empty(),
78            Value::Func(_) | Value::Builtin(_) => true,
79        }
80    }
81
82    /// Structural equality, backing the `is` / `==` operators.
83    pub fn deep_eq(&self, other: &Value) -> bool {
84        match (self, other) {
85            (Value::None, Value::None) => true,
86            (Value::Bool(a), Value::Bool(b)) => a == b,
87            (Value::Int(a), Value::Int(b)) => a == b,
88            (Value::Float(a), Value::Float(b)) => a == b,
89            (Value::Int(a), Value::Float(b)) | (Value::Float(b), Value::Int(a)) => {
90                (*a as f64) == *b
91            }
92            (Value::Str(a), Value::Str(b)) => a == b,
93            (Value::List(a), Value::List(b)) => {
94                if Rc::ptr_eq(a, b) {
95                    return true;
96                }
97                let a = a.borrow();
98                let b = b.borrow();
99                a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| x.deep_eq(y))
100            }
101            (Value::Map(a), Value::Map(b)) => {
102                if Rc::ptr_eq(a, b) {
103                    return true;
104                }
105                let a = a.borrow();
106                let b = b.borrow();
107                a.len() == b.len()
108                    && a.iter().all(|(k, v)| {
109                        b.iter()
110                            .find(|(k2, _)| k == k2)
111                            .is_some_and(|(_, v2)| v.deep_eq(v2))
112                    })
113            }
114            (Value::Func(a), Value::Func(b)) => Rc::ptr_eq(a, b),
115            (Value::Builtin(a), Value::Builtin(b)) => a == b,
116            _ => false,
117        }
118    }
119
120    pub fn as_f64(&self) -> Option<f64> {
121        match self {
122            Value::Int(n) => Some(*n as f64),
123            Value::Float(f) => Some(*f),
124            _ => None,
125        }
126    }
127
128    pub fn as_i64(&self) -> Option<i64> {
129        match self {
130            Value::Int(n) => Some(*n),
131            Value::Float(f) => Some(*f as i64),
132            _ => None,
133        }
134    }
135
136    pub fn as_str(&self) -> Option<&str> {
137        match self {
138            Value::Str(s) => Some(s),
139            _ => None,
140        }
141    }
142
143    /// A debug-style rendering, quoting strings (used inside lists and maps).
144    pub fn repr(&self) -> String {
145        match self {
146            Value::None => "none".to_string(),
147            Value::Bool(b) => b.to_string(),
148            Value::Int(n) => n.to_string(),
149            Value::Float(f) => format_float(*f),
150            Value::Str(s) => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
151            Value::List(items) => {
152                let items = items.borrow();
153                let inner: Vec<String> = items.iter().map(Value::repr).collect();
154                format!("[{}]", inner.join(", "))
155            }
156            Value::Map(map) => {
157                let map = map.borrow();
158                let inner: Vec<String> = map
159                    .iter()
160                    .map(|(k, v)| format!("{k}: {}", v.repr()))
161                    .collect();
162                format!("{{{}}}", inner.join(", "))
163            }
164            Value::Func(f) => match &f.name {
165                Some(n) => format!("<fn {n}>"),
166                None => "<fn>".to_string(),
167            },
168            Value::Builtin(n) => format!("<builtin {n}>"),
169        }
170    }
171
172    /// Rendering used by `print` and string interpolation: strings unquoted.
173    pub fn to_display(&self) -> String {
174        match self {
175            Value::Str(s) => s.to_string(),
176            other => other.repr(),
177        }
178    }
179}
180
181impl std::fmt::Display for Value {
182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        f.write_str(&self.to_display())
184    }
185}
186
187impl std::fmt::Debug for Value {
188    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189        f.write_str(&self.repr())
190    }
191}
192
193/// Formats a float without a trailing `.0` for integral values.
194pub fn format_float(f: f64) -> String {
195    if f.is_finite() && f.fract() == 0.0 && f.abs() < 1e15 {
196        format!("{}", f as i64)
197    } else {
198        format!("{f}")
199    }
200}
201
202// --- Map helpers -----------------------------------------------------------
203
204pub fn map_get(map: &Rc<RefCell<MapData>>, key: &str) -> Option<Value> {
205    map.borrow()
206        .iter()
207        .find(|(k, _)| &**k == key)
208        .map(|(_, v)| v.clone())
209}
210
211pub fn map_contains(map: &Rc<RefCell<MapData>>, key: &str) -> bool {
212    map.borrow().iter().any(|(k, _)| &**k == key)
213}
214
215pub fn map_insert(map: &Rc<RefCell<MapData>>, key: &str, value: Value) {
216    let mut map = map.borrow_mut();
217    if let Some(slot) = map.iter_mut().find(|(k, _)| &**k == key) {
218        *slot = (slot.0.clone(), value);
219    } else {
220        map.push((Rc::from(key), value));
221    }
222}