run-rs 0.2.9

Run a subset of Rust as an interpreted script
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
//! Binary and unary operator evaluation plus pattern binding for the
//! register machine. Split from `vm.rs`.

//! The register machine. Executes a compiled `Chunk` against one contiguous
//! register stack. Calls to user functions and closures push a frame record
//! and continue in the same instruction loop, so a script-level call costs no
//! native recursion, no allocation, and no register file copy beyond its
//! arguments. Anything else, methods and std or crate bridges, is delegated to
//! the existing dispatch on `Interp` with already evaluated values.

use std::cmp::Ordering;
use std::slice::from_ref;

use super::bytecode::{BinKind, PLit, PPat, UnKind};
use super::value::Value;
use anyhow::{Result, anyhow, bail};

// -- operators -------------------------------------------------------------

pub(super) fn apply_bin(op: BinKind, l: &Value, r: &Value) -> Result<Value> {
    use BinKind::*;
    Ok(match op {
        Add | Sub | Mul | Div | Rem => return arith(op, l, r),
        Eq => Value::Bool(l.eq_value(r)),
        Ne => Value::Bool(!l.eq_value(r)),
        Lt => Value::Bool(partial_compare(l, r)? == Some(Ordering::Less)),
        Le => Value::Bool(matches!(
            partial_compare(l, r)?,
            Some(Ordering::Less | Ordering::Equal)
        )),
        Gt => Value::Bool(partial_compare(l, r)? == Some(Ordering::Greater)),
        Ge => Value::Bool(matches!(
            partial_compare(l, r)?,
            Some(Ordering::Greater | Ordering::Equal)
        )),
        BitAnd => int_bin(l, r, |a, b| a & b)?,
        BitOr => int_bin(l, r, |a, b| a | b)?,
        BitXor => int_bin(l, r, |a, b| a ^ b)?,
        Shl => int_bin(l, r, |a, b| a << b)?,
        Shr => int_bin(l, r, |a, b| a >> b)?,
    })
}

/// `apply_bin` with an integer literal right operand, with a fast integer path
/// that skips building a `Value` for the literal.
pub(super) fn apply_bin_imm(op: BinKind, l: &Value, imm: i64) -> Result<Value> {
    use BinKind::*;
    if let Value::Int(a) = l {
        let a = *a;
        return Ok(match op {
            Add => Value::Int(
                a.checked_add(imm)
                    .ok_or_else(|| anyhow!("attempt to add with overflow"))?,
            ),
            Sub => Value::Int(
                a.checked_sub(imm)
                    .ok_or_else(|| anyhow!("attempt to subtract with overflow"))?,
            ),
            Mul => Value::Int(
                a.checked_mul(imm)
                    .ok_or_else(|| anyhow!("attempt to multiply with overflow"))?,
            ),
            Div => {
                if imm == 0 {
                    bail!("attempt to divide by zero");
                }
                Value::Int(
                    a.checked_div(imm)
                        .ok_or_else(|| anyhow!("attempt to divide with overflow"))?,
                )
            }
            Rem => {
                if imm == 0 {
                    bail!("attempt to calculate the remainder with a divisor of zero");
                }
                Value::Int(
                    a.checked_rem(imm).ok_or_else(|| {
                        anyhow!("attempt to calculate the remainder with overflow")
                    })?,
                )
            }
            Eq => Value::Bool(a == imm),
            Ne => Value::Bool(a != imm),
            Lt => Value::Bool(a < imm),
            Le => Value::Bool(a <= imm),
            Gt => Value::Bool(a > imm),
            Ge => Value::Bool(a >= imm),
            BitAnd => Value::Int(a & imm),
            BitOr => Value::Int(a | imm),
            BitXor => Value::Int(a ^ imm),
            Shl => Value::Int(a << imm),
            Shr => Value::Int(a >> imm),
        });
    }
    apply_bin(op, l, &Value::Int(imm))
}

