1use crate::ast::{Expr, Stmt};
5use crate::environment::Environment;
6use num_bigint::BigInt;
7use num_rational::Ratio;
8use num_traits::Zero;
9use std::cell::RefCell;
10use std::collections::HashMap;
11use std::fmt;
12use std::rc::Rc;
13
14#[derive(Debug, Clone)]
16pub enum Value {
17 Number(f64),
19
20 Fraction(Ratio<BigInt>),
22
23 String(String),
25
26 Boolean(bool),
28
29 Null,
31
32 Array(Vec<Value>),
34
35 Dict(HashMap<String, Value>),
37
38 Function {
40 params: Vec<String>,
41 body: Vec<Stmt>,
42 env: Rc<RefCell<Environment>>,
43 },
44
45 Generator {
47 params: Vec<String>,
48 body: Vec<Stmt>,
49 env: Rc<RefCell<Environment>>,
50 state: GeneratorState,
51 },
52
53 Lazy {
55 expr: Expr,
56 env: Rc<RefCell<Environment>>,
57 cached: Option<Box<Value>>,
58 },
59
60 BuiltIn { name: String, arity: usize },
62}
63
64#[derive(Debug, Clone)]
66pub enum GeneratorState {
67 NotStarted,
69
70 Running { position: usize },
72
73 Done,
75}
76
77impl Value {
78 pub fn is_truthy(&self) -> bool {
80 match self {
81 Value::Boolean(b) => *b,
82 Value::Null => false,
83 Value::Number(n) => *n != 0.0,
84 Value::Fraction(f) => !f.is_zero(),
85 Value::String(s) => !s.is_empty(),
86 Value::Array(arr) => !arr.is_empty(),
87 Value::Dict(dict) => !dict.is_empty(),
88 _ => true,
89 }
90 }
91
92 pub fn type_name(&self) -> &'static str {
94 match self {
95 Value::Number(_) => "Number",
96 Value::Fraction(_) => "Fraction",
97 Value::String(_) => "String",
98 Value::Boolean(_) => "Boolean",
99 Value::Null => "Null",
100 Value::Array(_) => "Array",
101 Value::Dict(_) => "Dict",
102 Value::Function { .. } => "Function",
103 Value::Generator { .. } => "Generator",
104 Value::Lazy { .. } => "Lazy",
105 Value::BuiltIn { .. } => "BuiltIn",
106 }
107 }
108
109 pub fn to_number(&self) -> Option<f64> {
111 match self {
112 Value::Number(n) => Some(*n),
113 Value::Fraction(f) => Some(
114 f.numer().to_string().parse::<f64>().ok()?
115 / f.denom().to_string().parse::<f64>().ok()?,
116 ),
117 Value::Boolean(true) => Some(1.0),
118 Value::Boolean(false) => Some(0.0),
119 Value::String(s) => s.parse().ok(),
120 _ => None,
121 }
122 }
123
124 pub fn to_string(&self) -> String {
126 match self {
127 Value::Number(n) => {
128 if n.fract() == 0.0 {
130 format!("{:.0}", n)
131 } else {
132 format!("{}", n)
133 }
134 }
135 Value::Fraction(f) => {
136 if f.is_integer() {
137 format!("{}", f.numer())
138 } else {
139 format!("{}/{}", f.numer(), f.denom())
140 }
141 }
142 Value::String(s) => s.clone(),
143 Value::Boolean(b) => b.to_string(),
144 Value::Null => "Null".to_string(),
145 Value::Array(arr) => {
146 let elements: Vec<String> = arr.iter().map(|v| v.to_string()).collect();
147 format!("[{}]", elements.join(", "))
148 }
149 Value::Dict(dict) => {
150 let pairs: Vec<String> = dict
151 .iter()
152 .map(|(k, v)| format!("{}: {}", k, v.to_string()))
153 .collect();
154 format!("{{{}}}", pairs.join(", "))
155 }
156 Value::Function { params, .. } => {
157 format!("<Function ({})>", params.join(", "))
158 }
159 Value::Generator { params, .. } => {
160 format!("<Generator ({})>", params.join(", "))
161 }
162 Value::Lazy { .. } => "<Lazy>".to_string(),
163 Value::BuiltIn { name, arity } => {
164 format!("<BuiltIn {} ({} args)>", name, arity)
165 }
166 }
167 }
168
169 pub fn equals(&self, other: &Value) -> bool {
171 match (self, other) {
172 (Value::Number(a), Value::Number(b)) => (a - b).abs() < f64::EPSILON,
173 (Value::Fraction(a), Value::Fraction(b)) => a == b,
174 (Value::String(a), Value::String(b)) => a == b,
175 (Value::Boolean(a), Value::Boolean(b)) => a == b,
176 (Value::Null, Value::Null) => true,
177 (Value::Array(a), Value::Array(b)) => {
178 a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| x.equals(y))
179 }
180 _ => false,
181 }
182 }
183
184 pub fn compare(&self, other: &Value) -> Option<std::cmp::Ordering> {
186 match (self, other) {
187 (Value::Number(a), Value::Number(b)) => a.partial_cmp(b),
188 (Value::Fraction(a), Value::Fraction(b)) => Some(a.cmp(b)),
189 (Value::String(a), Value::String(b)) => Some(a.cmp(b)),
190 (Value::Boolean(a), Value::Boolean(b)) => Some(a.cmp(b)),
191 _ => None,
192 }
193 }
194}
195
196impl fmt::Display for Value {
197 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
198 write!(f, "{}", self.to_string())
199 }
200}
201
202impl PartialEq for Value {
203 fn eq(&self, other: &Self) -> bool {
204 self.equals(other)
205 }
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211
212 #[test]
213 fn test_value_truthy() {
214 assert!(Value::Boolean(true).is_truthy());
215 assert!(!Value::Boolean(false).is_truthy());
216 assert!(!Value::Null.is_truthy());
217 assert!(Value::Number(1.0).is_truthy());
218 assert!(!Value::Number(0.0).is_truthy());
219 assert!(Value::String("hello".to_string()).is_truthy());
220 assert!(!Value::String("".to_string()).is_truthy());
221 }
222
223 #[test]
224 fn test_value_type_name() {
225 assert_eq!(Value::Number(42.0).type_name(), "Number");
226 assert_eq!(Value::String("test".to_string()).type_name(), "String");
227 assert_eq!(Value::Boolean(true).type_name(), "Boolean");
228 assert_eq!(Value::Null.type_name(), "Null");
229 assert_eq!(Value::Array(vec![]).type_name(), "Array");
230 }
231
232 #[test]
233 fn test_value_to_number() {
234 assert_eq!(Value::Number(42.0).to_number(), Some(42.0));
235 assert_eq!(Value::Boolean(true).to_number(), Some(1.0));
236 assert_eq!(Value::Boolean(false).to_number(), Some(0.0));
237 assert_eq!(Value::String("123".to_string()).to_number(), Some(123.0));
238 assert_eq!(Value::String("abc".to_string()).to_number(), None);
239 assert_eq!(Value::Null.to_number(), None);
240 }
241
242 #[test]
243 fn test_value_to_string() {
244 assert_eq!(Value::Number(42.0).to_string(), "42");
245 assert_eq!(Value::Number(3.14).to_string(), "3.14");
246 assert_eq!(Value::String("hello".to_string()).to_string(), "hello");
247 assert_eq!(Value::Boolean(true).to_string(), "true");
248 assert_eq!(Value::Null.to_string(), "Null");
249 assert_eq!(
250 Value::Array(vec![Value::Number(1.0), Value::Number(2.0)]).to_string(),
251 "[1, 2]"
252 );
253 }
254
255 #[test]
256 fn test_value_equals() {
257 assert!(Value::Number(42.0).equals(&Value::Number(42.0)));
258 assert!(!Value::Number(42.0).equals(&Value::Number(43.0)));
259 assert!(Value::String("test".to_string()).equals(&Value::String("test".to_string())));
260 assert!(Value::Boolean(true).equals(&Value::Boolean(true)));
261 assert!(Value::Null.equals(&Value::Null));
262 }
263
264 #[test]
265 fn test_value_compare() {
266 use std::cmp::Ordering;
267
268 assert_eq!(
269 Value::Number(42.0).compare(&Value::Number(43.0)),
270 Some(Ordering::Less)
271 );
272 assert_eq!(
273 Value::String("a".to_string()).compare(&Value::String("b".to_string())),
274 Some(Ordering::Less)
275 );
276 assert_eq!(
277 Value::Boolean(false).compare(&Value::Boolean(true)),
278 Some(Ordering::Less)
279 );
280 }
281
282 #[test]
283 fn test_array_equality() {
284 let arr1 = Value::Array(vec![Value::Number(1.0), Value::Number(2.0)]);
285 let arr2 = Value::Array(vec![Value::Number(1.0), Value::Number(2.0)]);
286 let arr3 = Value::Array(vec![Value::Number(1.0), Value::Number(3.0)]);
287
288 assert!(arr1.equals(&arr2));
289 assert!(!arr1.equals(&arr3));
290 }
291}