hexicon-vm 0.1.0

The Hexicon virtual machine: runs the games Hexicon builds
Documentation
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! The Decimal built-in class: how the VM uses [`Big`] values.

use std::cmp::Ordering;

use crate::decimal::{Big, Kind};
use crate::decimal_math::{self, Hyperbolic, MathError, Trig};
use crate::error::{VmError, VmResult, code};
use crate::object::Object;
use crate::value::{NativeDesc, ObjId, Value};
use crate::vm::Vm;

/// The precision an integer gets when arithmetic mixes it with a
/// Decimal on the right.
const INT_PREC: usize = 32;

/// The name and calling interface of each method, by method number.
const METHODS: &[(&str, NativeDesc)] = &[
    ("", NativeDesc::fixed(0)),
    ("formatString", NativeDesc::optional(0, 6)),
    ("equalRound", NativeDesc::fixed(1)),
    ("getPrecision", NativeDesc::fixed(0)),
    ("setPrecision", NativeDesc::fixed(1)),
    ("getFraction", NativeDesc::fixed(0)),
    ("getWhole", NativeDesc::fixed(0)),
    ("roundToDecimal", NativeDesc::fixed(1)),
    ("getAbs", NativeDesc::fixed(0)),
    ("getCeil", NativeDesc::fixed(0)),
    ("getFloor", NativeDesc::fixed(0)),
    ("getScale", NativeDesc::fixed(0)),
    ("scaleTen", NativeDesc::fixed(1)),
    ("negate", NativeDesc::fixed(0)),
    ("copySignFrom", NativeDesc::fixed(1)),
    ("isNegative", NativeDesc::fixed(0)),
    ("divideBy", NativeDesc::fixed(1)),
    ("sine", NativeDesc::fixed(0)),
    ("cosine", NativeDesc::fixed(0)),
    ("tangent", NativeDesc::fixed(0)),
    ("degreesToRadians", NativeDesc::fixed(0)),
    ("radiansToDegrees", NativeDesc::fixed(0)),
    ("arcsine", NativeDesc::fixed(0)),
    ("arccosine", NativeDesc::fixed(0)),
    ("arctangent", NativeDesc::fixed(0)),
    ("sqrt", NativeDesc::fixed(0)),
    ("logE", NativeDesc::fixed(0)),
    ("expE", NativeDesc::fixed(0)),
    ("log10", NativeDesc::fixed(0)),
    ("raiseToPower", NativeDesc::fixed(1)),
    ("sinh", NativeDesc::fixed(0)),
    ("cosh", NativeDesc::fixed(0)),
    ("tanh", NativeDesc::fixed(0)),
    // `getPi` and `getE` are static methods.
    ("getPi", NativeDesc::fixed(1)),
    ("getE", NativeDesc::fixed(1)),
    ("numType", NativeDesc::fixed(0)),
];

/// Turn a failed calculation into the error a program sees.
fn math<T>(result: Result<T, MathError>) -> VmResult<T> {
    result.map_err(|error| {
        VmError::new(match error {
            MathError::OutOfRange => code::OUT_OF_RANGE,
            MathError::Overflow => code::NUM_OVERFLOW,
            MathError::DivideByZero => code::DIVIDE_BY_ZERO,
        })
    })
}

/// An arithmetic operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Arith {
    Add,
    Sub,
    Mul,
    Div,
}

impl Vm {
    /// Create a Decimal object.
    pub(crate) fn new_big(&mut self, value: Big) -> Value {
        Value::Obj(self.alloc_obj(Object::Decimal(Box::new(value))))
    }

    /// The number a value holds, if it is a Decimal object.
    pub(crate) fn as_big(&self, value: Value) -> Option<&Big> {
        match value {
            Value::Obj(id) => match self.objects.get(id)? {
                Object::Decimal(big) => Some(big),
                _ => None,
            },
            _ => None,
        }
    }

    /// The number a value holds, converting an integer.
    fn to_big(&self, value: Value) -> Option<Big> {
        match value {
            Value::Int(n) => Some(Big::from_int(n.into(), INT_PREC)),
            other => self.as_big(other).cloned(),
        }
    }

    /// Arithmetic with a Decimal as the left operand. The right one
    /// can be a Decimal or an integer.
    /// Note an operand of Decimal arithmetic or comparison. The
    /// reference VM turns an integer operand into a Decimal object
    /// before it uses it, and a program can tell that an object was
    /// created, so one is created here too.
    pub(crate) fn big_operand(&mut self, operand: Value) {
        if let Value::Int(n) = operand {
            self.new_big(Big::from_int(n.into(), INT_PREC));
        }
    }

