hexicon-vm 0.2.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
//! The `sprintf` function: text built from a format string and values.

use crate::decimal::{self, Big};
use crate::error::{VmError, VmResult, code};
use crate::value::Value;
use crate::vm::Vm;

/// The options of one format item.
struct Options {
    /// What to show in front of a number that is not negative: `+`, a
    /// space, or nothing.
    sign: Option<char>,
    /// The character to put between groups of three digits.
    group: Option<char>,
    width: i32,
    precision: i32,
    left_align: bool,
    pad: char,
    /// The `#` flag: show a radix prefix, or always show a decimal point.
    pound: bool,
}

/// The format string, read a byte or a character at a time.
struct Reader<'a> {
    text: &'a [u8],
    at: usize,
}

impl Reader<'_> {
    fn more(&self) -> bool {
        self.at < self.text.len()
    }

    fn peek(&self) -> u8 {
        self.text.get(self.at).copied().unwrap_or(0)
    }

    fn next(&mut self) -> u8 {
        let byte = self.peek();
        if self.more() {
            self.at += 1;
        }
        byte
    }

    fn skip_if(&mut self, byte: u8) -> bool {
        let found = self.more() && self.peek() == byte;
        if found {
            self.at += 1;
        }
        found
    }

    /// Read a whole character.
    fn next_char(&mut self) -> char {
        let rest = &self.text[self.at..];
        let len = match rest.first() {
            None => return '\0',
            Some(&b) if b < 0x80 => 1,
            Some(&b) if b < 0xe0 => 2,
            Some(&b) if b < 0xf0 => 3,
            Some(_) => 4,
        }
        .min(rest.len());
        self.at += len;
        String::from_utf8_lossy(&rest[..len])
            .chars()
            .next()
            .unwrap_or('\0')
    }

    fn number(&mut self) -> i32 {
        let mut acc: i32 = 0;
        while self.peek().is_ascii_digit() {
            acc = acc
                .wrapping_mul(10)
                .wrapping_add(i32::from(self.next() - b'0'));
        }
        acc
    }
}

fn pad(out: &mut String, with: char, count: i32) {
    out.extend(std::iter::repeat_n(with, count.max(0) as usize));
}

/// Write text in a field of the width the options ask for.
fn padded(out: &mut String, text: &str, options: &Options) {
    let chars = text.chars().count() as i32;
    let fill = (options.width - chars).max(0);
    if !options.left_align {
        pad(out, options.pad, fill);
    }
    out.push_str(text);
    if options.left_align {
        pad(out, options.pad, fill);
    }
}

/// Write the digits of an integer, with sign, prefix, grouping, and
/// padding.
fn integer(out: &mut String, digits: &str, prefix: Option<&str>, options: &Options, caps: bool) {
    let text = if digits.is_empty() { "0" } else { digits };
    let negative = text.starts_with('-');
    let zero = text.starts_with('0');
    let len = text.len() as i32;
    let digit_count = len - i32::from(negative);
    let prefix = prefix.filter(|_| options.pound && !zero);

    let mut shown = len;
    if options.sign.is_some() && !negative {
        shown += 1;
    }
    if options.group.is_some() {
        shown += (digit_count - 1) / 3;
    }
    if let Some(prefix) = prefix {
        shown += prefix.len() as i32;
    }
    if digit_count < options.precision {
        shown += options.precision - digit_count;
    }
    let fill = (options.width - shown).max(0);

    if !options.left_align {
        pad(out, options.pad, fill);
    }
    match options.sign {
        Some(sign) if !negative => out.push(sign),
        _ => {}
    }
    if negative {
        out.push('-');
    }
    if let Some(prefix) = prefix {
        out.push_str(prefix);
    }
    pad(out, '0', options.precision - digit_count);
    let body = &text[usize::from(negative)..];
    for (index, c) in body.chars().enumerate() {
        let left = body.len() - index;
        if let Some(group) = options.group
            && index != 0
            && left % 3 == 0
        {
            out.push(group);
        }
        out.push(if caps {
            c.to_ascii_uppercase()
        } else {
            c.to_ascii_lowercase()
        });
    }
    if options.left_align {
        pad(out, options.pad, fill);
    }
}