/// Comparison result for the fused compare-and-branch ops.
pub(super) fn cmp_test(op: BinKind, l: &Value, r: &Value) -> Result<bool> {
    use BinKind::*;
    Ok(match op {
        Eq => l.eq_value(r),
        Ne => !l.eq_value(r),
        Lt => partial_compare(l, r)? == Some(Ordering::Less),
        Le => matches!(
            partial_compare(l, r)?,
            Some(Ordering::Less | Ordering::Equal)
        ),
        Gt => partial_compare(l, r)? == Some(Ordering::Greater),
        Ge => matches!(
            partial_compare(l, r)?,
            Some(Ordering::Greater | Ordering::Equal)
        ),
        _ => unreachable!("compare jump carries a non-comparison operator"),
    })
}

pub(super) fn cmp_test_imm(op: BinKind, l: &Value, imm: i64) -> Result<bool> {
    use BinKind::*;
    if let Value::Int(a) = l {
        let a = *a;
        return Ok(match op {
            Eq => a == imm,
            Ne => a != imm,
            Lt => a < imm,
            Le => a <= imm,
            Gt => a > imm,
            Ge => a >= imm,
            _ => unreachable!("compare jump carries a non-comparison operator"),
        });
    }
    cmp_test(op, l, &Value::Int(imm))
}

fn arith(op: BinKind, l: &Value, r: &Value) -> Result<Value> {
    use BinKind::*;
    if let (Add, Value::Str(a), Value::Str(b)) = (op, l, r) {
        let mut out = String::with_capacity(a.len() + b.len());
        out.push_str(a);
        out.push_str(b);
        return Ok(Value::str(out));
    }
    match (l, r) {
        (Value::Int(a), Value::Int(b)) => {
            let (a, b) = (*a, *b);
            let result = match op {
                Add => a
                    .checked_add(b)
                    .ok_or_else(|| anyhow!("attempt to add with overflow"))?,
                Sub => a
                    .checked_sub(b)
                    .ok_or_else(|| anyhow!("attempt to subtract with overflow"))?,
                Mul => a
                    .checked_mul(b)
                    .ok_or_else(|| anyhow!("attempt to multiply with overflow"))?,
                Div => {
                    if b == 0 {
                        bail!("attempt to divide by zero");
                    }
                    a.checked_div(b)
                        .ok_or_else(|| anyhow!("attempt to divide with overflow"))?
                }
                Rem => {
                    if b == 0 {
                        bail!("attempt to calculate the remainder with a divisor of zero");
                    }
                    a.checked_rem(b).ok_or_else(|| {
                        anyhow!("attempt to calculate the remainder with overflow")
                    })?
                }
                _ => unreachable!(),
            };
            Ok(Value::Int(result))
        }
        (a, b) => {
            let (x, y) = (to_float(a)?, to_float(b)?);
            Ok(Value::Float(match op {
                Add => x + y,
                Sub => x - y,
                Mul => x * y,
                Div => x / y,
                Rem => x % y,
                _ => unreachable!(),
            }))
        }
    }
}

fn int_bin(l: &Value, r: &Value, f: impl Fn(i64, i64) -> i64) -> Result<Value> {
    match (l, r) {
        (Value::Int(a), Value::Int(b)) => Ok(Value::Int(f(*a, *b))),
        (Value::Bool(a), Value::Bool(b)) => Ok(Value::Bool(f(*a as i64, *b as i64) != 0)),
        _ => bail!("bitwise operators need integers"),
    }
}

pub(super) fn compare_values(l: &Value, r: &Value) -> Result<Ordering> {
    partial_compare(l, r)?.ok_or_else(|| anyhow!("cannot order NaN"))
}