    pub(crate) fn big_arith(&mut self, op: Arith, a: &Big, b: Value) -> VmResult<Value> {
        self.big_operand(b);
        let Some(b) = self.to_big(b) else {
            return Err(VmError::new(match op {
                Arith::Sub => code::BAD_TYPE_SUB,
                _ => code::BAD_TYPE_ADD,
            }));
        };
        let result = match op {
            Arith::Add => Big::add(a, &b),
            Arith::Sub => Big::sub(a, &b),
            Arith::Mul => Big::mul(a, &b),
            Arith::Div => match Big::div(a, &b) {
                Some(result) => result,
                None => return Err(VmError::new(code::DIVIDE_BY_ZERO)),
            },
        };
        Ok(self.new_big(result))
    }

    /// Integer arithmetic whose result does not fit in 32 bits: the
    /// result is a Decimal instead.
    pub(crate) fn promote_int_arith(&mut self, op: Arith, a: i32, b: i32) -> VmResult<Value> {
        // Sums and quotients get ten digits, products twenty.
        let prec = if op == Arith::Mul { 20 } else { 10 };
        let (a, b) = (Big::from_int(a.into(), prec), Big::from_int(b.into(), prec));
        let result = match op {
            Arith::Add => Big::add(&a, &b),
            Arith::Sub => Big::sub(&a, &b),
            Arith::Mul => Big::mul(&a, &b),
            Arith::Div => Big::div(&a, &b).ok_or_else(|| VmError::new(code::DIVIDE_BY_ZERO))?,
        };
        Ok(self.new_big(result))
    }

    /// The negation of a Decimal object.
    pub(crate) fn big_neg(&mut self, id: ObjId, a: &Big) -> Value {
        if a.kind == Kind::NaN || a.zero {
            return Value::Obj(id);
        }
        let mut result = a.clone();
        result.neg = !result.neg;
        self.new_big(result)
    }

    /// Whether a Decimal equals another value.
    pub(crate) fn big_equals(&self, a: &Big, other: Value) -> bool {
        self.to_big(other).is_some_and(|b| a.equals_exact(&b))
    }

    /// Compare a Decimal with another value.
    pub(crate) fn big_compare(&self, a: &Big, other: Value) -> VmResult<Ordering> {
        self.to_big(other)
            .and_then(|b| a.compare(&b))
            .ok_or_else(|| VmError::new(code::INVALID_COMPARISON))
    }

    /// Convert a Decimal to an integer, rounding. A value out of range
    /// is an error.
    pub(crate) fn big_to_int(a: &Big) -> VmResult<i32> {
        match a.to_i32() {
            (value, false) => Ok(value),
            (_, true) => Err(VmError::new(code::NUM_OVERFLOW)),
        }
    }

    /// Construct a Decimal from the arguments to `new`: a value and an
    /// optional precision.
    pub(crate) fn create_big(&mut self, argc: u32) -> VmResult<ObjId> {
        if !(1..=2).contains(&argc) {
            return Err(VmError::new(code::WRONG_NUM_OF_ARGS));
        }
        let source = self.arg(0);
        let text = self
            .as_str(source)
            .map(|t| String::from_utf8_lossy(&t).into_owned());
        let existing = self.as_big(source).cloned();
        if !matches!(source, Value::Int(_)) && text.is_none() && existing.is_none() {
            return Err(VmError::new(code::NUM_VAL_REQD));
        }
        let digits = if argc > 1 {
            match self.arg(1) {
                Value::Int(n) => n.max(0) as usize,
                _ => return Err(VmError::new(code::INT_VAL_REQD)),
            }
        } else if let Some(text) = &text {
            Big::precision_from_str(text)
        } else if let Some(existing) = &existing {
            existing.prec()
        } else {
            32
        };
        let value = match (source, text, existing) {
            (_, Some(text), _) => Big::parse(&text, digits),
            (_, _, Some(existing)) => existing.with_prec(digits, true),
            (Value::Int(n), _, _) => Big::from_int(n.into(), digits),
            _ => return Err(VmError::new(code::NUM_VAL_REQD)),
        };
        self.discard(argc as usize);
        Ok(self.alloc_obj(Object::Decimal(Box::new(value))))
    }

    /// Call a method of the Decimal class.
    pub(crate) fn big_method(
        &mut self,
        id: ObjId,
        index: u16,
        argc: Option<&mut u32>,
    ) -> VmResult<Option<Value>> {
        if index == 0 || index == 33 || index == 34 {
            return Ok(None);
        }
        let Some(&(_, desc)) = METHODS.get(index as usize) else {
            return Ok(None);
        };
        self.native_method(argc, desc, |vm, argc| vm.big_call(id, index, argc))
            .map(Some)
    }

