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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
//! Tokay value
use super::{BoxedObject, Dict, Object, RefValue};
use crate::{Accept, Context, Error, Reject};
use tokay_macros::tokay_method;
extern crate self as tokay;
use num::{ToPrimitive, Zero};
use num_bigint::BigInt;
use std::any::Any;
use std::cmp::Ordering;

#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    // Atomics
    Void,  // void
    Null,  // null
    True,  // true
    False, // false

    // Numerics
    Int(BigInt), // int
    Float(f64),  // float

    // Objects
    Object(BoxedObject), // object
}

impl Value {
    /// Return reference to object of type T.
    pub fn object<T: Any>(&self) -> Option<&T> {
        if let Self::Object(o) = self {
            return o.as_any().downcast_ref::<T>();
        }

        None
    }

    /// Return mutable reference to object of type T.
    pub fn object_mut<T: Any>(&mut self) -> Option<&mut T> {
        if let Self::Object(o) = self {
            return o.as_any_mut().downcast_mut::<T>();
        }

        None
    }

    /// Extract object of type T from Val.
    pub fn into_object<T: Any>(self) -> Option<T> {
        if let Self::Object(o) = self {
            if let Ok(inner) = o.into_any().downcast::<T>() {
                return Some(*inner);
            }
        }

        None
    }

    // Constructors
    tokay_method!("bool : @value", Ok(RefValue::from(value.is_true())));
    tokay_method!("int : @value", {
        if let Ok(value) = value.to_bigint() {
            Ok(RefValue::from(value))
        } else {
            Err(Error::from(format!(
                "`{}` cannot be converted to int",
                value.name()
            )))
        }
    });
    tokay_method!("float : @value", {
        if let Ok(value) = value.to_f64() {
            Ok(RefValue::from(value))
        } else {
            Err(Error::from(format!(
                "`{}` cannot be converted to float",
                value.name()
            )))
        }
    });

    // float methods
    tokay_method!(
        "float_ceil : @float",
        Ok(RefValue::from(float.to_f64()?.ceil()))
    );
    tokay_method!(
        "float_trunc : @float",
        Ok(RefValue::from(float.to_f64()?.trunc()))
    );
    tokay_method!(
        "float_fract : @float",
        Ok(RefValue::from(float.to_f64()?.fract()))
    );
}

impl Object for Value {
    fn severity(&self) -> u8 {
        match self {
            Self::Int(_) => 1,
            Self::Float(_) => 2,
            Self::Object(o) => o.severity(),
            _ => 0,
        }
    }