/// PartialOrd semantics: a NaN operand compares as `None`, which makes every
/// ordered comparison operator false, exactly like compiled Rust. Contexts
/// that need a total order, sorting for example, go through `compare_values`
/// and keep rejecting NaN.
fn partial_compare(l: &Value, r: &Value) -> Result<Option<Ordering>> {
    Ok(match (l, r) {
        (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
        (Value::Float(a), Value::Float(b)) => a.partial_cmp(b),
        (Value::Int(a), Value::Float(b)) => (*a as f64).partial_cmp(b),
        (Value::Float(a), Value::Int(b)) => a.partial_cmp(&(*b as f64)),
        (Value::Str(a), Value::Str(b)) => Some(a.as_str().cmp(b.as_str())),
        (Value::Char(a), Value::Char(b)) => Some(a.cmp(b)),
        (Value::Bool(a), Value::Bool(b)) => Some(a.cmp(b)),
        (a, b) => bail!("cannot compare {} and {}", a.type_name(), b.type_name()),
    })
}

fn to_float(v: &Value) -> Result<f64> {
    match v {
        Value::Int(i) => Ok(*i as f64),
        Value::Float(f) => Ok(*f),
        other => bail!("expected a number, got {}", other.type_name()),
    }
}

pub(super) fn apply_un(op: UnKind, v: &Value) -> Result<Value> {
    Ok(match (op, v) {
        (UnKind::Neg, Value::Int(i)) => Value::Int(-*i),
        (UnKind::Neg, Value::Float(f)) => Value::Float(-*f),
        (UnKind::Not, Value::Bool(b)) => Value::Bool(!*b),
        (UnKind::Not, Value::Int(i)) => Value::Int(!*i),
        (op, v) => bail!("cannot apply {:?} to {}", op, v.type_name()),
    })
}

// -- patterns --------------------------------------------------------------

/// True when a serde_json `Value` variant name matches the native value that a
/// parsed json holds. A json string is a `Str`, a number an `Int` or `Float`, an
/// array a `Vec`, an object a `Map`. `Null` is handled separately as a unit
/// variant because a json null is `Option::None` here.
fn json_variant_kind_matches(name: Option<&str>, val: &Value) -> bool {
    matches!(
        (name, val),
        (Some("String"), Value::Str(_))
            | (Some("Number"), Value::Int(_) | Value::Float(_))
            | (Some("Bool"), Value::Bool(_))
            | (Some("Array"), Value::Vec(_))
            | (Some("Object"), Value::Map(_))
    )
}

/// Match `pat` against `val`, calling `define` for each bound name. Returns
/// false without fully binding when the pattern does not match.
pub(super) fn try_bind(pat: &PPat, val: &Value, define: &mut dyn FnMut(&str, Value)) -> bool {
    match pat {
        PPat::Wild | PPat::Rest => true,
        PPat::Ident { name, sub } => {
            if let Some(subpattern) = sub
                && !try_bind(subpattern, val, define)
            {
                return false;
            }
            define(name, val.clone());
            true
        }
        PPat::Lit(literal) => literal_matches(literal, val),
        PPat::Tuple(patterns) => match val {
            Value::Tuple(items) => bind_seq(patterns, &items.borrow(), define),
            Value::Unit if patterns.is_empty() => true,
            _ => false,
        },
        PPat::TupleStruct { name, elems } => match val {
            Value::Enum { variant, data, .. } => {
                name.as_deref() == Some(&**variant) && bind_seq(elems, data, define)
            }
            Value::Struct(structure) => bind_seq(elems, &structure.values.borrow(), define),
            // A json string is a plain Str here, so a serde accessor like
            // as_str hands back the string itself as an already unwrapped Some,
            // the same model the Option methods on a Str follow. Matching a
            // bare value against Some(x) does not type check in real Rust, so
            // the script can only mean that pre-unwrapped Some. Unit is left
            // out because it is also this interpreter's filler for a missing
            // value.
            Value::Unit => false,
            other => {
                // A serde_json Value variant pattern, `Value::String(s)` and
                // friends, matched against the native value a parsed json holds.
                // The single field binds to the value itself, the same shape as
                // the pre-unwrapped Some rule below.
                if json_variant_kind_matches(name.as_deref(), other) {
                    bind_seq(elems, from_ref(other), define)
                } else {
                    name.as_deref() == Some("Some") && bind_seq(elems, from_ref(other), define)
                }
            }
        },
        PPat::Path { name } => match val {
            Value::Enum {
                enum_name, variant, ..
            } => {
                name.as_deref() == Some(&**variant)
                    // A json null is Option::None here, so `Value::Null` matches it.
                    || (name.as_deref() == Some("Null")
                        && &**enum_name == "Option"
                        && &**variant == "None")
            }
            _ => false,
        },
        PPat::Struct { name, fields } => {
            let Value::Struct(structure) = val else {
                return false;
            };
            if let Some(pattern_name) = name
                && pattern_name != super::resolver::bare(structure.name())
            {
                return false;
            }
            for (field, pattern) in fields {
                match structure.get(field) {
                    Some(value) if try_bind(pattern, &value, define) => {}
                    _ => return false,
                }
            }
            true
        }
        PPat::Or(patterns) => patterns
            .iter()
            .any(|pattern| try_bind(pattern, val, define)),
        PPat::Slice(patterns) => match val {
            Value::Vec(items) => bind_seq(patterns, &items.borrow(), define),
            _ => false,
        },
        PPat::Range { lo, hi, inclusive } => {
            range_matches(lo.as_ref(), hi.as_ref(), *inclusive, |l| {
                endpoint_cmp(l, val)
            })
        }
        PPat::Unsupported => false,
    }
}

/// Order a range endpoint against a value of the same type. `None` for a type
/// mismatch, which makes the range not match.
fn endpoint_cmp(literal: &PLit, value: &Value) -> Option<Ordering> {
    match (literal, value) {
        (PLit::Int(a), Value::Int(b)) => Some(a.cmp(b)),
        (PLit::Float(a), Value::Float(b)) => a.partial_cmp(b),
        (PLit::Char(a), Value::Char(b)) => Some(a.cmp(b)),
        _ => None,
    }
}

/// Shared range test, parameterized over the engine's endpoint comparison.
/// `cmp` orders an endpoint literal against the matched value.
pub(super) fn range_matches<L>(
    lo: Option<&L>,
    hi: Option<&L>,
    inclusive: bool,
    cmp: impl Fn(&L) -> Option<Ordering>,
) -> bool {
    if let Some(l) = lo {
        match cmp(l) {
            Some(Ordering::Less | Ordering::Equal) => {}
            _ => return false,
        }
    }
    if let Some(h) = hi {
        match cmp(h) {
            Some(Ordering::Greater) => {}
            Some(Ordering::Equal) if inclusive => {}
            _ => return false,
        }
    }
    true
}

fn bind_seq(patterns: &[PPat], vals: &[Value], define: &mut dyn FnMut(&str, Value)) -> bool {
    if patterns.iter().any(|pattern| matches!(pattern, PPat::Rest)) {
        let head_len = patterns
            .iter()
            .take_while(|pattern| !matches!(pattern, PPat::Rest))
            .count();
        for (pattern, value) in patterns.iter().take(head_len).zip(vals.iter()) {
            if !try_bind(pattern, value, define) {
                return false;
            }
        }
        for (pattern, value) in patterns.iter().skip(head_len + 1).zip(vals.iter().rev()) {
            if !try_bind(pattern, value, define) {
                return false;
            }
        }
        return true;
    }
    patterns.len() == vals.len()
        && patterns
            .iter()
            .zip(vals.iter())
            .all(|(pattern, value)| try_bind(pattern, value, define))
}

fn literal_matches(literal: &PLit, value: &Value) -> bool {
    match (literal, value) {
        (PLit::Int(left), Value::Int(right)) => left == right,
        (PLit::Float(left), Value::Float(right)) => left == right,
        (PLit::Bool(left), Value::Bool(right)) => left == right,
        (PLit::Str(left), Value::Str(right)) => left == right.as_str(),
        (PLit::Char(left), Value::Char(right)) => left == right,
        _ => false,
    }
}