    /// The static methods of the Decimal class: `getPi(digits)` and
    /// `getE(digits)`.
    pub(crate) fn big_static_method(
        &mut self,
        index: u16,
        argc: Option<&mut u32>,
    ) -> VmResult<Option<Value>> {
        if index != 33 && index != 34 {
            return Ok(None);
        }
        self.native_method(argc, NativeDesc::fixed(1), |vm, _| {
            let digits = vm.int_arg(vm.arg(0))?.max(0) as usize;
            let constant = if index == 33 {
                vm.big_cache.pi(digits)
            } else {
                vm.big_cache.e(digits)
            };
            let value = math(constant)?.with_prec(digits, true);
            Ok(vm.new_big(value))
        })
        .map(Some)
    }

    /// An optional integer argument: nil or a missing argument gives the
    /// default.
    fn int_or(&self, argc: u32, index: u32, default: i32) -> VmResult<i32> {
        if index >= argc {
            return Ok(default);
        }
        match self.arg(index as usize) {
            Value::Nil => Ok(default),
            Value::Int(n) => Ok(n),
            _ => Err(VmError::new(code::INT_VAL_REQD)),
        }
    }

    fn big_call(&mut self, id: ObjId, index: u16, argc: u32) -> VmResult<Value> {
        let self_value = Value::Obj(id);
        let Some(a) = self.as_big(self_value).cloned() else {
            return Err(VmError::new(code::BAD_TYPE_BIF));
        };
        // Most methods of something that is not a number return it as is.
        let nan = a.kind == Kind::NaN;
        // The other operand of a two-number method.
        let other = |vm: &Vm| {
            vm.to_big(vm.arg(0))
                .ok_or_else(|| VmError::new(code::BAD_TYPE_BIF))
        };
        Ok(match index {
            // formatString(maxDigits?, flags?, wholePlaces?, fracDigits?,
            // expDigits?, leadFiller?)
            1 => {
                let max_digits = self.int_or(argc, 0, -1)?;
                let flags = self.int_or(argc, 1, 0)? as u32;
                let whole_places = self.int_or(argc, 2, -1)?;
                let frac_digits = self.int_or(argc, 3, -1)?;
                let exp_digits = self.int_or(argc, 4, -1)?;
                let fill = if argc >= 6 && !self.arg(5).is_nil() {
                    let text = self.require_str(self.arg(5))?;
                    Some(String::from_utf8_lossy(&text).into_owned()).filter(|t| !t.is_empty())
                } else {
                    None
                };
                let text = a.format(
                    max_digits,
                    whole_places,
                    frac_digits,
                    exp_digits,
                    flags,
                    fill.as_deref(),
                );
                self.try_new_str(&text)?
            }
            // equalRound(num)
            2 => match self.to_big(self.arg(0)) {
                Some(b) => Value::logical(a.equals_rounded(&b)),
                None => Value::Nil,
            },
            // getPrecision()
            3 => Value::Int(a.prec() as i32),
            // setPrecision(digits)
            4 => {
                let digits = self.int_arg(self.arg(0))?.max(0) as usize;
                if nan {
                    self_value
                } else {
                    self.new_big(a.with_prec(digits, true))
                }
            }
            // getFraction() and getWhole()
            5 | 6 if nan => self_value,
            5 => {
                let mut result = a;
                result.keep_frac();
                self.new_big(result)
            }
            6 => {
                let mut result = a;
                result.keep_whole();
                self.new_big(result)
            }
            // roundToDecimal(places)
            7 => {
                let places = self.int_arg(self.arg(0))?;
                if nan {
                    return Ok(self_value);
                }
                let mut result = a;
                let keep = places.saturating_add(result.exp);
                if keep < 0 {
                    result = Big::zero(result.prec());
                    result.exp = 1;
                } else if (keep as usize) < result.prec() {
                    result.round_to(keep);
                    result.normalize();
                }
                self.new_big(result)
            }
            // getAbs()
            8 => {
                if !a.neg || nan {
                    self_value
                } else {
                    let mut result = a;
                    result.neg = false;
                    self.new_big(result)
                }
            }
            // getCeil() and getFloor()
            9 | 10 => {
                if nan {
                    return Ok(self_value);
                }
                // Rounding goes away from zero for a positive ceiling
                // and a negative floor.
                let away = a.neg == (index == 10);
                let frac_zero = a.is_frac_zero();
                let mut result = a;
                if result.exp <= 0 {
                    let neg = result.neg;
                    if !away || frac_zero {
                        result = Big::zero(result.prec());
                        result.exp = 1;
                    } else {
                        result = Big::from_int(1, result.prec());
                        result.neg = neg;
                    }
                } else {
                    let whole = result.exp as usize;
                    if whole < result.prec() {
                        result.digs[whole..].fill(0);
                    }
                    if !frac_zero && away {
                        result.increment_abs();
                    }
                }
                self.new_big(result)
            }
            // getScale()
            11 => {
                if nan {
                    Value::Nil
                } else {
                    Value::Int(a.exp)
                }
            }
            // scaleTen(n)
            12 => {
                let scale = self.int_arg(self.arg(0))?;
                if nan {
                    return Ok(self_value);
                }
                let mut result = a;
                result.exp = result.exp.saturating_add(scale);
                self.new_big(result)
            }
            // negate()
            13 => self.big_neg(id, &a),
            // copySignFrom(num)
            14 => {
                let b = other(self)?;
                if b.kind == Kind::NaN {
                    return Ok(self.arg(0));
                }
                if nan {
                    return Ok(self_value);
                }
                let mut result = a;
                result.neg = b.neg;
                result.normalize();
                self.new_big(result)
            }
            // isNegative()
            15 => {
                if nan {
                    Value::Nil
                } else {
                    Value::logical(a.neg)
                }
            }
            // divideBy(num): the whole quotient and the remainder.
            16 => {
                let b = other(self)?;
                let Some((quotient, remainder)) = Big::div_rem(&a, &b) else {
                    return Err(VmError::new(code::DIVIDE_BY_ZERO));
                };
                let quotient = self.new_big(quotient);
                let remainder = self.new_big(remainder);
                self.new_list(vec![quotient, remainder])
            }
            // sine(), cosine(), tangent()
            17..=19 => {
                if nan {
                    return Ok(self_value);
                }
                let function = match index {
                    17 => Trig::Sin,
                    18 => Trig::Cos,
                    _ => Trig::Tan,
                };
                let result = math(decimal_math::trig(function, &a, &mut self.big_cache))?;
                self.new_big(result)
            }
            // degreesToRadians() and radiansToDegrees()
            20 | 21 => {
                if nan {
                    return Ok(self_value);
                }
                let result = math(decimal_math::convert_angle(
                    &a,
                    index == 20,
                    &mut self.big_cache,
                ))?;
                self.new_big(result)
            }
            // arcsine() and arccosine()
            22 | 23 => {
                if nan {
                    return Ok(self_value);
                }
                let result = math(decimal_math::asin_acos_into(
                    a.prec(),
                    &a,
                    index == 23,
                    &mut self.big_cache,
                ))?;
                self.new_big(result)
            }
            // arctangent()
            24 => {
                if nan {
                    return Ok(self_value);
                }
                let result = math(decimal_math::atan(&a, &mut self.big_cache))?;
                self.new_big(result)
            }
            // sqrt()
            25 => {
                if nan {
                    return Ok(self_value);
                }
                let result = math(decimal_math::sqrt_into(a.prec(), &a))?;
                self.new_big(result)
            }
            // logE()
            26 => {
                if a.zero || a.neg {
                    return Err(VmError::new(code::OUT_OF_RANGE));
                }
                if nan {
                    return Ok(self_value);
                }
                let result = math(decimal_math::ln_into(a.prec(), &a, &mut self.big_cache))?;
                self.new_big(result)
            }
            // expE()
            27 => {
                if nan {
                    return Ok(self_value);
                }
                let result = math(decimal_math::exp_into(a.prec(), &a, &mut self.big_cache))?;
                self.new_big(result)
            }
            // log10()
            28 => {
                if nan {
                    return Ok(self_value);
                }
                let result = math(decimal_math::log10(&a, &mut self.big_cache))?;
                self.new_big(result)
            }
            // raiseToPower(num)
            29 => {
                let b = other(self)?;
                if b.kind == Kind::NaN {
                    return Ok(self.arg(0));
                }
                if nan {
                    return Ok(self_value);
                }
                let result = math(decimal_math::pow(&a, &b, &mut self.big_cache))?;
                self.new_big(result)
            }
            // sinh(), cosh(), tanh()
            30..=32 => {
                if nan {
                    return Ok(self_value);
                }
                let function = match index {
                    30 => Hyperbolic::Sinh,
                    31 => Hyperbolic::Cosh,
                    _ => Hyperbolic::Tanh,
                };
                let result = math(decimal_math::hyperbolic(function, &a, &mut self.big_cache))?;
                self.new_big(result)
            }
            // numType()
            35 => Value::Int(match a.kind {
                Kind::Num if a.zero && a.neg => 0x0001 | 0x0020,
                Kind::Num if a.zero => 0x0001 | 0x0010,
                Kind::Num => 0x0001,
                Kind::Inf if a.neg => 0x0008,
                Kind::Inf => 0x0004,
                Kind::NaN => 0x0002,
            }),
            _ => {
                return Err(VmError::unimplemented(format!(
                    "Decimal.{}",
                    METHODS[index as usize].0
                )));
            }
        })
    }
}