// The reference VM has no entry for forty, so 40 is "xxxx". Programs can
// see that, so it stays.
const ROMAN: [(&str, i32); 12] = [
    ("m", 1000),
    ("cm", 900),
    ("d", 500),
    ("cd", 400),
    ("c", 100),
    ("xc", 90),
    ("l", 50),
    ("x", 10),
    ("ix", 9),
    ("v", 5),
    ("iv", 4),
    ("i", 1),
];

impl Vm {
    /// `sprintf(format, ...)`.
    pub(crate) fn sprintf(&mut self, argc: u32) -> VmResult<Value> {
        if argc < 1 {
            return Err(VmError::new(code::WRONG_NUM_OF_ARGS));
        }
        let format = self.require_str(self.arg(0))?.to_vec();
        let value_count = argc - 1;
        let mut reader = Reader {
            text: &format,
            at: 0,
        };
        let mut out: Vec<u8> = Vec::with_capacity(format.len() * 3 / 2);
        let mut next_arg: u32 = 1;
        while reader.more() {
            let byte = reader.next();
            if byte != b'%' {
                out.push(byte);
                continue;
            }
            let start = reader.at - 1;
            let mut options = Options {
                sign: None,
                group: None,
                width: -1,
                precision: -1,
                left_align: false,
                pad: ' ',
                pound: false,
            };
            let mut explicit_arg: i32 = -1;
            loop {
                match reader.peek() {
                    b'[' if reader.more() => {
                        reader.at += 1;
                        explicit_arg = reader.number();
                        reader.skip_if(b']');
                    }
                    b'+' => {
                        options.sign = Some('+');
                        reader.at += 1;
                    }
                    b' ' => {
                        options.sign = Some(' ');
                        reader.at += 1;
                    }
                    b',' => {
                        options.group = Some(',');
                        reader.at += 1;
                    }
                    b'-' => {
                        options.left_align = true;
                        reader.at += 1;
                    }
                    b'_' => {
                        reader.at += 1;
                        options.pad = reader.next_char();
                    }
                    b'#' => {
                        options.pound = true;
                        reader.at += 1;
                    }
                    _ => break,
                }
            }
            if reader.skip_if(b'0') && !options.left_align {
                options.pad = '0';
            }
            if reader.peek().is_ascii_digit() {
                options.width = reader.number();
            }
            if reader.skip_if(b'.') {
                options.precision = reader.number();
            }
            let spec = reader.next();
            let arg_index = if explicit_arg > 0 {
                explicit_arg as u32
            } else {
                next_arg
            };
            let value = if arg_index <= value_count {
                self.arg(arg_index as usize)
            } else {
                Value::Nil
            };
            let mut text = String::new();
            let mut used_arg = true;
            match spec {
                b'%' => {
                    text.push('%');
                    used_arg = false;
                }
                b'b' => self.format_int(&mut text, value, 2, None, &options, true, false)?,
                b'c' => match self.as_str(value) {
                    Some(string) => text.push(
                        String::from_utf8_lossy(&string)
                            .chars()
                            .next()
                            .unwrap_or('\0'),
                    ),
                    None => {
                        let code_point = self.cast_to_int(value)?;
                        if !(0..=65535).contains(&code_point) {
                            return Err(VmError::new(code::NUM_OVERFLOW));
                        }
                        text.push(char::from_u32(code_point as u32).unwrap_or('\u{fffd}'));
                    }
                },
                b'd' => self.format_int(&mut text, value, 10, None, &options, false, false)?,
                b'r' | b'R' => {
                    let caps = spec == b'R';
                    let mut n = self.cast_to_int(value)?;
                    if (1..=4999).contains(&n) {
                        for (numeral, worth) in ROMAN {
                            while worth <= n {
                                if caps {
                                    text.push_str(&numeral.to_ascii_uppercase());
                                } else {
                                    text.push_str(numeral);
                                }
                                n -= worth;
                            }
                        }
                    } else {
                        integer(&mut text, &n.to_string(), None, &options, false);
                    }
                }
                b'u' => self.format_int(&mut text, value, 10, None, &options, true, false)?,
                b'e' | b'E' | b'f' | b'g' | b'G' => {
                    self.format_float(&mut text, value, spec, &options)?;
                }
                b'o' => self.format_int(&mut text, value, 8, Some("0"), &options, true, false)?,
                b's' => {
                    let string = self.cast_to_text(value)?;
                    let string = String::from_utf8_lossy(&string);
                    let shown: String = if options.precision >= 0 {
                        string.chars().take(options.precision as usize).collect()
                    } else {
                        string.into_owned()
                    };
                    padded(&mut text, &shown, &options);
                }
                b'x' => self.format_int(&mut text, value, 16, Some("0x"), &options, true, false)?,
                b'X' => self.format_int(&mut text, value, 16, Some("0X"), &options, true, true)?,
                _ => {
                    // Not a format item after all: keep the text as it is.
                    out.extend_from_slice(&format[start..reader.at]);
                    used_arg = false;
                }
            }
            out.extend_from_slice(text.as_bytes());
            if used_arg && explicit_arg < 0 {
                next_arg += 1;
            }
        }
        self.try_new_string(out)
    }