    fn name(&self) -> &'static str {
        match self {
            Self::Void => "void",
            Self::Null => "null",
            Self::True | Self::False => "bool",
            Self::Int(_) => "int",
            Self::Float(_) => "float",
            Self::Object(o) => o.name(),
        }
    }

    fn repr(&self) -> String {
        match self {
            Self::True => "true".to_string(),
            Self::False => "false".to_string(),
            Self::Int(i) => format!("{}", i),
            Self::Float(f) => format!("{}", f),
            Self::Object(o) => o.repr(),
            _ => self.name().to_string(),
        }
    }

    fn is_void(&self) -> bool {
        matches!(self, Value::Void)
    }

    fn is_true(&self) -> bool {
        match self {
            Self::True => true,
            Self::Int(i) => !i.is_zero(),
            Self::Float(f) => *f != 0.0,
            Self::Object(o) => o.is_true(),
            _ => false,
        }
    }

    fn to_i64(&self) -> Result<i64, String> {
        match self {
            Self::True => Ok(1),
            Self::Int(i) => Ok(i.to_i64().or(Some(0)).unwrap()),
            Self::Float(f) => Ok(*f as i64),
            Self::Object(o) => o.to_i64(),
            _ => Ok(0),
        }
    }

    fn to_f64(&self) -> Result<f64, String> {
        match self {
            Self::True => Ok(1.0),
            Self::Int(i) => Ok(i.to_f64().or(Some(0.0)).unwrap()),
            Self::Float(f) => Ok(*f),
            Self::Object(o) => o.to_f64(),
            _ => Ok(0.0),
        }
    }

    fn to_usize(&self) -> Result<usize, String> {
        match self {
            Self::True => Ok(1),
            Self::Int(i) => i
                .to_usize()
                .ok_or("Cannot convert BigInt to usize".to_string()),
            Self::Float(f) => Ok(*f as usize),
            Self::Object(o) => o.to_usize(),
            _ => Ok(0),
        }
    }

    fn to_string(&self) -> String {
        match self {
            Self::Void => "".to_string(),
            Self::Object(o) => o.to_string(),
            _ => self.repr(),
        }
    }

    fn to_bigint(&self) -> Result<BigInt, String> {
        match self {
            Self::True => Ok(BigInt::from(1)),
            Self::Int(i) => Ok(i.clone()),
            Self::Float(f) => Ok(BigInt::from(*f as i64)),
            Self::Object(o) => o.to_bigint(),
            _ => Ok(BigInt::from(0)),
        }
    }

    fn is_callable(&self, without_arguments: bool) -> bool {
        if let Self::Object(object) = self {
            object.is_callable(without_arguments)
        } else {
            false
        }
    }

    fn is_consuming(&self) -> bool {
        if let Self::Object(object) = self {
            object.is_consuming()
        } else {
            false
        }
    }

    fn is_nullable(&self) -> bool {
        if let Self::Object(object) = self {
            object.is_nullable()
        } else {
            false
        }
    }

    fn is_mutable(&self) -> bool {
        if let Self::Object(object) = self {
            object.is_mutable()
        } else {
            false
        }
    }

    fn is_hashable(&self) -> bool {
        match self {
            Self::Void => false,
            Self::Object(object) => object.is_hashable(),
            _ => true,
        }
    }

    fn call(
        &self,
        context: Option<&mut Context>,
        args: Vec<RefValue>,
        nargs: Option<Dict>,
    ) -> Result<Accept, Reject> {
        if let Value::Object(object) = self {
            object.call(context, args, nargs)
        } else {
            Err(format!("'{}' is not callable", self.name()).into())
        }
    }

    fn call_direct(
        &self,
        context: &mut Context,
        args: usize,
        nargs: Option<Dict>,
    ) -> Result<Accept, Reject> {
        if let Value::Object(object) = self {
            object.call_direct(context, args, nargs)
        } else {
            Err(format!("'{}' is not callable", self.name()).into())
        }
    }
}

impl Eq for Value {}

impl PartialOrd for Value {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (self, other) {
            (Self::Object(i), Self::Object(j)) => i.partial_cmp(j),
            (Self::Object(_), _) => Some(Ordering::Greater),
            (_, Self::Object(_)) => Some(Ordering::Less),

            (Self::Float(i), j) => i.partial_cmp(&j.to_f64().ok()?),
            (i, Self::Float(j)) => i.to_f64().ok()?.partial_cmp(j),

            (Self::Int(i), j) => i.partial_cmp(&j.to_bigint().ok()?),
            (i, j) => i.to_bigint().ok()?.partial_cmp(&j.to_bigint().ok()?),
        }
    }
}

impl Ord for Value {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.partial_cmp(other) {
            Some(ordering) => ordering,
            None => self.id().cmp(&other.id()),
        }
    }
}

impl From<bool> for RefValue {
    fn from(value: bool) -> Self {
        RefValue::from(if value { Value::True } else { Value::False })
    }
}

impl From<BigInt> for RefValue {
    fn from(int: BigInt) -> Self {
        RefValue::from(Value::Int(int))
    }
}

impl From<i64> for RefValue {
    fn from(int: i64) -> Self {
        RefValue::from(Value::Int(BigInt::from(int)))
    }
}

impl From<u64> for RefValue {
    fn from(int: u64) -> Self {
        RefValue::from(Value::Int(BigInt::from(int)))
    }
}

impl From<i32> for RefValue {
    fn from(int: i32) -> Self {
        RefValue::from(Value::Int(BigInt::from(int)))
    }
}

impl From<u32> for RefValue {
    fn from(int: u32) -> Self {
        RefValue::from(Value::Int(BigInt::from(int)))
    }
}

impl From<usize> for RefValue {
    fn from(addr: usize) -> Self {
        RefValue::from(Value::Int(BigInt::from(addr)))
    }
}

impl From<f64> for RefValue {
    fn from(float: f64) -> Self {
        RefValue::from(Value::Float(float))
    }
}

impl From<f32> for RefValue {
    fn from(float: f32) -> Self {
        RefValue::from(float as f64)
    }
}