    #[allow(clippy::too_many_arguments)]
    fn format_int(
        &mut self,
        out: &mut String,
        value: Value,
        radix: u32,
        prefix: Option<&str>,
        options: &Options,
        unsigned: bool,
        caps: bool,
    ) -> VmResult<()> {
        let digits = match self.cast_to_num(value)? {
            Value::Int(n) => crate::bif::int_to_radix(n, radix, !unsigned),
            // A Decimal is rounded to a whole number.
            number => match self.as_big(number) {
                Some(big) => big.to_radix_text(radix),
                None => return Err(VmError::new(code::NO_NUM_CONV)),
            },
        };
        integer(out, &digits, prefix, options, caps);
        Ok(())
    }

    fn format_float(
        &mut self,
        out: &mut String,
        value: Value,
        spec: u8,
        options: &Options,
    ) -> VmResult<()> {
        let mut frac_digits = if options.precision >= 0 {
            options.precision
        } else {
            6
        };
        let mut max_digits = -1;
        let mut flags = decimal::FORMAT_LEADING_ZERO;
        match options.sign {
            Some('+') => flags |= decimal::FORMAT_SIGN,
            Some(' ') => flags |= decimal::FORMAT_POS_SPACE,
            _ => {}
        }
        let general = spec == b'g' || spec == b'G';
        if options.pound {
            flags |= decimal::FORMAT_POINT;
            if general {
                flags |= decimal::FORMAT_TRAILING_ZEROS;
            }
        }
        if spec == b'E' || spec == b'G' {
            flags |= decimal::FORMAT_EXP_CAP;
        }
        if spec == b'e' || spec == b'E' {
            flags |= decimal::FORMAT_EXP | decimal::FORMAT_EXP_SIGN;
        }
        if general {
            // The precision counts significant digits, and the shorter
            // of the plain and scientific forms is used.
            flags |= decimal::FORMAT_COMPACT | decimal::FORMAT_EXP_SIGN | decimal::FORMAT_MAXSIG;
            max_digits = frac_digits;
            frac_digits = -1;
        }
        let number = match self.cast_to_num(value)? {
            Value::Int(n) => {
                // Zeros after the point are not significant in an
                // integer, so its precision is its number of digits.
                let big = Big::from_int(n.into(), 20);
                let digits = big.exp.max(1) as usize;
                big.with_prec(digits, false)
            }
            number => match self.as_big(number) {
                Some(big) => big.clone(),
                None => return Ok(()),
            },
        };
        let text = number.format(max_digits, -1, frac_digits, 3, flags, None);
        padded(out, &text, options);
        Ok(())
    }
}