From aedd3caa93540a7d2765ef2816af459c448a2e75 Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Mon, 16 Nov 2026 16:19:48 +0000 Subject: [PATCH 1/4] Add clazel-js-vm: the bytecode op list and `spec fn step` (item 7.4) Spec first (rule 3), no handlers and no compiler. The crate depends on vstd only. - ops.rs: the instruction set (register moves, constants, int32 and double arithmetic, comparisons, branches, property get/set with an inline-cache index, element get/set, calls and returns, closures, environment access, iteration, generator suspend and resume, throw), each op classed Core, Guarded or Handler, and the handler it calls. - spec.rs: NaN-boxed u64 values (encode and decode), ECMA-262 Number operations on IEEE 754 bit patterns (pinned commit 0248456c), the abstract machine (frames as windows of the value-stack region, pc, heap as a map, inline-cache tables), `fast_path`, `fast_step`, the uninterpreted `handler`, and `step`. Modelling choices are listed at the top of the file. - lemmas.rs: encode/decode round trips, op classes, core ops keep the machine well-formed, Number comparison properties. - docs/ERRATA.md: Number::multiply gives +0 for +0 * -5. Verus: 67 verified, 0 errors. Tier stays 0; nothing here is an implementation. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 7 + crates/clazel-js-vm/Cargo.toml | 27 + crates/clazel-js-vm/src/lemmas.rs | 431 ++++++++ crates/clazel-js-vm/src/lib.rs | 21 + crates/clazel-js-vm/src/ops.rs | 976 ++++++++++++++++++ crates/clazel-js-vm/src/spec.rs | 1597 +++++++++++++++++++++++++++++ docs/ERRATA.md | 22 + xtask/src/status.rs | 1 + 8 files changed, 3082 insertions(+) create mode 100644 crates/clazel-js-vm/Cargo.toml create mode 100644 crates/clazel-js-vm/src/lemmas.rs create mode 100644 crates/clazel-js-vm/src/lib.rs create mode 100644 crates/clazel-js-vm/src/ops.rs create mode 100644 crates/clazel-js-vm/src/spec.rs diff --git a/Cargo.lock b/Cargo.lock index 4819e7bfa..a0cddff91 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -367,6 +367,13 @@ version = "0.0.0" name = "clazel-js-regexp" version = "0.0.0" +[[package]] +name = "clazel-js-vm" +version = "0.0.0" +dependencies = [ + "vstd", +] + [[package]] name = "clazel-kernel" version = "0.0.0" diff --git a/crates/clazel-js-vm/Cargo.toml b/crates/clazel-js-vm/Cargo.toml new file mode 100644 index 000000000..a6539bf03 --- /dev/null +++ b/crates/clazel-js-vm/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "clazel-js-vm" +version = "0.0.0" +edition.workspace = true +license.workspace = true +publish.workspace = true +description = "The JavaScript engine's bytecode and its semantics for Clazel's Phase 7 browser (phase-7.md item 7.4): the instruction set, NaN-boxed values, and `spec fn step`." + +[dependencies] +vstd = "=0.0.0-2026-10-04-0306" + +# Verification tier (docs/VERIFICATION.md). `tier` is what is proven about the +# shipped code today: nothing, since this crate holds only the specification +# of item 7.4 (the handlers, compiler and interpreter loop come later, in 7.7 +# and 7.8). `target-tier` is 0 for the shipped code, as the Crates table of +# phase-7.md states; the spec itself is written to Tier 2 standards (Verus +# checks it and the lemmas in src/lemmas.rs), because the JIT's front-end +# proofs (jit.md J.10) refine `step`. +[package.metadata.clazel] +tier = 0 +target-tier = 0 + +[package.metadata.verus] +verify = true + +[lints] +workspace = true diff --git a/crates/clazel-js-vm/src/lemmas.rs b/crates/clazel-js-vm/src/lemmas.rs new file mode 100644 index 000000000..b0595686c --- /dev/null +++ b/crates/clazel-js-vm/src/lemmas.rs @@ -0,0 +1,431 @@ +//! Facts proven about the spec (docs/SPEC-STYLE.md): evidence that the +//! transcription is coherent, not part of what the implementation must meet. +//! +//! - [`lemma_decode_enc_int32`], [`lemma_decode_enc_ref`], +//! [`lemma_decode_enc_double`] and [`lemma_encode_decode`]: the NaN-boxing +//! round-trips, so a value has exactly one encoding and no two kinds of +//! value share a bit pattern. +//! - [`lemma_core_always_fast`] and [`lemma_handler_never_fast`]: the op +//! classes mean what [`crate::ops`] says, which is what lets the JIT map +//! handler ops to exits and core ops to straight-line code. +//! - [`lemma_core_step_wf`]: a core op keeps the machine well-formed, so the +//! region window, the callee and `pc` stay in bounds without a check. +//! - [`lemma_less_than_asymmetric`] and [`lemma_number_equal_key`]: two +//! properties the standard implies of Number comparison, which the integer +//! ordering key of `f64_key` must satisfy. +//! - [`lemma_examples`]: the value of a few conversions, evaluated. + + +#[allow(unused_imports)] +use super::spec::*; + +#[allow(unused_imports)] +use vstd::prelude::*; + +verus! { + +// --------------------------------------------------------------------- +// NaN-boxing +// --------------------------------------------------------------------- + +proof fn bv_int32(i: i32) + ensures + ((0xFFF9_0000_0000_0000u64 | (((i as u32) as u64) & 0xFFFF_FFFF)) >> 48) == 0xFFF9u64, + (((0xFFF9_0000_0000_0000u64 | (((i as u32) as u64) & 0xFFFF_FFFF)) >> 32) & 0xFFFF) == 0u64, + (((0xFFF9_0000_0000_0000u64 | (((i as u32) as u64) & 0xFFFF_FFFF)) & 0xFFFF_FFFF) as u32) as i32 == i, +{ + assert(((0xFFF9_0000_0000_0000u64 | (((i as u32) as u64) & 0xFFFF_FFFF)) >> 48) == 0xFFF9u64) by (bit_vector); + assert((((0xFFF9_0000_0000_0000u64 | (((i as u32) as u64) & 0xFFFF_FFFF)) >> 32) & 0xFFFF) == 0u64) by (bit_vector); + assert((((0xFFF9_0000_0000_0000u64 | (((i as u32) as u64) & 0xFFFF_FFFF)) & 0xFFFF_FFFF) as u32) as i32 == i) by (bit_vector); +} + +/// An int32 decodes back to itself. +pub proof fn lemma_decode_enc_int32(i: i32) + ensures + decode(enc_int32(i)) == Val::Int32(i), +{ + bv_int32(i); +} + +proof fn bv_ref(index: u32, generation: u16) + ensures + ((0xFFFB_0000_0000_0000u64 | ((generation as u64) << 32) | (index as u64)) >> 48) == 0xFFFBu64, + (((0xFFFB_0000_0000_0000u64 | ((generation as u64) << 32) | (index as u64)) & 0xFFFF_FFFF) as u32) == index, + (((((0xFFFB_0000_0000_0000u64 | ((generation as u64) << 32) | (index as u64)) >> 32) & 0xFFFF) as u16)) == generation, +{ + assert(((0xFFFB_0000_0000_0000u64 | ((generation as u64) << 32) | (index as u64)) >> 48) == 0xFFFBu64) by (bit_vector); + assert((((0xFFFB_0000_0000_0000u64 | ((generation as u64) << 32) | (index as u64)) & 0xFFFF_FFFF) as u32) == index) by (bit_vector); + assert((((((0xFFFB_0000_0000_0000u64 | ((generation as u64) << 32) | (index as u64)) >> 32) & 0xFFFF) as u16)) == generation) by (bit_vector); +} + +/// A heap reference decodes back to its index and generation. +pub proof fn lemma_decode_enc_ref(index: u32, generation: u16) + ensures + decode(enc_ref(index, generation)) == Val::Ref(index, generation), +{ + bv_ref(index, generation); +} + +proof fn bv_double(b: u64) + ensures + !(((b >> 52) & 0x7FF) == 0x7FF && (b & 0xF_FFFF_FFFF_FFFF) != 0) ==> (b >> 48) < 0xFFF9u64, +{ + assert(!(((b >> 52) & 0x7FF) == 0x7FF && (b & 0xF_FFFF_FFFF_FFFF) != 0) ==> (b >> 48) < 0xFFF9u64) by (bit_vector); +} + +proof fn bv_canon_nan() + ensures + (0x7FF8_0000_0000_0000u64 >> 48) < 0xFFF9u64, + ((0x7FF8_0000_0000_0000u64 >> 52) & 0x7FF) == 0x7FFu64, + (0x7FF8_0000_0000_0000u64 & 0xF_FFFF_FFFF_FFFFu64) != 0u64, +{ + assert((0x7FF8_0000_0000_0000u64 >> 48) < 0xFFF9u64) by (bit_vector); + assert(((0x7FF8_0000_0000_0000u64 >> 52) & 0x7FF) == 0x7FFu64) by (bit_vector); + assert((0x7FF8_0000_0000_0000u64 & 0xF_FFFF_FFFF_FFFFu64) != 0u64) by (bit_vector); +} + +/// The encoding of a double is a double value, and a double value decodes to +/// itself. +pub proof fn lemma_decode_enc_double(bits: u64) + ensures + is_double(enc_double(bits)), + decode(enc_double(bits)) == Val::Double(enc_double(bits)), +{ + bv_double(bits); + bv_canon_nan(); +} + +proof fn bv_special(v: u64, k: u64) + requires + (v >> 48) == 0xFFFAu64, + (v & 0xFFFF_FFFF_FFFF) == k, + ensures + v == 0xFFFA_0000_0000_0000u64 + k, +{ + assert(((v >> 48) == 0xFFFAu64 && (v & 0xFFFF_FFFF_FFFF) == k) ==> v == 0xFFFA_0000_0000_0000u64 + k) by (bit_vector); +} + +proof fn bv_int32_inv(v: u64) + requires + (v >> 48) == 0xFFF9u64, + ((v >> 32) & 0xFFFF) == 0u64, + ensures + (0xFFF9_0000_0000_0000u64 | ((((v & 0xFFFF_FFFF) as u32) as i32 as u32) as u64) & 0xFFFF_FFFF) == v, +{ + assert(((v >> 48) == 0xFFF9u64 && ((v >> 32) & 0xFFFF) == 0u64) + ==> (0xFFF9_0000_0000_0000u64 | ((((v & 0xFFFF_FFFF) as u32) as i32 as u32) as u64) & 0xFFFF_FFFF) == v) by (bit_vector); +} + +proof fn bv_ref_inv(v: u64) + requires + (v >> 48) == 0xFFFBu64, + ensures + (0xFFFB_0000_0000_0000u64 | ((((v >> 32) & 0xFFFF) as u16 as u64) << 32) | ((v & 0xFFFF_FFFF) as u32 as u64)) == v, +{ + assert((v >> 48) == 0xFFFBu64 + ==> (0xFFFB_0000_0000_0000u64 | ((((v >> 32) & 0xFFFF) as u16 as u64) << 32) | ((v & 0xFFFF_FFFF) as u32 as u64)) == v) by (bit_vector); +} + +proof fn bv_raw_inv(v: u64) + requires + (v >> 48) == 0xFFFCu64, + ensures + (0xFFFC_0000_0000_0000u64 | ((v & 0xFFFF_FFFF_FFFF) & 0xFFFF_FFFF_FFFF)) == v, +{ + assert((v >> 48) == 0xFFFCu64 + ==> (0xFFFC_0000_0000_0000u64 | ((v & 0xFFFF_FFFF_FFFF) & 0xFFFF_FFFF_FFFF)) == v) by (bit_vector); +} + +/// Every value re-encodes to the same bits: no two bit patterns decode to +/// one value. +pub proof fn lemma_encode_decode(v: u64) + requires + value_wf(v), + ensures + encode(decode(v)) == v, +{ + let tag = v >> 48; + if tag < 0xFFF9 { + assert(is_double(v)); + if is_nan(v) { + assert(v == CANON_NAN); + } + } else if tag == 0xFFF9 { + bv_int32_inv(v); + } else if tag == 0xFFFA { + let k = v & 0xFFFF_FFFF_FFFF; + bv_special(v, k); + } else if tag == 0xFFFB { + bv_ref_inv(v); + } else if tag == 0xFFFC { + bv_raw_inv(v); + } +} + +/// The five specials are values and decode as named. +pub proof fn lemma_specials() + ensures + decode(UNDEFINED) == Val::Undefined, + decode(NULL) == Val::Null, + decode(FALSE) == Val::Bool(false), + decode(TRUE) == Val::Bool(true), + decode(HOLE) == Val::Hole, + decode(CANON_NAN) == Val::Double(CANON_NAN), +{ + assert((UNDEFINED >> 48) == 0xFFFAu64) by (bit_vector); + assert((NULL >> 48) == 0xFFFAu64) by (bit_vector); + assert((FALSE >> 48) == 0xFFFAu64) by (bit_vector); + assert((TRUE >> 48) == 0xFFFAu64) by (bit_vector); + assert((HOLE >> 48) == 0xFFFAu64) by (bit_vector); + assert((UNDEFINED & 0xFFFF_FFFF_FFFF) == 0u64) by (bit_vector); + assert((NULL & 0xFFFF_FFFF_FFFF) == 1u64) by (bit_vector); + assert((FALSE & 0xFFFF_FFFF_FFFF) == 2u64) by (bit_vector); + assert((TRUE & 0xFFFF_FFFF_FFFF) == 3u64) by (bit_vector); + assert((HOLE & 0xFFFF_FFFF_FFFF) == 4u64) by (bit_vector); + lemma_decode_enc_double(CANON_NAN); + assert(enc_double(CANON_NAN) == CANON_NAN); +} + +// --------------------------------------------------------------------- +// Op classes +// --------------------------------------------------------------------- + +/// A core op takes its fast path in every state: it never calls a handler. +pub proof fn lemma_core_always_fast(s: State, op: Op) + requires + op_class(op) is Core, + ensures + fast_path(s, op), + step(s, op) == fast_step(s, op), +{ +} + +/// A handler op never takes a fast path: it always calls its handler. +pub proof fn lemma_handler_never_fast(s: State, op: Op) + requires + op_class(op) is Handler, + ensures + !fast_path(s, op), + step(s, op) == handler(op_handler(op), s, op), +{ +} + +// --------------------------------------------------------------------- +// Core ops keep the machine well-formed +// --------------------------------------------------------------------- + +/// Setting a register of the current frame keeps the machine well-formed +/// (the callee slot is below every register, so the frame's code is the same). +proof fn lemma_set_reg_wf(s: State, r: nat, v: u64) + requires + state_wf(s), + reg_ok(cur_code(s), r), + ensures + state_wf(set_reg(s, r, v)), + set_reg(s, r, v).region.len() == s.region.len(), + set_reg(s, r, v).fp == s.fp, + set_reg(s, r, v).pc == s.pc, +{ + let t = set_reg(s, r, v); + assert(frame_wf(s, s.fp)); + assert(reg_slot(s.fp, r) >= s.fp + hdr_slots()); + assert(t.region[(s.fp + hdr_callee()) as int] == s.region[(s.fp + hdr_callee()) as int]); + assert(t.heap == s.heap); + assert(frame_wf(t, t.fp)); + assert(cur_code(t) == cur_code(s)); +} + +/// `pc` moved to an op inside the function keeps the machine well-formed. +proof fn lemma_pc_wf(s: State, pc: nat) + requires + state_wf(s), + pc < cur_code(s).ops.len(), + ensures + state_wf(State { pc: pc, ..s }), +{ + let t = State { pc: pc, ..s }; + assert(cur_code(t) == cur_code(s)); +} + +/// A core op keeps the machine well-formed, and the region keeps its size: +/// no core op moves the frame, touches the heap or leaves the function. +pub proof fn lemma_core_step_wf(s: State, op: Op) + requires + state_wf(s), + op == fetch(s), + op_wf(cur_code(s), op), + op_class(op) is Core, + ensures + state_wf(step(s, op)), + step(s, op).region.len() == s.region.len(), + step(s, op).fp == s.fp, + step(s, op).heap == s.heap, +{ + let c = cur_code(s); + assert(code_wf(c)); + assert(op_wf(c, c.ops[s.pc as int])); + lemma_core_always_fast(s, op); + // Every op that can continue is not the last (`code_wf`). + if falls_through(op) { + assert(s.pc + 1 < c.ops.len()); + } + match op { + Op::Nop => { lemma_pc_wf(s, s.pc + 1); }, + Op::Move { dst, src } => { + lemma_set_reg_wf(s, dst, reg(s, src)); + lemma_pc_wf(set_reg(s, dst, reg(s, src)), s.pc + 1); + }, + Op::LoadConst { dst, k } => { + lemma_set_reg_wf(s, dst, c.consts[k as int]); + lemma_pc_wf(set_reg(s, dst, c.consts[k as int]), s.pc + 1); + }, + Op::LoadInt { dst, imm } => { + lemma_set_reg_wf(s, dst, enc_int32(imm)); + lemma_pc_wf(set_reg(s, dst, enc_int32(imm)), s.pc + 1); + }, + Op::LoadUndefined { dst } => { + lemma_set_reg_wf(s, dst, UNDEFINED); + lemma_pc_wf(set_reg(s, dst, UNDEFINED), s.pc + 1); + }, + Op::LoadNull { dst } => { + lemma_set_reg_wf(s, dst, NULL); + lemma_pc_wf(set_reg(s, dst, NULL), s.pc + 1); + }, + Op::LoadBool { dst, flag } => { + lemma_set_reg_wf(s, dst, enc_bool(flag)); + lemma_pc_wf(set_reg(s, dst, enc_bool(flag)), s.pc + 1); + }, + Op::LoadHole { dst } => { + lemma_set_reg_wf(s, dst, HOLE); + lemma_pc_wf(set_reg(s, dst, HOLE), s.pc + 1); + }, + Op::GetThis { dst } => { + let v = s.region[(s.fp + hdr_this()) as int]; + lemma_set_reg_wf(s, dst, v); + lemma_pc_wf(set_reg(s, dst, v), s.pc + 1); + }, + Op::GetCallee { dst } => { + let v = s.region[(s.fp + hdr_callee()) as int]; + lemma_set_reg_wf(s, dst, v); + lemma_pc_wf(set_reg(s, dst, v), s.pc + 1); + }, + Op::GetArgc { dst } => { + let v = enc_int32(argc_of(s.region[(s.fp + hdr_argc()) as int]) as i32); + lemma_set_reg_wf(s, dst, v); + lemma_pc_wf(set_reg(s, dst, v), s.pc + 1); + }, + Op::GetException { dst } => { + lemma_set_reg_wf(s, dst, s.exception); + lemma_pc_wf(set_reg(s, dst, s.exception), s.pc + 1); + }, + Op::Jump { target } => { lemma_pc_wf(s, target); }, + Op::JumpIfUndefined { src, target } => { + lemma_pc_wf(s, target); + lemma_pc_wf(s, s.pc + 1); + }, + Op::JumpIfNotUndefined { src, target } => { + lemma_pc_wf(s, target); + lemma_pc_wf(s, s.pc + 1); + }, + Op::JumpIfNullish { src, target } => { + lemma_pc_wf(s, target); + lemma_pc_wf(s, s.pc + 1); + }, + Op::JumpIfNotNullish { src, target } => { + lemma_pc_wf(s, target); + lemma_pc_wf(s, s.pc + 1); + }, + _ => {}, + } +} + +// --------------------------------------------------------------------- +// Numbers +// --------------------------------------------------------------------- + +/// For finite Numbers, `number_equal` is equality of the integer ordering +/// key: the justification for `f64_key` standing for `ℝ(x) = ℝ(y)`. +pub proof fn lemma_number_equal_key(x: u64, y: u64) + requires + is_finite(x), + is_finite(y), + ensures + number_equal(x, y) <==> f64_key(x) == f64_key(y), +{ + assert(!is_nan(x) && !is_nan(y)); + bv_key_facts(x); + bv_key_facts(y); + bv_same_key(x, y); +} + +/// The facts about sign-magnitude bits the key lemma uses. +proof fn bv_key_facts(x: u64) + ensures + (x >> 63) == 0u64 || (x >> 63) == 1u64, + (x & 0x7FFF_FFFF_FFFF_FFFFu64) == 0u64 <==> (x == 0u64 || x == 0x8000_0000_0000_0000u64), +{ + assert((x >> 63) == 0u64 || (x >> 63) == 1u64) by (bit_vector); + assert(((x & 0x7FFF_FFFF_FFFF_FFFFu64) == 0u64) <==> (x == 0u64 || x == 0x8000_0000_0000_0000u64)) by (bit_vector); +} + +/// Same sign and same magnitude is the same bits. +proof fn bv_same_key(x: u64, y: u64) + ensures + ((x >> 63) == (y >> 63) && (x & 0x7FFF_FFFF_FFFF_FFFFu64) == (y & 0x7FFF_FFFF_FFFF_FFFFu64)) ==> x == y, +{ + assert(((x >> 63) == (y >> 63) && (x & 0x7FFF_FFFF_FFFF_FFFFu64) == (y & 0x7FFF_FFFF_FFFF_FFFFu64)) ==> x == y) by (bit_vector); +} + +/// `x < y` and `y < x` are never both true (asymmetry of Number::lessThan). +pub proof fn lemma_less_than_asymmetric(x: u64, y: u64) + ensures + number_less_than(x, y) == Some(true) ==> number_less_than(y, x) == Some(false), +{ + if number_less_than(x, y) == Some(true) { + assert(!is_nan(x) && !is_nan(y)); + assert(x != y); + // Which of the infinity and zero steps fired. + if is_pos_inf(y) { + assert(!is_pos_inf(x)); + } else if is_neg_inf(x) { + assert(!is_neg_inf(y)); + } else { + assert(f64_key(x) < f64_key(y)); + } + } +} + +/// A few conversions, evaluated. +pub proof fn lemma_examples() + ensures + f64_of_int(0) == 0u64, + to_int32(0x41F0_0000_0000_0000u64) == 0i32, + to_uint32(0xBFF0_0000_0000_0000u64) == 4294967295u32, +{ + vstd::arithmetic::power2::lemma2_to64(); + vstd::arithmetic::power2::lemma2_to64_rest(); + reveal_with_fuel(ilog2, 40); + assert(f64_exp(0x41F0_0000_0000_0000u64) == 1055u64) by (bit_vector); + assert(f64_frac(0x41F0_0000_0000_0000u64) == 0u64) by (bit_vector); + assert(f64_sign(0x41F0_0000_0000_0000u64) == 0u64) by (bit_vector); + assert(f64_exp(0x41E0_0000_0000_0000u64) == 1054u64) by (bit_vector); + assert(f64_frac(0x41E0_0000_0000_0000u64) == 0u64) by (bit_vector); + assert(f64_sign(0x41E0_0000_0000_0000u64) == 0u64) by (bit_vector); + assert(f64_exp(0xBFF0_0000_0000_0000u64) == 1023u64) by (bit_vector); + assert(f64_frac(0xBFF0_0000_0000_0000u64) == 0u64) by (bit_vector); + assert(f64_sign(0xBFF0_0000_0000_0000u64) == 1u64) by (bit_vector); + assert(vstd::arithmetic::power2::pow2(52) / vstd::arithmetic::power2::pow2(52) == 1) by { + vstd::arithmetic::div_mod::lemma_div_by_self(vstd::arithmetic::power2::pow2(52) as int); + } + assert(f64_trunc_abs(0xBFF0_0000_0000_0000u64) == 1nat); + assert(f64_int32bit(0xBFF0_0000_0000_0000u64) == 4294967295nat); + assert(vstd::arithmetic::power2::pow2(52) / vstd::arithmetic::power2::pow2(20) == 4294967296) by { + vstd::arithmetic::div_mod::lemma_div_by_multiple(4294967296int, vstd::arithmetic::power2::pow2(20) as int); + } + assert(f64_trunc_abs(0x41F0_0000_0000_0000u64) == 4294967296nat); + assert(f64_int32bit(0x41F0_0000_0000_0000u64) == 0nat); + assert(to_int32(0x41F0_0000_0000_0000u64) == 0i32); + assert(to_uint32(0xBFF0_0000_0000_0000u64) == 4294967295u32); +} + +} // verus! diff --git a/crates/clazel-js-vm/src/lib.rs b/crates/clazel-js-vm/src/lib.rs new file mode 100644 index 000000000..30e5e1e71 --- /dev/null +++ b/crates/clazel-js-vm/src/lib.rs @@ -0,0 +1,21 @@ +//! The JavaScript engine's bytecode and its semantics (phase-7.md item 7.4). +//! +//! This crate holds, for now, only the specification: +//! +//! - [`ops`]: the instruction set (the op list), each op's class (core, +//! guarded or handler) and the handler an op calls out to; +//! - [`spec`]: NaN-boxed values, ECMA-262's Number operations on bit +//! patterns, the abstract machine, and `spec fn step`; +//! - [`lemmas`]: facts proven about the spec (the value encoding round-trips, +//! the op classes mean what they say, core ops keep the machine well-formed). +//! +//! The compiler (7.7), the handlers and the interpreter loop (7.8) come +//! later and refine `step`. The crate depends on no browser crate, as +//! phase-7.md's "The engine as a library" requires. +//! +//! Tier: see `[package.metadata.clazel]` in `Cargo.toml` and +//! `docs/VERIFICATION.md`. + +pub mod lemmas; +pub mod ops; +pub mod spec; diff --git a/crates/clazel-js-vm/src/ops.rs b/crates/clazel-js-vm/src/ops.rs new file mode 100644 index 000000000..31bdccb99 --- /dev/null +++ b/crates/clazel-js-vm/src/ops.rs @@ -0,0 +1,976 @@ +//! The instruction set (phase-7.md item 7.4): the op list, each op's class, +//! and the handler an op calls out to. +//! +//! This file is the "op list" of 7.4's commit. The semantics of every op is +//! in [`crate::spec`] (`step`); this file only says what the ops are, which +//! operands they carry, and how the JIT must treat each one. +//! +//! # Core, guarded and handler ops +//! +//! jit.md J.1 requires that "every op that can allocate, call out or throw is +//! a distinguished op, so it maps to an exit". Three classes ([`OpClass`]) +//! make that explicit: +//! +//! - **Core** ops never allocate, never call out and never throw, whatever +//! the machine state. `step` defines them in full. The JIT lowers each one +//! inline, with no exit. +//! - **Handler** ops always do at least one of those things. `step` defines +//! them as the uninterpreted `handler(h, s, op)` with `h = op_handler(op)`. +//! The JIT lowers each one to an exit that calls the same Rust handler the +//! interpreter calls (phase-7.md 7.8). +//! - **Guarded** ops have a fast path under a stated condition and call a +//! handler otherwise. `fast_path(s, op)` in [`crate::spec`] is the +//! condition, `step` is the fast result when it holds and the handler's +//! result when it does not. The JIT lowers the fast path inline, guards it +//! by that condition, and exits to the handler on the other branch +//! (jit.md J.10: "fast paths inline ... everything else is an exit"). +//! Every property get, call and `+` is guarded: whether it allocates or +//! throws depends on the operands. +//! +//! Operands are `nat`s so that this file needs no encoding decision: `dst`, +//! `src`, `a`, `b` and the other register names are register numbers +//! (register `r` is slot `fp + HDR_SLOTS + r`, arguments first, see +//! `spec::reg_slot`), `k` indexes the function's constant pool, `target` is an +//! op index in the same function, `ic` indexes the function's inline-cache +//! table, and `key` indexes the constant pool for a property name. The +//! binary encoding of ops belongs to the compiler (7.7). +//! +//! # What this list leaves out +//! +//! The op list covers the categories 7.4 names. Language features that 7.7 +//! compiles to *more handler ops* (classes, private names, `super`, `with`, +//! `eval`, tagged templates, regular-expression literals, destructuring +//! helpers, spread into array literals, optional-chaining helpers, `delete` +//! of references, `import()`) are added the same way: a new variant here, in +//! class [`OpClass::Handler`], with a new [`HandlerId`]. Nothing in the +//! semantics of the ops below changes when one is added, because a handler op +//! is opaque to `step`. + +#[allow(unused_imports)] +use vstd::prelude::*; + +verus! { + +/// How the JIT must treat an op (see the file header). +pub enum OpClass { + /// Never allocates, calls out or throws. Total and defined in full. + Core, + /// Fast path under `fast_path`, handler call otherwise. + Guarded, + /// Always a handler call. + Handler, +} + +/// The identity of a handler, one per handler function in phase-7.md 7.8. +/// A guarded op's slow path calls the same handler a handler op of the +/// same name would (for example `Add`'s slow path is [`HandlerId::Add`], which +/// does ToPrimitive, string concatenation and BigInt addition, ECMA-262 +/// §13.15.3). This is also the exit code the JIT passes (jit.md J.5's +/// `exit(code, operands)`). +pub enum HandlerId { + /// `+`: §13.15.3 ApplyStringOrNumericBinaryOperator. + Add, + /// `-`, §13.15.3. + Sub, + /// `*`, §13.15.3. + Mul, + /// `/`, §13.15.3. + Div, + /// `%`, §13.15.3. + Mod, + /// `**`, §13.6.1 and Number::exponentiate §6.1.6.1.3. + Exp, + /// Unary `-`, §13.5.5.1. + Neg, + /// `++`, §13.4. + Inc, + /// `--`, §13.4. + Dec, + /// `&`, §13.15.3. + BitAnd, + /// `|`, §13.15.3. + BitOr, + /// `^`, §13.15.3. + BitXor, + /// `<<`, §13.15.3. + Shl, + /// `>>`, §13.15.3. + Shr, + /// `>>>`, §13.15.3. + UShr, + /// `~`, §13.5.6.1. + BitNot, + /// `<`, §13.10.1 with IsLessThan §7.2.12. + Lt, + /// `<=`, §13.10.1. + Le, + /// `>`, §13.10.1. + Gt, + /// `>=`, §13.10.1. + Ge, + /// `===` and `!==`, IsStrictlyEqual §7.2.14 (string and BigInt contents). + StrictEq, + /// `==` and `!=`, IsLooselyEqual §7.2.13. + LooseEq, + /// `!`, ToBoolean §7.1.2 (strings, BigInts, IsHTMLDDA). + Not, + /// ToNumeric §7.1.3. + ToNumeric, + /// `JumpIfTrue` and `JumpIfFalse`: ToBoolean §7.1.2. + ToBoolean, + /// The termination check at a back-edge: ends the evaluation with an + /// error JS cannot catch (phase-7.md, "Limits and stopping"). + Terminate, + /// A TDZ read: throws a ReferenceError, §9.1.1.1.6 step 2. + ThrowHole, + /// Property get that missed its cache: Get §7.3.2, [[Get]] §10.1.8. + GetProp, + /// Property set that missed its cache: Set §7.3.4, [[Set]] §10.1.9. + SetProp, + /// Element get off the dense path. + GetElem, + /// Element set off the dense path. + SetElem, + /// A call that is not a plain call of an ordinary function: Call §7.3.13. + Call, + /// A return that is not a plain return, §14.10.1. + Return, + /// An environment access that missed. + EnvAccess, + /// `typeof`, §13.5.3.1. + TypeOf, + /// `instanceof`, §13.10.2 InstanceofOperator. + InstanceOf, + /// `in`, §13.10.1 and HasProperty §7.3.11. + HasProperty, + /// `delete obj[key]`, §13.5.1.2. + DeleteProp, + /// A global variable read, ResolveBinding §9.4.2 and GetValue §6.2.5.5. + GetGlobal, + /// A global variable write, PutValue §6.2.5.6. + SetGlobal, + /// Object literal, §13.2.5. + NewObject, + /// Array literal, §13.2.4. + NewArray, + /// NewDeclarativeEnvironment §9.1.2.2. + NewEnv, + /// Function object creation, OrdinaryFunctionCreate §10.2.3. + NewClosure, + /// `new`, EvaluateNew §13.3.5.1.1 and [[Construct]] §10.2.2. + New, + /// A call with a spread argument list, §13.3.8.1. + CallSpread, + /// GetIterator §7.4.4. + GetIterator, + /// IteratorNext, IteratorComplete and IteratorValue §7.4.6 to §7.4.8. + IterNext, + /// IteratorClose §7.4.11. + IterClose, + /// Generator suspend, GeneratorYield §27.5.3.6 and Yield §27.5.3.7. + Yield, + /// Async suspend, Await §27.7.5.3. + Await, + /// `throw`, §14.14.1. + Throw, + /// A throw the compiler knows the kind of, for example assignment to a + /// constant (a TypeError). + ThrowError, +} + +/// The error constructors a compiler-known throw can name. +pub enum ErrorKind { + /// `TypeError`. + TypeError, + /// `ReferenceError`. + ReferenceError, + /// `SyntaxError`. + SyntaxError, + /// `RangeError`. + RangeError, +} + +/// One instruction. Field names are the operand roles named in the file +/// header; `dst` is always written, `src`, `a`, `b`, `obj`, `idx`, `val`, +/// `cond`, `callee`, `this`, `env` are read. +pub enum Op { + // --------------------------------------------------------------- + // Core: never allocate, call out or throw. + // --------------------------------------------------------------- + /// Does nothing. + Nop, + /// `dst := src`. Register moves. + Move { + /// The register written. + dst: nat, + /// The register read. + src: nat, + }, + /// `dst := consts[k]`. A constant of the function's pool: a double, an + /// int32, a special, or a heap reference to an interned string, a + /// BigInt or a function template (the pool is a root, phase-7.md 7.6). + LoadConst { + /// The register written. + dst: nat, + /// The constant-pool index. + k: nat, + }, + /// `dst := imm` as an int32. + LoadInt { + /// The register written. + dst: nat, + /// The immediate int32. + imm: i32, + }, + /// `dst := undefined`. + LoadUndefined { + /// The register written. + dst: nat, + }, + /// `dst := null`. + LoadNull { + /// The register written. + dst: nat, + }, + /// `dst := true` or `false`. + LoadBool { + /// The register written. + dst: nat, + /// The boolean loaded. + flag: bool, + }, + /// `dst := hole`, the uninitialized-binding marker of the temporal dead + /// zone (§9.1.1.1.6) and of array holes. Never visible to JS. + LoadHole { + /// The register written. + dst: nat, + }, + /// `dst := this`, the frame header's `this` slot. + GetThis { + /// The register written. + dst: nat, + }, + /// `dst := callee`, the frame header's callee slot (`new.target`-free; + /// the function itself, for named function expressions). + GetCallee { + /// The register written. + dst: nat, + }, + /// `dst := argc` as an int32, from the frame header. + GetArgc { + /// The register written. + dst: nat, + }, + /// `dst := exception`: delivers the thrown value at a catch handler + /// (§14.15.2 Catch clause, step "Let thrownValue be ..."), after + /// unwinding (a handler's job) has stored it. + GetException { + /// The register written. + dst: nat, + }, + /// `pc := target`. Forward jumps and the loop-exit edge. + Jump { + /// The op index jumped to. + target: nat, + }, + /// `pc := target` if `src` is `undefined`, else the next op. + JumpIfUndefined { + /// The register read. + src: nat, + /// The op index jumped to. + target: nat, + }, + /// `pc := target` if `src` is not `undefined`. + JumpIfNotUndefined { + /// The register read. + src: nat, + /// The op index jumped to. + target: nat, + }, + /// `pc := target` if `src` is `undefined` or `null` (`??`, `?.`). + JumpIfNullish { + /// The register read. + src: nat, + /// The op index jumped to. + target: nat, + }, + /// `pc := target` if `src` is neither `undefined` nor `null`. + JumpIfNotNullish { + /// The register read. + src: nat, + /// The op index jumped to. + target: nat, + }, + + // --------------------------------------------------------------- + // Guarded: fast path when `fast_path` holds, else a handler. + // --------------------------------------------------------------- + /// `dst := a + b` on Numbers. Number::add, §6.1.6.1.7. + Add { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a - b` on Numbers. Number::subtract, §6.1.6.1.8. + Sub { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a * b` on Numbers. Number::multiply, §6.1.6.1.4. + Mul { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a / b` on Numbers. Number::divide, §6.1.6.1.5. + Div { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a % b` on Numbers. Number::remainder, §6.1.6.1.6. + Mod { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := -src` on a Number. Number::unaryMinus, §6.1.6.1.1. + Neg { + /// The register written. + dst: nat, + /// The register read. + src: nat, + }, + /// `dst := src + 1` on a Number (the numeric part of `++`, §13.4.2.1). + Inc { + /// The register written. + dst: nat, + /// The register read. + src: nat, + }, + /// `dst := src - 1` on a Number (the numeric part of `--`, §13.4.3.1). + Dec { + /// The register written. + dst: nat, + /// The register read. + src: nat, + }, + /// `dst := a & b` on Numbers. Number::bitwiseAND, §6.1.6.1.17. + BitAnd { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a | b` on Numbers. Number::bitwiseOR, §6.1.6.1.19. + BitOr { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a ^ b` on Numbers. Number::bitwiseXOR, §6.1.6.1.18. + BitXor { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a << b` on Numbers. Number::leftShift, §6.1.6.1.9. + Shl { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a >> b` on Numbers. Number::signedRightShift, §6.1.6.1.10. + Shr { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a >>> b` on Numbers. Number::unsignedRightShift, §6.1.6.1.11. + UShr { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := ~src` on a Number. Number::bitwiseNOT, §6.1.6.1.2. + BitNot { + /// The register written. + dst: nat, + /// The register read. + src: nat, + }, + /// `dst := a < b` on Numbers, §13.10.1 with Number::lessThan §6.1.6.1.12. + Lt { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a <= b` on Numbers, §13.10.1. + Le { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a > b` on Numbers, §13.10.1. + Gt { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a >= b` on Numbers, §13.10.1. + Ge { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a === b`, IsStrictlyEqual §7.2.14, §13.11.1. + StrictEq { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a !== b`, §13.11.1. + StrictNe { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := !src`, ToBoolean §7.1.2, §13.5.7.1. + Not { + /// The register written. + dst: nat, + /// The register read. + src: nat, + }, + /// `dst := ToNumeric(src)`, §7.1.3, on a Number (the identity). + ToNumeric { + /// The register written. + dst: nat, + /// The register read. + src: nat, + }, + /// `pc := target` if ToBoolean(`cond`), §14.6.2. + JumpIfTrue { + /// The register tested. + cond: nat, + /// The op index jumped to. + target: nat, + }, + /// `pc := target` if not ToBoolean(`cond`), §14.6.2. + JumpIfFalse { + /// The register tested. + cond: nat, + /// The op index jumped to. + target: nat, + }, + /// `pc := target`, a loop back-edge. The termination flag is checked + /// here (phase-7.md, "Limits and stopping"), and the interpreter and the + /// JIT count back-edges here for tiering (7.8, jit.md J.10); neither + /// count is observable, so neither is in the state. + Loop { + /// The op index jumped to. + target: nat, + }, + /// Throws a ReferenceError if `src` is the hole, else the next op: the + /// TDZ check (§9.1.1.1.6 GetBindingValue step 2, §9.1.1.1.5 + /// SetMutableBinding step 3). + ThrowIfHole { + /// The register read. + src: nat, + }, + /// `dst := obj.key`, with an inline cache: Get §7.3.2 specialised to an + /// own data property found by shape. + GetProp { + /// The register written. + dst: nat, + /// The register holding the object. + obj: nat, + /// The constant-pool index of the property name. + key: nat, + /// The inline-cache index. + ic: nat, + }, + /// `obj.key := val`, with an inline cache: Set §7.3.4 specialised to an + /// existing own writable data property found by shape. + SetProp { + /// The register holding the object. + obj: nat, + /// The constant-pool index of the property name. + key: nat, + /// The register holding the value stored. + val: nat, + /// The inline-cache index. + ic: nat, + }, + /// `dst := obj[idx]` on a dense element. + GetElem { + /// The register written. + dst: nat, + /// The register holding the object. + obj: nat, + /// The register (or slot index, for environment ops) of the element. + idx: nat, + }, + /// `obj[idx] := val` on a dense element that exists. + SetElem { + /// The register holding the object. + obj: nat, + /// The register (or slot index, for environment ops) of the element. + idx: nat, + /// The register holding the value stored. + val: nat, + }, + /// `dst := callee(args[0..argc])` with `this`. The caller lays the + /// arguments in `argc` consecutive registers from `args`. Call §7.3.13, + /// [[Call]] §10.2.1, EvaluateCall §13.3.6.2. + Call { + /// The register written. + dst: nat, + /// The register holding the function. + callee: nat, + /// The register holding `this`. + this: nat, + /// The first of the consecutive argument registers (or the array register). + args: nat, + /// The number of arguments. + argc: nat, + }, + /// `return src` from the current frame. §14.10.1, [[Call]] §10.2.1 + /// step 7 ("If result is a return completion, return result.[[Value]]"). + Return { + /// The register read. + src: nat, + }, + /// `dst := env.slots[idx]`: a captured variable, GetBindingValue + /// §9.1.1.1.6 on a declarative environment. + GetEnvSlot { + /// The register written. + dst: nat, + /// The register holding the environment. + env: nat, + /// The register (or slot index, for environment ops) of the element. + idx: nat, + }, + /// `env.slots[idx] := src`, SetMutableBinding §9.1.1.1.5. + SetEnvSlot { + /// The register holding the environment. + env: nat, + /// The register (or slot index, for environment ops) of the element. + idx: nat, + /// The register read. + src: nat, + }, + /// `dst := env.parent`: one hop of the scope chain, the outer environment + /// of §9.1.2.1 GetIdentifierReference step 3. + GetEnvParent { + /// The register written. + dst: nat, + /// The register holding the environment. + env: nat, + }, + /// `dst := callee.env`: the environment the running closure captured + /// (OrdinaryFunctionCreate §10.2.3, [[Environment]]). + GetCalleeEnv { + /// The register written. + dst: nat, + }, + + // --------------------------------------------------------------- + // Handler: always a handler call. + // --------------------------------------------------------------- + /// `dst := a ** b`, §13.6.1. + Exp { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a == b`, §13.11.1. + LooseEq { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a != b`, §13.11.1. + LooseNe { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := typeof src`, §13.5.3.1. + TypeOf { + /// The register written. + dst: nat, + /// The register read. + src: nat, + }, + /// `dst := a instanceof b`, §13.10.2. + InstanceOf { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := a in b`, §13.10.1. + HasProperty { + /// The register written. + dst: nat, + /// The left operand register. + a: nat, + /// The right operand register. + b: nat, + }, + /// `dst := delete obj[idx]`, §13.5.1.2. + DeleteProp { + /// The register written. + dst: nat, + /// The register holding the object. + obj: nat, + /// The register (or slot index, for environment ops) of the element. + idx: nat, + }, + /// `dst := global.key`, with an inline cache (the handler may install it). + GetGlobal { + /// The register written. + dst: nat, + /// The constant-pool index of the property name. + key: nat, + /// The inline-cache index. + ic: nat, + }, + /// `global.key := src`. + SetGlobal { + /// The constant-pool index of the property name. + key: nat, + /// The register read. + src: nat, + /// The inline-cache index. + ic: nat, + }, + /// `dst := {}`. + NewObject { + /// The register written. + dst: nat, + }, + /// `dst := []` with room for `len` elements. + NewArray { + /// The register written. + dst: nat, + /// The element capacity. + len: nat, + }, + /// `dst := new environment` with `size` slots (all holes) and `parent`. + NewEnv { + /// The register written. + dst: nat, + /// The register holding the parent environment. + parent: nat, + /// The number of slots. + size: nat, + }, + /// `dst := closure of function template `func` over `env``. + NewClosure { + /// The register written. + dst: nat, + /// The index of the function template. + func: nat, + /// The register holding the environment. + env: nat, + }, + /// `dst := new callee(args[0..argc])`. + New { + /// The register written. + dst: nat, + /// The register holding the function. + callee: nat, + /// The first of the consecutive argument registers (or the array register). + args: nat, + /// The number of arguments. + argc: nat, + }, + /// `dst := callee.apply(this, array in args)` for `f(...xs)`. + CallSpread { + /// The register written. + dst: nat, + /// The register holding the function. + callee: nat, + /// The register holding `this`. + this: nat, + /// The first of the consecutive argument registers (or the array register). + args: nat, + }, + /// `dst := GetIterator(src)`. + GetIterator { + /// The register written. + dst: nat, + /// The register read. + src: nat, + }, + /// `value := iterator.next()`; `done := whether it was done`. + IterNext { + /// The register receiving the value. + value: nat, + /// The register receiving the done flag. + done: nat, + /// The register holding the iterator record. + iter: nat, + }, + /// `IteratorClose(iter)`. + IterClose { + /// The register holding the iterator record. + iter: nat, + }, + /// Suspends the running generator, giving `src` to its consumer. On + /// resume, `value` receives the sent value and `mode` an int32: 0 next, + /// 1 throw, 2 return (the compiler follows with `Jump`s on it). + Yield { + /// The register read. + src: nat, + /// The register receiving the value. + value: nat, + /// The register receiving the resume mode. + mode: nat, + }, + /// As `Yield`, for `await`. + Await { + /// The register read. + src: nat, + /// The register receiving the value. + value: nat, + /// The register receiving the resume mode. + mode: nat, + }, + /// `throw src`. + Throw { + /// The register read. + src: nat, + }, + /// Throws a new error of `kind` with message `consts[msg]`. + ThrowError { + /// The error constructor. + kind: ErrorKind, + /// The constant-pool index of the message. + msg: nat, + }, +} + +/// The class of an op (see the file header). +pub open spec fn op_class(op: Op) -> OpClass { + match op { + Op::Nop + | Op::Move { .. } + | Op::LoadConst { .. } + | Op::LoadInt { .. } + | Op::LoadUndefined { .. } + | Op::LoadNull { .. } + | Op::LoadBool { .. } + | Op::LoadHole { .. } + | Op::GetThis { .. } + | Op::GetCallee { .. } + | Op::GetArgc { .. } + | Op::GetException { .. } + | Op::Jump { .. } + | Op::JumpIfUndefined { .. } + | Op::JumpIfNotUndefined { .. } + | Op::JumpIfNullish { .. } + | Op::JumpIfNotNullish { .. } => OpClass::Core, + Op::Add { .. } + | Op::Sub { .. } + | Op::Mul { .. } + | Op::Div { .. } + | Op::Mod { .. } + | Op::Neg { .. } + | Op::Inc { .. } + | Op::Dec { .. } + | Op::BitAnd { .. } + | Op::BitOr { .. } + | Op::BitXor { .. } + | Op::Shl { .. } + | Op::Shr { .. } + | Op::UShr { .. } + | Op::BitNot { .. } + | Op::Lt { .. } + | Op::Le { .. } + | Op::Gt { .. } + | Op::Ge { .. } + | Op::StrictEq { .. } + | Op::StrictNe { .. } + | Op::Not { .. } + | Op::ToNumeric { .. } + | Op::JumpIfTrue { .. } + | Op::JumpIfFalse { .. } + | Op::Loop { .. } + | Op::ThrowIfHole { .. } + | Op::GetProp { .. } + | Op::SetProp { .. } + | Op::GetElem { .. } + | Op::SetElem { .. } + | Op::Call { .. } + | Op::Return { .. } + | Op::GetEnvSlot { .. } + | Op::SetEnvSlot { .. } + | Op::GetEnvParent { .. } + | Op::GetCalleeEnv { .. } => OpClass::Guarded, + Op::Exp { .. } + | Op::LooseEq { .. } + | Op::LooseNe { .. } + | Op::TypeOf { .. } + | Op::InstanceOf { .. } + | Op::HasProperty { .. } + | Op::DeleteProp { .. } + | Op::GetGlobal { .. } + | Op::SetGlobal { .. } + | Op::NewObject { .. } + | Op::NewArray { .. } + | Op::NewEnv { .. } + | Op::NewClosure { .. } + | Op::New { .. } + | Op::CallSpread { .. } + | Op::GetIterator { .. } + | Op::IterNext { .. } + | Op::IterClose { .. } + | Op::Yield { .. } + | Op::Await { .. } + | Op::Throw { .. } + | Op::ThrowError { .. } => OpClass::Handler, + } +} + +/// The handler an op calls when it is a handler op, or when it is a guarded +/// op whose guard failed. For a core op the value is unused (`Nop`'s +/// arbitrary choice is `HandlerId::Throw`). +pub open spec fn op_handler(op: Op) -> HandlerId { + match op { + Op::Add { .. } => HandlerId::Add, + Op::Sub { .. } => HandlerId::Sub, + Op::Mul { .. } => HandlerId::Mul, + Op::Div { .. } => HandlerId::Div, + Op::Mod { .. } => HandlerId::Mod, + Op::Exp { .. } => HandlerId::Exp, + Op::Neg { .. } => HandlerId::Neg, + Op::Inc { .. } => HandlerId::Inc, + Op::Dec { .. } => HandlerId::Dec, + Op::BitAnd { .. } => HandlerId::BitAnd, + Op::BitOr { .. } => HandlerId::BitOr, + Op::BitXor { .. } => HandlerId::BitXor, + Op::Shl { .. } => HandlerId::Shl, + Op::Shr { .. } => HandlerId::Shr, + Op::UShr { .. } => HandlerId::UShr, + Op::BitNot { .. } => HandlerId::BitNot, + Op::Lt { .. } => HandlerId::Lt, + Op::Le { .. } => HandlerId::Le, + Op::Gt { .. } => HandlerId::Gt, + Op::Ge { .. } => HandlerId::Ge, + Op::StrictEq { .. } | Op::StrictNe { .. } => HandlerId::StrictEq, + Op::LooseEq { .. } | Op::LooseNe { .. } => HandlerId::LooseEq, + Op::Not { .. } => HandlerId::Not, + Op::ToNumeric { .. } => HandlerId::ToNumeric, + Op::JumpIfTrue { .. } | Op::JumpIfFalse { .. } => HandlerId::ToBoolean, + Op::Loop { .. } => HandlerId::Terminate, + Op::ThrowIfHole { .. } => HandlerId::ThrowHole, + Op::GetProp { .. } => HandlerId::GetProp, + Op::SetProp { .. } => HandlerId::SetProp, + Op::GetElem { .. } => HandlerId::GetElem, + Op::SetElem { .. } => HandlerId::SetElem, + Op::Call { .. } => HandlerId::Call, + Op::Return { .. } => HandlerId::Return, + Op::GetEnvSlot { .. } + | Op::SetEnvSlot { .. } + | Op::GetEnvParent { .. } + | Op::GetCalleeEnv { .. } => HandlerId::EnvAccess, + Op::TypeOf { .. } => HandlerId::TypeOf, + Op::InstanceOf { .. } => HandlerId::InstanceOf, + Op::HasProperty { .. } => HandlerId::HasProperty, + Op::DeleteProp { .. } => HandlerId::DeleteProp, + Op::GetGlobal { .. } => HandlerId::GetGlobal, + Op::SetGlobal { .. } => HandlerId::SetGlobal, + Op::NewObject { .. } => HandlerId::NewObject, + Op::NewArray { .. } => HandlerId::NewArray, + Op::NewEnv { .. } => HandlerId::NewEnv, + Op::NewClosure { .. } => HandlerId::NewClosure, + Op::New { .. } => HandlerId::New, + Op::CallSpread { .. } => HandlerId::CallSpread, + Op::GetIterator { .. } => HandlerId::GetIterator, + Op::IterNext { .. } => HandlerId::IterNext, + Op::IterClose { .. } => HandlerId::IterClose, + Op::Yield { .. } => HandlerId::Yield, + Op::Await { .. } => HandlerId::Await, + Op::Throw { .. } | Op::Nop => HandlerId::Throw, + Op::ThrowError { .. } => HandlerId::ThrowError, + // Core ops never call a handler; the value is not used. + _ => HandlerId::Throw, + } +} + +/// The register an op writes its result to when it is a call, which is where +/// a `Return` delivers its value. Only calls have one. +pub open spec fn call_dst(op: Op) -> Option { + match op { + Op::Call { dst, .. } => Some(dst), + Op::CallSpread { dst, .. } => Some(dst), + _ => None, + } +} + +} // verus! diff --git a/crates/clazel-js-vm/src/spec.rs b/crates/clazel-js-vm/src/spec.rs new file mode 100644 index 000000000..33fe327f6 --- /dev/null +++ b/crates/clazel-js-vm/src/spec.rs @@ -0,0 +1,1597 @@ +//! The bytecode's semantics (phase-7.md item 7.4): NaN-boxed values, the +//! abstract machine, and `spec fn step`. +//! +//! Sources: +//! - ECMA-262, 17th edition (ES2026), `tc39/ecma262` commit +//! `0248456c758431e4bb8e5d26333ff1865123c9cd` (see +//! `crates/clazel-js-lexer/SPEC-PIN.md`). Section numbers below are the +//! numbers of that commit's `spec.html`, which does not print them: they +//! are computed from the nesting of its `emu-clause` elements, and each +//! cited clause is named by its anchor (`#sec-...`) in the doc comment of +//! the function that implements it. +//! - phase-7.md "Shapes fixed here for the JIT" and 7.4; jit.md J.1, J.5, J.10. +//! +//! Nothing here runs. This file defines what the interpreter's handlers and +//! the JIT's lowerings must refine; the part a reviewer reads is this file, +//! and [`crate::ops`] for the op list. +//! +//! # Structure +//! +//! 1. Values: the NaN-boxing (`enc_*`, `decode`). +//! 2. Numbers: ECMA-262's Number operations on IEEE 754 bit patterns. +//! 3. The machine: frames in the value-stack region, the heap, the code. +//! 4. `fast_path`, `fast_step`, `handler` and `step`. +//! +//! # Modelling choices +//! +//! Each is a deliberate difference in form from the standard or from phase-7.md, +//! with the argument that the meaning is unchanged, or the stated extension. +//! +//! - **A Number is its IEEE 754 binary64 bit pattern, a `u64`.** Verus has no +//! floating-point arithmetic in specs, and a bit pattern is what the +//! region holds. Everything the standard says about a Number +//! (`NaN`, `+0`, `-0`, `+∞`, finite) is a predicate on the bits +//! (`is_nan`, `is_pos_zero`, ...). `x is y` in the standard, for non-NaN +//! Numbers, is bit equality. `ℝ(x) < ℝ(y)` for finite Numbers is +//! `f64_key(x) < f64_key(y)`, which is correct because IEEE 754's +//! sign-magnitude layout orders finite and infinite values as integers, +//! with `-0` and `+0` both mapping to key 0 (`lemma_number_equal_key`, `lemma_less_than_asymmetric`). +//! - **The rounding of an exact real result is uninterpreted.** +//! `𝔽(ℝ(x) + ℝ(y))` (and the same for `×`, `/`, and the remainder's +//! `r`) is `f64_add_finite`, `f64_mul_finite`, `f64_div_finite`, +//! `f64_rem_finite`: `spec fn`s without bodies. The standard defines the +//! function ("the Number value for", §6.1.6.1, roundTiesToEven) but it is +//! a statement about real numbers, which Verus cannot compute here. The +//! special cases around it (`NaN`, infinities, zeros: steps 1 to 7 of each +//! Number method) *are* transcribed. The assumption made, and listed for +//! VERIFICATION.md's TCB when the JIT's back end uses it, is that the +//! target's `addsd`/`mulsd`/`divsd` (x86-64) and `fadd`/`fmul`/`fdiv` +//! (A64) in the default rounding mode agree with those four functions on +//! finite arguments, and `f64_rem_finite` is C's `fmod` +//! ("the result of a floating-point remainder ... is analogous to ... +//! fmod", the standard's note on Number::remainder). +//! - **int32 and double encodings of one Number are both Numbers.** The +//! standard has one Number type; the machine has two encodings, `Int32(i)` +//! and `Double(bits)`, and `num_bits` maps each to the double that +//! represents the same Number. An arithmetic op chooses the encoding of +//! its result by a fixed rule (`arith_add`, ...: int32 when both operands +//! are int32 and the exact result is an int32 and not `-0`, a double +//! otherwise). The rule is pinned here, not left free, because the JIT's +//! proof refines `step` exactly, and a lowering that narrowed a double to +//! an int32 would be a different result. Whether to narrow is then an +//! explicit, provable change to this file. +//! - **Fast paths are conditions on the whole state, not on types.** A +//! guarded op's `fast_path` is what the JIT tests inline: operand tags, +//! shape ids, bounds. `step` is `fast_step` when it holds and `handler` +//! when it does not. Nothing else is interpreted: whether the handler +//! allocates, throws or calls JS is the handler's business. +//! - **A handler is one uninterpreted function of the whole state.** +//! `handler(h, s, op)` returns the next state, including `pc`. It has no +//! body and no axioms, so nothing is proven about it here. Test262 is the +//! evidence for each handler (phase-7.md 7.4, 7.8). The properties the JIT +//! needs of handlers (they touch only the region window of the current +//! call chain, they preserve heap well-formedness) will be stated as the +//! handlers' contracts in 7.8, not assumed here. +//! - **Exceptions are handler results.** Throwing and unwinding set +//! `exception`, restore `fp`, and move `pc` to a catch handler (or leave +//! the frame), all inside `handler`. The exception table is a handler +//! input, so it is not in this state's `Code`. +//! - **The heap is an abstract map** from arena index (`u32`) to `Cell`, +//! where a cell has the `u16` generation the arena would hold. A reference +//! is *live* (`live_cell`) when the index is in the map and the +//! generations agree. A stale reference is therefore never an alias: it is +//! not live, so no fast path accepts it and the handler reports the +//! defined error (phase-7.md 7.0(f)). Free-list order, string contents, +//! BigInt limbs and so on are the heap crate's (7.5); here a cell only +//! says what a fast path reads: its shape id, its slot values, its dense +//! elements, and for functions and environments their code and parent. +//! - **Shapes are ids, and a shape determines slot count only through the +//! inline cache.** An inline-cache entry is `(shape, slot)`. A hit +//! re-checks `slot < slots.len()` so `step` is total; the JIT may drop that +//! test if it proves the invariant `ic_wf` ("any object with the cached +//! shape has the slot"), which the heap maintains (7.5). Shape id `0` is +//! never an object's shape in a cache, so an empty entry never hits. +//! Inline caches here are own-property caches. A prototype-chain hit (a +//! method on a class) misses and goes to the handler, until the cache +//! gains a holder and a validity cell. +//! - **The return address is a RAW value** (`TAG_RAW`): bits 24 to 47 hold +//! the caller's frame base and bits 0 to 23 the caller's `pc`, so that +//! every slot of a frame, including the header, is a well-formed +//! `u64`-boxed value and the collector scans a frame without a layout +//! table (phase-7.md 7.0(f): the value stack is a root). This limits a +//! region to `2^24 - 1` slots and a function to `2^24 - 1` ops; the +//! fast paths that build or read an address check the limit, so a larger +//! frame goes to a handler (which can fall back to an out-of-line address). +//! The return address does not name the caller's destination register: it +//! is read from the call op at the saved `pc` (`call_dst`). +//! - **The argument-count slot carries the frame kind.** The header slot +//! "argument count" holds an int32 `argc | kind << 28` (kind 0: plain +//! call, 1: construct call, 2: generator or async frame). A plain return +//! is fast; the other two kinds return through a handler, because a +//! construct call substitutes `this` for a non-object result ([[Construct]], +//! §10.2.2) and a generator's return allocates an iterator result +//! (§27.5.3.3 GeneratorResume). +//! - **A call passes arguments by copy.** The arguments are `argc` consecutive +//! caller registers (`Call::args`). The callee frame is pushed at the first +//! slot after the caller's frame and arguments are copied into it, missing +//! parameters filled with `undefined`. Calls with more arguments than +//! parameters, any sloppy-mode `this` coercion, any `arguments` object and +//! every non-ordinary callee (bound, native, class constructor, generator, +//! async, Proxy) are not fast (`FnInfo::fast_callable`), so go to the call +//! handler, which pushes the same frame layout. +//! - **The termination flag** (phase-7.md, "Limits and stopping") is a read-only +//! state field, `terminate`. A `Loop` back-edge and a `Call` are guarded on it +//! being clear; when it is set the handler ends the evaluation with the +//! uncatchable `Terminated` error. Setting it is another thread's act, so +//! `step` never changes it. +//! - **Counters** for tiering (function entries, back-edges) are not in the +//! state: they are not observable by JS. +//! - **Op operands are `nat`s and the ops are an enum**, not a bit +//! encoding. `op_wf` is the check a compiler's output must pass. +//! - **A value of tag `0xFFFC` (RAW) and the hole** are internal values: they +//! never reach a JS-visible register except through the TDZ and array-hole +//! uses documented on `Op::LoadHole`. +//! +//! # Errata +//! +//! Number::multiply (§6.1.6.1.4) as written returns `+0` for `+0 × -5` +//! (step 6, `𝔽(ℝ(x) × ℝ(y))`, with `ℝ(+0) × ℝ(-5) = 0` and §6.1.6.1's "Number +//! value for", which gives `-0` only for a negative real). Every engine +//! and IEEE 754 give `-0`. `number_multiply` implements the evident intent +//! (a zero result has the sign of the product of the operand signs) in an +//! added step 5a, and `docs/ERRATA.md` has the entry. + +#[allow(unused_imports)] +use vstd::prelude::*; + + +pub use crate::ops::*; + +verus! { + +// ===================================================================== +// 1. Values (phase-7.md "Shapes fixed here for the JIT") +// ===================================================================== +// +// A value is a `u64`. +// +// - A double is itself, with every NaN replaced by the canonical NaN +// `0x7FF8_0000_0000_0000`. Then the top 16 bits of a double are at most +// `0xFFF8`, and `0xFFF8_0000_0000_0000` (the negative quiet NaN) is the +// only double-range pattern that is *not* a value. +// - Everything else is a NaN-space pattern with a 16-bit tag in bits 48..63: +// 0xFFF9 int32: bits 32..47 zero, the int32 in bits 0..31 +// 0xFFFA special: bits 0..47 are 0 undefined, 1 null, 2 false, 3 true, +// 4 hole +// 0xFFFB heap reference: generation (u16) in bits 32..47, arena +// index (u32) in bits 0..31 +// 0xFFFC raw: a 48-bit payload (header slots: return address) +// Tags 0xFFFD..0xFFFF are reserved and not values. + +/// `undefined`. +pub const UNDEFINED: u64 = 0xFFFA_0000_0000_0000; +/// `null`. +pub const NULL: u64 = 0xFFFA_0000_0000_0001; +/// `false`. +pub const FALSE: u64 = 0xFFFA_0000_0000_0002; +/// `true`. +pub const TRUE: u64 = 0xFFFA_0000_0000_0003; +/// The hole: an uninitialized binding or an absent array element. +pub const HOLE: u64 = 0xFFFA_0000_0000_0004; +/// The canonical NaN, the only NaN a value may be. +pub const CANON_NAN: u64 = 0x7FF8_0000_0000_0000; +/// The return-address payload of the outermost frame: no caller. +pub const RET_NONE: u64 = 0xFFFF_FFFF_FFFF; + +/// A decoded value. +pub enum Val { + /// A double (not an int32), by its canonical bits. + Double(u64), + /// An int32. + Int32(i32), + /// `undefined`. + Undefined, + /// `null`. + Null, + /// A boolean. + Bool(bool), + /// The hole. + Hole, + /// A heap reference: arena index and generation. + Ref(u32, u16), + /// A raw 48-bit payload. + Raw(u64), + /// A bit pattern that is not a value. + Invalid, +} + +/// IEEE 754 exponent field of a double's bits. +pub open spec fn f64_exp(b: u64) -> u64 { + (b >> 52) & 0x7FF +} + +/// IEEE 754 fraction field of a double's bits. +pub open spec fn f64_frac(b: u64) -> u64 { + b & 0xF_FFFF_FFFF_FFFF +} + +/// IEEE 754 sign bit of a double's bits (1 for negative). +pub open spec fn f64_sign(b: u64) -> u64 { + b >> 63 +} + +/// The Number is `NaN`. +pub open spec fn is_nan(b: u64) -> bool { + f64_exp(b) == 0x7FF && f64_frac(b) != 0 +} + +/// The Number is `+∞`. +pub open spec fn is_pos_inf(b: u64) -> bool { + b == 0x7FF0_0000_0000_0000 +} + +/// The Number is `-∞`. +pub open spec fn is_neg_inf(b: u64) -> bool { + b == 0xFFF0_0000_0000_0000 +} + +/// The Number is `+∞` or `-∞`. +pub open spec fn is_inf(b: u64) -> bool { + is_pos_inf(b) || is_neg_inf(b) +} + +/// The Number is `+0`. +pub open spec fn is_pos_zero(b: u64) -> bool { + b == 0 +} + +/// The Number is `-0`. +pub open spec fn is_neg_zero(b: u64) -> bool { + b == 0x8000_0000_0000_0000 +} + +/// The Number is `+0` or `-0`. +pub open spec fn is_zero(b: u64) -> bool { + is_pos_zero(b) || is_neg_zero(b) +} + +/// The Number is finite (not `NaN`, not an infinity). +pub open spec fn is_finite(b: u64) -> bool { + f64_exp(b) != 0x7FF +} + +/// The bits are a double *value*: in the double range, and no NaN but the +/// canonical one. +pub open spec fn is_double(v: u64) -> bool { + (v >> 48) < 0xFFF9 && (is_nan(v) ==> v == CANON_NAN) +} + +/// Encode a double: canonicalize NaN, keep every other pattern. +pub open spec fn enc_double(bits: u64) -> u64 { + if is_nan(bits) { CANON_NAN } else { bits } +} + +/// Encode an int32: tag `0xFFF9`, bits 32..47 zero. +pub open spec fn enc_int32(i: i32) -> u64 { + 0xFFF9_0000_0000_0000u64 | (((i as u32) as u64) & 0xFFFF_FFFF) +} + +/// Encode a heap reference: tag `0xFFFB`, generation, arena index. +pub open spec fn enc_ref(index: u32, generation: u16) -> u64 { + 0xFFFB_0000_0000_0000u64 | ((generation as u64) << 32) | (index as u64) +} + +/// Encode a raw payload (low 48 bits). +pub open spec fn enc_raw(p: u64) -> u64 { + 0xFFFC_0000_0000_0000u64 | (p & 0xFFFF_FFFF_FFFF) +} + +/// Encode a boolean. +pub open spec fn enc_bool(b: bool) -> u64 { + if b { TRUE } else { FALSE } +} + +/// Decode a value (total: a pattern that is not a value gives `Invalid`). +pub open spec fn decode(v: u64) -> Val { + let tag = v >> 48; + if tag < 0xFFF9 { + if is_double(v) { Val::Double(v) } else { Val::Invalid } + } else if tag == 0xFFF9 { + if (v >> 32) & 0xFFFF == 0 { + Val::Int32(((v & 0xFFFF_FFFF) as u32) as i32) + } else { + Val::Invalid + } + } else if tag == 0xFFFA { + let k = v & 0xFFFF_FFFF_FFFF; + if k == 0 { Val::Undefined } + else if k == 1 { Val::Null } + else if k == 2 { Val::Bool(false) } + else if k == 3 { Val::Bool(true) } + else if k == 4 { Val::Hole } + else { Val::Invalid } + } else if tag == 0xFFFB { + Val::Ref((v & 0xFFFF_FFFF) as u32, ((v >> 32) & 0xFFFF) as u16) + } else if tag == 0xFFFC { + Val::Raw(v & 0xFFFF_FFFF_FFFF) + } else { + Val::Invalid + } +} + +/// Encode a decoded value (the inverse of `decode`, `lemma_encode_decode`). +/// `Invalid` has no encoding; `0` is arbitrary. +pub open spec fn encode(x: Val) -> u64 { + match x { + Val::Double(b) => enc_double(b), + Val::Int32(i) => enc_int32(i), + Val::Undefined => UNDEFINED, + Val::Null => NULL, + Val::Bool(b) => enc_bool(b), + Val::Hole => HOLE, + Val::Ref(i, g) => enc_ref(i, g), + Val::Raw(p) => enc_raw(p), + Val::Invalid => 0, + } +} + +/// The bits are a well-formed value. +pub open spec fn value_wf(v: u64) -> bool { + !(decode(v) is Invalid) +} + +/// The value is an int32. +pub open spec fn is_int32(v: u64) -> bool { + decode(v) is Int32 +} + +/// The int32 payload of an int32 value (0 for any other value). +pub open spec fn int32_of(v: u64) -> i32 { + match decode(v) { + Val::Int32(i) => i, + _ => 0, + } +} + +/// The value is a Number: an int32 or a double. +pub open spec fn is_number(v: u64) -> bool { + decode(v) is Int32 || decode(v) is Double +} + +/// The value is a heap reference. +pub open spec fn is_ref(v: u64) -> bool { + decode(v) is Ref +} + +// ===================================================================== +// 2. Numbers (ECMA-262 §6.1.6.1 and §7.1) +// ===================================================================== + +/// An int32 fits. +pub open spec fn fits_i32(n: int) -> bool { + -2147483648 <= n && n <= 2147483647 +} + +/// `floor(log2(n))` for `n >= 1` (0 for 0 and 1). +pub open spec fn ilog2(n: nat) -> nat + decreases n, +{ + if n <= 1 { 0 } else { 1 + ilog2((n / 2) as nat) } +} + +/// The double that represents the integer `n`, exactly, for `|n| < 2^53` +/// (every int32 and uint32 qualify). `+0` for 0 (the integer 0 is `+0`). +pub open spec fn f64_of_int(n: int) -> u64 + recommends -9007199254740992 < n < 9007199254740992, +{ + if n == 0 { + 0 + } else { + let neg = n < 0; + let mag: nat = (if neg { -n } else { n }) as nat; + let k = ilog2(mag); + let frac: int = mag * vstd::arithmetic::power2::pow2((52 - k) as nat) - vstd::arithmetic::power2::pow2(52); + let exp: int = (k + 1023) as int; + ((if neg { 0x8000_0000_0000_0000int } else { 0int }) + exp * 4503599627370496int + frac) as u64 + } +} + +/// The double that represents an int32. +pub open spec fn i32_to_f64(i: i32) -> u64 { + f64_of_int(i as int) +} + +/// The double that represents the Number a value holds: an int32's integer, +/// or a double itself. (A non-Number gives itself, unused.) +pub open spec fn num_bits(v: u64) -> u64 { + match decode(v) { + Val::Int32(i) => i32_to_f64(i), + _ => v, + } +} + +/// The value for an integer result: an int32 when it fits, else the double +/// that represents it (for `|n| < 2^53`). +pub open spec fn enc_number_int(n: int) -> u64 { + if fits_i32(n) { enc_int32(n as i32) } else { enc_double(f64_of_int(n)) } +} + +/// `x > +0` for a non-NaN Number: positive and not a zero. +pub open spec fn gt_pos_zero(x: u64) -> bool { + f64_sign(x) == 0 && !is_zero(x) +} + +/// `x < -0` for a non-NaN Number: negative and not a zero. +pub open spec fn lt_neg_zero(x: u64) -> bool { + f64_sign(x) == 1 && !is_zero(x) +} + +/// The rounded sum of two finite Numbers: `𝔽(ℝ(x) + ℝ(y))`, with the +/// rounding of §6.1.6.1 ("the Number value for"). Uninterpreted, see the +/// modelling choices. +pub uninterp spec fn f64_add_finite(x: u64, y: u64) -> u64; + +/// `𝔽(ℝ(x) × ℝ(y))` for finite non-zero `x`, `y`. Uninterpreted. +pub uninterp spec fn f64_mul_finite(x: u64, y: u64) -> u64; + +/// `𝔽(ℝ(x) / ℝ(y))` for finite non-zero `x`, `y`. Uninterpreted. +pub uninterp spec fn f64_div_finite(x: u64, y: u64) -> u64; + +/// `𝔽(r)` of Number::remainder step 11, for finite non-zero `n`, `d`: +/// `r = ℝ(n) - ℝ(d) × truncate(ℝ(n) / ℝ(d))`, with `-0` when `r = 0` and +/// `n < -0` (steps 10 and 11 together). Uninterpreted. +pub uninterp spec fn f64_rem_finite(n: u64, d: u64) -> u64; + +/// Number::unaryMinus, §6.1.6.1.1 +/// (`#sec-numeric-types-number-unaryMinus`). +pub open spec fn number_unary_minus(x: u64) -> u64 { + if is_nan(x) { + CANON_NAN // 1. "If x is NaN, return NaN." + } else { + x ^ 0x8000_0000_0000_0000 // 2. "Return the negation of x" + } +} + +/// Number::add, §6.1.6.1.7 (`#sec-numeric-types-number-add`). +pub open spec fn number_add(x: u64, y: u64) -> u64 { + if is_nan(x) || is_nan(y) { + CANON_NAN // 1. + } else if is_pos_inf(x) && is_neg_inf(y) { + CANON_NAN // 2. + } else if is_neg_inf(x) && is_pos_inf(y) { + CANON_NAN // 3. + } else if is_inf(x) { + x // 4. + } else if is_inf(y) { + y // 5. + } + // 6. "Assert: x and y are both finite." + else if is_neg_zero(x) && is_neg_zero(y) { + x // 7. "return -0" + } else { + f64_add_finite(x, y) // 8. "Return 𝔽(ℝ(x) + ℝ(y))." + } +} + +/// Number::subtract, §6.1.6.1.8 (`#sec-numeric-types-number-subtract`). +pub open spec fn number_subtract(x: u64, y: u64) -> u64 { + number_add(x, number_unary_minus(y)) // 1. +} + +/// Number::multiply, §6.1.6.1.4 (`#sec-numeric-types-number-multiply`). +/// Step 5a is the erratum (docs/ERRATA.md): see the file header. +pub open spec fn number_multiply(x: u64, y: u64) -> u64 { + if is_nan(x) || is_nan(y) { + CANON_NAN // 1. + } else if is_inf(x) { + // 2. + if is_zero(y) { CANON_NAN } // 2.a. + else if gt_pos_zero(y) { x } // 2.b. + else { number_unary_minus(x) } // 2.c. + } else if is_inf(y) { + // 3. + if is_zero(x) { CANON_NAN } // 3.a. + else if gt_pos_zero(x) { y } // 3.b. + else { number_unary_minus(y) } // 3.c. + } else if is_neg_zero(x) { + // 4. + if is_neg_zero(y) || lt_neg_zero(y) { 0 } // 4.a. "return +0" + else { 0x8000_0000_0000_0000 } // 4.b. "Return -0" + } else if is_neg_zero(y) { + // 5. + if lt_neg_zero(x) { 0 } // 5.a. "return +0" + else { 0x8000_0000_0000_0000 } // 5.b. "Return -0" + } else if is_pos_zero(x) || is_pos_zero(y) { + // 5a (erratum): the other operand is finite and not NaN; the result is + // a zero whose sign is the exclusive or of the operand signs. + (f64_sign(x) ^ f64_sign(y)) << 63 + } else { + f64_mul_finite(x, y) // 6. "Return 𝔽(ℝ(x) × ℝ(y))." + } +} + +/// Number::divide, §6.1.6.1.5 (`#sec-numeric-types-number-divide`). +pub open spec fn number_divide(x: u64, y: u64) -> u64 { + if is_nan(x) || is_nan(y) { + CANON_NAN // 1. + } else if is_inf(x) { + // 2. + if is_inf(y) { CANON_NAN } // 2.a. + else if is_pos_zero(y) || gt_pos_zero(y) { x } // 2.b. + else { number_unary_minus(x) } // 2.c. + } else if is_pos_inf(y) { + // 3. + if is_pos_zero(x) || gt_pos_zero(x) { 0 } // 3.a. "return +0" + else { 0x8000_0000_0000_0000 } // 3.b. "Return -0" + } else if is_neg_inf(y) { + // 4. + if is_pos_zero(x) || gt_pos_zero(x) { 0x8000_0000_0000_0000 } // 4.a. + else { 0 } // 4.b. + } else if is_zero(x) { + // 5. + if is_zero(y) { CANON_NAN } // 5.a. + else if gt_pos_zero(y) { x } // 5.b. + else { number_unary_minus(x) } // 5.c. + } else if is_pos_zero(y) { + // 6. + if gt_pos_zero(x) { 0x7FF0_0000_0000_0000 } // 6.a. "return +∞" + else { 0xFFF0_0000_0000_0000 } // 6.b. "Return -∞" + } else if is_neg_zero(y) { + // 7. + if gt_pos_zero(x) { 0xFFF0_0000_0000_0000 } // 7.a. "return -∞" + else { 0x7FF0_0000_0000_0000 } // 7.b. "Return +∞" + } else { + f64_div_finite(x, y) // 8. "Return 𝔽(ℝ(x) / ℝ(y))." + } +} + +/// Number::remainder, §6.1.6.1.6 (`#sec-numeric-types-number-remainder`). +pub open spec fn number_remainder(n: u64, d: u64) -> u64 { + if is_nan(n) || is_nan(d) { + CANON_NAN // 1. + } else if is_inf(n) { + CANON_NAN // 2. + } else if is_inf(d) { + n // 3. + } else if is_zero(d) { + CANON_NAN // 4. + } else if is_zero(n) { + n // 5. + } else { + // 6. "Assert: n and d are finite and non-zero." + // 7. to 11. quotient, q, r, the -0 case, 𝔽(r): f64_rem_finite. + f64_rem_finite(n, d) + } +} + +/// The integer ordering key of a non-NaN Number: sign-magnitude as an +/// integer. `-0` and `+0` are both 0. +pub open spec fn f64_key(b: u64) -> int { + let m = (b & 0x7FFF_FFFF_FFFF_FFFF) as int; + if f64_sign(b) == 1 { -m } else { m } +} + +/// Number::lessThan, §6.1.6.1.12 (`#sec-numeric-types-number-lessThan`). +/// `None` is `undefined`. +pub open spec fn number_less_than(x: u64, y: u64) -> Option { + if is_nan(x) { + None // 1. + } else if is_nan(y) { + None // 2. + } else if x == y { + Some(false) // 3. "If x is y, return false." + } else if is_pos_zero(x) && is_neg_zero(y) { + Some(false) // 4. + } else if is_neg_zero(x) && is_pos_zero(y) { + Some(false) // 5. + } else if is_pos_inf(x) { + Some(false) // 6. + } else if is_pos_inf(y) { + Some(true) // 7. + } else if is_neg_inf(y) { + Some(false) // 8. + } else if is_neg_inf(x) { + Some(true) // 9. + } + // 10. "Assert: x and y are finite." + else { + Some(f64_key(x) < f64_key(y)) // 11. and 12. ℝ(x) < ℝ(y) + } +} + +/// Number::equal, §6.1.6.1.13 (`#sec-numeric-types-number-equal`). +pub open spec fn number_equal(x: u64, y: u64) -> bool { + if is_nan(x) { + false // 1. + } else if is_nan(y) { + false // 2. + } else if x == y { + true // 3. "If x is y, return true." + } else if is_pos_zero(x) && is_neg_zero(y) { + true // 4. + } else if is_neg_zero(x) && is_pos_zero(y) { + true // 5. + } else { + false // 6. + } +} + +/// `truncate(|ℝ(b)|)` for a finite Number: the integer part of the +/// magnitude. A finite double is `m × 2^k` with `m = 2^52 + frac` and +/// `k = exponent - 1075` (a zero exponent field is a subnormal or zero, of +/// magnitude below 1). +pub open spec fn f64_trunc_abs(b: u64) -> nat { + let e: int = f64_exp(b) as int; + if e == 0 { + 0 + } else { + let m: int = vstd::arithmetic::power2::pow2(52) + f64_frac(b) as int; + let k: int = e - 1075; + if k >= 0 { (m * vstd::arithmetic::power2::pow2(k as nat)) as nat } else { (m / (vstd::arithmetic::power2::pow2((-k) as nat) as int)) as nat } + } +} + +/// `int modulo 2^32` of ToInt32 and ToUint32, step 4: `truncate(ℝ(number))` +/// reduced into `[0, 2^32)`. +pub open spec fn f64_int32bit(b: u64) -> nat { + let t: int = f64_trunc_abs(b) as int; + let i: int = if f64_sign(b) == 1 { -t } else { t }; + (i % 4294967296int) as nat +} + +/// ToInt32, §7.1.6 (`#sec-toint32`), on a Number (step 1's ToNumber is the +/// identity on a Number). +pub open spec fn to_int32(b: u64) -> i32 { + // 2. "If number is not finite or number is either +0 or -0, return +0." + if !is_finite(b) || is_zero(b) { + 0 + } else { + let int32bit: int = f64_int32bit(b) as int; // 3. and 4. + if int32bit >= 2147483648int { + (int32bit - 4294967296int) as i32 // 5. + } else { + int32bit as i32 // 6. + } + } +} + +/// ToUint32, §7.1.7 (`#sec-touint32`), on a Number. +pub open spec fn to_uint32(b: u64) -> u32 { + // 2. + if !is_finite(b) || is_zero(b) { + 0 + } else { + f64_int32bit(b) as u32 // 3. to 5. + } +} + +/// `n` reduced into the int32 range, two's complement ("exactly representable +/// as a 32-bit two's complement bit string" in §6.1.6.1.9 and .10). +pub open spec fn wrap_i32(n: int) -> i32 { + let m: int = n % 4294967296int; + if m >= 2147483648int { (m - 4294967296int) as i32 } else { m as i32 } +} + +/// Number::bitwiseNOT, §6.1.6.1.2, on the Number's bits. +pub open spec fn number_bitwise_not(x: u64) -> i32 { + let old_value = to_int32(x); // 1. + (-1 - old_value as int) as i32 // 2. "bitwise complement of oldValue" +} + +/// Number::leftShift, §6.1.6.1.9, giving the int32 result. +pub open spec fn number_left_shift(x: u64, y: u64) -> i32 { + let l_num = to_int32(x); // 1. + let r_num = to_uint32(y); // 2. + let shift_count: nat = (r_num as nat) % 32; // 3. + wrap_i32(l_num as int * vstd::arithmetic::power2::pow2(shift_count) as int) // 4. +} + +/// Number::signedRightShift, §6.1.6.1.10, giving the int32 result. +pub open spec fn number_signed_right_shift(x: u64, y: u64) -> i32 { + let l_num = to_int32(x); // 1. + let r_num = to_uint32(y); // 2. + let shift_count: nat = (r_num as nat) % 32; // 3. + // 4. Sign-extending shift: floor division by 2^shiftCount. + (l_num as int / vstd::arithmetic::power2::pow2(shift_count) as int) as i32 +} + +/// Number::unsignedRightShift, §6.1.6.1.11, giving the uint32 result as an +/// integer. +pub open spec fn number_unsigned_right_shift(x: u64, y: u64) -> nat { + let l_num = to_uint32(x); // 1. + let r_num = to_uint32(y); // 2. + let shift_count: nat = (r_num as nat) % 32; // 3. + (l_num as nat) / vstd::arithmetic::power2::pow2(shift_count) // 4. Zero-filling shift. +} + +/// Number::bitwiseAND, §6.1.6.1.17 (the shared helper of §6.1.6.1.16 +/// NumberBitwiseOp: both operands through ToInt32, the operation on the +/// 32-bit strings, the result as an int32). +pub open spec fn number_bitwise_and(x: u64, y: u64) -> i32 { + to_int32(x) & to_int32(y) +} + +/// Number::bitwiseOR, §6.1.6.1.19. +pub open spec fn number_bitwise_or(x: u64, y: u64) -> i32 { + to_int32(x) | to_int32(y) +} + +/// Number::bitwiseXOR, §6.1.6.1.18. +pub open spec fn number_bitwise_xor(x: u64, y: u64) -> i32 { + to_int32(x) ^ to_int32(y) +} + +/// ToBoolean, §7.1.2 (`#sec-toboolean`), on the values that need no heap: +/// `None` for a heap reference (a String or BigInt needs its length, an +/// object may be IsHTMLDDA) and for internal values. +pub open spec fn to_boolean_fast(v: u64) -> Option { + match decode(v) { + Val::Undefined => Some(false), // 3. "If argument is undefined, null, false, +0, -0, NaN, 0n, or the empty String, return false." + Val::Null => Some(false), + Val::Bool(b) => Some(b), // 1. "If argument is a Boolean, return argument." + Val::Int32(i) => Some(i != 0), + Val::Double(b) => Some(!(is_zero(b) || is_nan(b))), + _ => None, + } +} + +/// IsStrictlyEqual, §7.2.14 (`#sec-isstrictlyequal`), where it needs no heap +/// contents: `None` when two distinct heap references might be equal Strings +/// or BigInts (the handler compares contents). +pub open spec fn strict_eq_fast(a: u64, b: u64) -> Option { + if !value_wf(a) || !value_wf(b) || decode(a) is Hole || decode(b) is Hole + || decode(a) is Raw || decode(b) is Raw { + None + } else if is_number(a) && is_number(b) { + Some(number_equal(num_bits(a), num_bits(b))) // 2. "If x is a Number, return Number::equal(x, y)." + } else if is_ref(a) && is_ref(b) { + if a == b { Some(true) } else { None } // 3. SameValueNonNumber, equal cells + } else if is_ref(a) || is_ref(b) { + Some(false) // 1. "If SameType(x, y) is false, return false." + } else { + Some(a == b) // 1., 3.: undefined, null and booleans + } +} + +/// The relational operators' result on Numbers, §13.10.1: `lt` is +/// `IsLessThan` §7.2.12 steps for two Numbers +/// ("If nx is a Number, return Number::lessThan(nx, ny)") with the +/// operand order and `undefined` handling of each operator. +pub open spec fn rel_lt(x: u64, y: u64) -> bool { + match number_less_than(x, y) { Some(r) => r, None => false } // `<`: "If r is undefined, return false." +} + +/// `x > y`: `IsLessThan(y, x, false)`. +pub open spec fn rel_gt(x: u64, y: u64) -> bool { + match number_less_than(y, x) { Some(r) => r, None => false } +} + +/// `x <= y`: `IsLessThan(y, x, false)`; "If r is either true or undefined, +/// return false. Return true." +pub open spec fn rel_le(x: u64, y: u64) -> bool { + match number_less_than(y, x) { Some(r) => !r, None => false } +} + +/// `x >= y`: `IsLessThan(x, y, true)`; "If r is either true or undefined, +/// return false. Return true." +pub open spec fn rel_ge(x: u64, y: u64) -> bool { + match number_less_than(x, y) { Some(r) => !r, None => false } +} + +// ---- The result of each guarded arithmetic op on two Numbers ---------- + +/// `a + b` on two Number values, with the encoding rule of the modelling +/// choices. Number::add §6.1.6.1.7. +pub open spec fn arith_add(a: u64, b: u64) -> u64 { + if is_int32(a) && is_int32(b) && fits_i32(int32_of(a) as int + int32_of(b) as int) { + enc_int32((int32_of(a) as int + int32_of(b) as int) as i32) + } else { + enc_double(number_add(num_bits(a), num_bits(b))) + } +} + +/// `a - b` on two Number values. Number::subtract §6.1.6.1.8. +pub open spec fn arith_sub(a: u64, b: u64) -> u64 { + if is_int32(a) && is_int32(b) && fits_i32(int32_of(a) as int - int32_of(b) as int) { + enc_int32((int32_of(a) as int - int32_of(b) as int) as i32) + } else { + enc_double(number_subtract(num_bits(a), num_bits(b))) + } +} + +/// `a * b` on two Number values. Number::multiply §6.1.6.1.4. An exact zero +/// product with a negative operand is `-0`, which no int32 is. +pub open spec fn arith_mul(a: u64, b: u64) -> u64 { + if is_int32(a) && is_int32(b) && fits_i32(int32_of(a) as int * int32_of(b) as int) + && !(int32_of(a) as int * int32_of(b) as int == 0 && (int32_of(a) < 0 || int32_of(b) < 0)) { + enc_int32((int32_of(a) as int * int32_of(b) as int) as i32) + } else { + enc_double(number_multiply(num_bits(a), num_bits(b))) + } +} + +/// `a / b` on two Number values: always a double. Number::divide §6.1.6.1.5. +pub open spec fn arith_div(a: u64, b: u64) -> u64 { + enc_double(number_divide(num_bits(a), num_bits(b))) +} + +/// The truncated remainder of two integers (sign of the dividend), `d != 0`. +pub open spec fn int_rem_trunc(n: int, d: int) -> int { + let m: int = (if n < 0 { -n } else { n }) % (if d < 0 { -d } else { d }); + if n < 0 { -m } else { m } +} + +/// `a % b` on two Number values. Number::remainder §6.1.6.1.6. The int32 +/// result is the remainder unless it is a zero from a negative dividend, +/// which is `-0`. +pub open spec fn arith_mod(a: u64, b: u64) -> u64 { + if is_int32(a) && is_int32(b) && int32_of(b) != 0 + && !(int_rem_trunc(int32_of(a) as int, int32_of(b) as int) == 0 && int32_of(a) < 0) { + enc_int32(int_rem_trunc(int32_of(a) as int, int32_of(b) as int) as i32) + } else { + enc_double(number_remainder(num_bits(a), num_bits(b))) + } +} + +/// `-a` on a Number value. Number::unaryMinus §6.1.6.1.1. `-0` is not an +/// int32, and `-(-2^31)` does not fit. +pub open spec fn arith_neg(a: u64) -> u64 { + if is_int32(a) && int32_of(a) != 0 && int32_of(a) != -2147483648 { + enc_int32((-(int32_of(a) as int)) as i32) + } else { + enc_double(number_unary_minus(num_bits(a))) + } +} + +/// `a + 1` (§13.4.2.1 and §13.4.4.1: `Number::add(oldValue, 1𝔽)`). +pub open spec fn arith_inc(a: u64) -> u64 { + arith_add(a, enc_int32(1)) +} + +/// `a - 1` (§13.4.3.1 and §13.4.5.1: `Number::subtract(oldValue, 1𝔽)`). +pub open spec fn arith_dec(a: u64) -> u64 { + arith_sub(a, enc_int32(1)) +} + +// ===================================================================== +// 3. The machine +// ===================================================================== + +/// The number of header slots in a frame: callee, `this`, argument count, +/// return address (phase-7.md "Shapes fixed here"). +pub open spec fn hdr_slots() -> nat { + 4 +} + +/// Slot of the callee in a frame (offset from the frame base). +pub open spec fn hdr_callee() -> nat { + 0 +} + +/// Slot of `this`. +pub open spec fn hdr_this() -> nat { + 1 +} + +/// Slot of the argument count and frame kind. +pub open spec fn hdr_argc() -> nat { + 2 +} + +/// Slot of the return address. +pub open spec fn hdr_ret() -> nat { + 3 +} + +/// A plain call's frame kind. +pub open spec fn kind_plain() -> nat { + 0 +} + +/// A construct call's frame kind. +pub open spec fn kind_construct() -> nat { + 1 +} + +/// A generator or async frame's kind. +pub open spec fn kind_suspendable() -> nat { + 2 +} + +/// The int32 stored in a frame's argument-count slot. +pub open spec fn enc_argc(argc: nat, kind: nat) -> u64 { + enc_int32((argc + kind * 268435456) as i32) +} + +/// The argument count in an argument-count slot. +pub open spec fn argc_of(v: u64) -> nat { + ((int32_of(v) as int) % 268435456) as nat +} + +/// The frame kind in an argument-count slot. +pub open spec fn kind_of(v: u64) -> nat { + ((int32_of(v) as int) / 268435456) as nat +} + +/// The return-address payload for a caller with frame base `base` at `pc`. +pub open spec fn pack_ret(base: nat, pc: nat) -> u64 { + (((base as u64) << 24) | (pc as u64)) & 0xFFFF_FFFF_FFFF +} + +/// The return address packs a frame base and a `pc`, each below this. +pub open spec fn ret_limit() -> nat { + 0xFF_FFFF +} + +/// What a cell is, for the fast paths. +pub enum Class { + /// An ordinary object. + Plain, + /// An Array exotic object (§10.4.2), dense. + Array, + /// A function object. + Function(FnInfo), + /// A declarative environment (§9.1.1.1): its slots are the bindings. + Env { + /// The enclosing environment: a heap reference, or `undefined` for the outermost. + parent: u64, + }, + /// A string, symbol, BigInt, or any cell the fast paths do not touch. + Other, +} + +/// What a fast call needs to know of a function object. +pub struct FnInfo { + /// The function's code, an index into `State::codes`. + pub code: nat, + /// The captured environment: a heap reference, or `undefined`. + pub env: u64, + /// The function is ordinary for the fast call: [[Call]] is + /// OrdinaryCallEvaluateBody (§10.2.1.4) with no `this` coercion, no + /// `arguments` object, not a class constructor, generator or async. + /// Decided by the heap (7.5) when the function is created. + pub fast_callable: bool, +} + +/// A heap cell, as far as the fast paths see it. +pub struct Cell { + /// The generation (phase-7.md 7.0(f): bumped when the slot is reused). + pub generation: u16, + /// The shape id; 0 for cells with no properties. + pub shape: nat, + /// What the cell is. + pub class: Class, + /// Property slots, by the shape's layout. + pub slots: Seq, + /// Dense elements; the hole marks an absent one. + pub elements: Seq, + /// Every element is an ordinary writable, configurable, enumerable data + /// property of an extensible object (not frozen, sealed, or an accessor). + pub elements_plain: bool, +} + +/// The heap: live cells by arena index. +pub struct Heap { + /// Live cells. + pub cells: Map, +} + +/// One inline-cache entry: a shape and the slot index it gives. +pub struct IcEntry { + /// The shape id; 0 means empty and never hits. + pub shape: nat, + /// The property's slot. + pub slot: nat, +} + +/// A function's code. +pub struct Code { + /// The ops. + pub ops: Seq, + /// The constant pool (values). + pub consts: Seq, + /// The number of parameters. + pub nparams: nat, + /// The number of registers after the parameters. + pub nregs: nat, + /// The size of the inline-cache table. + pub nics: nat, +} + +/// The abstract machine state. +pub struct State { + /// The value-stack region: every frame is a window of it. + pub region: Seq, + /// The base slot of the current frame. + pub fp: nat, + /// The index of the next op of the current function. + pub pc: nat, + /// The heap. + pub heap: Heap, + /// All code, by id. Immutable while running. + pub codes: Seq, + /// Inline-cache tables, by code id then ic index. Handlers install entries. + pub ics: Seq>, + /// The thrown value, set by unwinding and read by `GetException`. + pub exception: u64, + /// The termination flag. Set from outside; `step` never changes it. + pub terminate: bool, +} + +/// The number of slots of a frame of `code`: header, parameters, registers. +pub open spec fn frame_size(c: Code) -> nat { + hdr_slots() + c.nparams + c.nregs +} + +/// The slot of register `r` in the frame at `fp`: arguments first (registers +/// `0..nparams`), then locals. +pub open spec fn reg_slot(fp: nat, r: nat) -> nat { + fp + hdr_slots() + r +} + +/// The live cell a value refers to, if it is a live heap reference. +pub open spec fn live_cell(h: Heap, v: u64) -> Option { + match decode(v) { + Val::Ref(i, g) => { + if h.cells.dom().contains(i) && h.cells[i].generation == g { + Some(h.cells[i]) + } else { + None + } + } + _ => None, + } +} + +/// The arena index of a heap reference (0 for anything else). +pub open spec fn ref_index(v: u64) -> u32 { + match decode(v) { + Val::Ref(i, _) => i, + _ => 0, + } +} + +/// The value of register `r` of the current frame. +pub open spec fn reg(s: State, r: nat) -> u64 + recommends reg_slot(s.fp, r) < s.region.len(), +{ + s.region[reg_slot(s.fp, r) as int] +} + +/// `s` with register `r` of the current frame set to `v`. +pub open spec fn set_reg(s: State, r: nat, v: u64) -> State + recommends reg_slot(s.fp, r) < s.region.len(), +{ + State { region: s.region.update(reg_slot(s.fp, r) as int, v), ..s } +} + +/// `s` at the next op. +pub open spec fn next(s: State) -> State { + State { pc: s.pc + 1, ..s } +} + +/// `s` at op `target`. +pub open spec fn jump(s: State, target: nat) -> State { + State { pc: target, ..s } +} + +/// The code id of the function a frame at `fp` is running, from the callee +/// slot of its header (0 if the slot is not a live function). +pub open spec fn frame_code_id(s: State, fp: nat) -> nat + recommends fp < s.region.len(), +{ + match live_cell(s.heap, s.region[(fp + hdr_callee()) as int]) { + Some(c) => match c.class { + Class::Function(f) => f.code, + _ => 0, + }, + None => 0, + } +} + +/// The code of the current frame. +pub open spec fn cur_code(s: State) -> Code + recommends s.fp < s.region.len(), frame_code_id(s, s.fp) < s.codes.len(), +{ + s.codes[frame_code_id(s, s.fp) as int] +} + +/// The op at `pc` in the current function. +pub open spec fn fetch(s: State) -> Op + recommends s.pc < cur_code(s).ops.len(), +{ + cur_code(s).ops[s.pc as int] +} + +/// One step of the machine: fetch and run. +pub open spec fn step_fetch(s: State) -> State { + step(s, fetch(s)) +} + +/// An operand register is inside the frame of `c`. +pub open spec fn reg_ok(c: Code, r: nat) -> bool { + r < c.nparams + c.nregs +} + +/// `n` registers from `r` are inside the frame of `c`. +pub open spec fn regs_ok(c: Code, r: nat, n: nat) -> bool { + r + n <= c.nparams + c.nregs +} + +/// An op's operands are in range for the function `c` with `nops` ops: every +/// register inside the frame, every constant, target and cache index in its +/// table. A compiler's output must satisfy it (7.7). +pub open spec fn op_wf(c: Code, op: Op) -> bool { + let nops = c.ops.len(); + match op { + Op::Nop => true, + Op::Move { dst, src } => reg_ok(c, dst) && reg_ok(c, src), + Op::LoadConst { dst, k } => reg_ok(c, dst) && k < c.consts.len() && value_wf(c.consts[k as int]), + Op::LoadInt { dst, .. } => reg_ok(c, dst), + Op::LoadUndefined { dst } => reg_ok(c, dst), + Op::LoadNull { dst } => reg_ok(c, dst), + Op::LoadBool { dst, .. } => reg_ok(c, dst), + Op::LoadHole { dst } => reg_ok(c, dst), + Op::GetThis { dst } => reg_ok(c, dst), + Op::GetCallee { dst } => reg_ok(c, dst), + Op::GetArgc { dst } => reg_ok(c, dst), + Op::GetException { dst } => reg_ok(c, dst), + Op::Jump { target } => target < nops, + Op::JumpIfUndefined { src, target } => reg_ok(c, src) && target < nops, + Op::JumpIfNotUndefined { src, target } => reg_ok(c, src) && target < nops, + Op::JumpIfNullish { src, target } => reg_ok(c, src) && target < nops, + Op::JumpIfNotNullish { src, target } => reg_ok(c, src) && target < nops, + Op::Add { dst, a, b } | Op::Sub { dst, a, b } | Op::Mul { dst, a, b } + | Op::Div { dst, a, b } | Op::Mod { dst, a, b } | Op::BitAnd { dst, a, b } + | Op::BitOr { dst, a, b } | Op::BitXor { dst, a, b } | Op::Shl { dst, a, b } + | Op::Shr { dst, a, b } | Op::UShr { dst, a, b } | Op::Lt { dst, a, b } + | Op::Le { dst, a, b } | Op::Gt { dst, a, b } | Op::Ge { dst, a, b } + | Op::StrictEq { dst, a, b } | Op::StrictNe { dst, a, b } | Op::Exp { dst, a, b } + | Op::LooseEq { dst, a, b } | Op::LooseNe { dst, a, b } + | Op::InstanceOf { dst, a, b } | Op::HasProperty { dst, a, b } => + reg_ok(c, dst) && reg_ok(c, a) && reg_ok(c, b), + Op::Neg { dst, src } | Op::Inc { dst, src } | Op::Dec { dst, src } + | Op::BitNot { dst, src } | Op::Not { dst, src } | Op::ToNumeric { dst, src } + | Op::TypeOf { dst, src } | Op::GetIterator { dst, src } => + reg_ok(c, dst) && reg_ok(c, src), + Op::JumpIfTrue { cond, target } | Op::JumpIfFalse { cond, target } => + reg_ok(c, cond) && target < nops, + Op::Loop { target } => target < nops, + Op::ThrowIfHole { src } => reg_ok(c, src), + Op::GetProp { dst, obj, key, ic } => + reg_ok(c, dst) && reg_ok(c, obj) && key < c.consts.len() && ic < c.nics, + Op::SetProp { obj, key, val, ic } => + reg_ok(c, obj) && key < c.consts.len() && reg_ok(c, val) && ic < c.nics, + Op::GetElem { dst, obj, idx } => reg_ok(c, dst) && reg_ok(c, obj) && reg_ok(c, idx), + Op::SetElem { obj, idx, val } => reg_ok(c, obj) && reg_ok(c, idx) && reg_ok(c, val), + Op::Call { dst, callee, this, args, argc } => + reg_ok(c, dst) && reg_ok(c, callee) && reg_ok(c, this) && regs_ok(c, args, argc), + Op::Return { src } => reg_ok(c, src), + Op::GetEnvSlot { dst, env, .. } => reg_ok(c, dst) && reg_ok(c, env), + Op::SetEnvSlot { env, src, .. } => reg_ok(c, env) && reg_ok(c, src), + Op::GetEnvParent { dst, env } => reg_ok(c, dst) && reg_ok(c, env), + Op::GetCalleeEnv { dst } => reg_ok(c, dst), + Op::DeleteProp { dst, obj, idx } => reg_ok(c, dst) && reg_ok(c, obj) && reg_ok(c, idx), + Op::GetGlobal { dst, key, ic } => reg_ok(c, dst) && key < c.consts.len() && ic < c.nics, + Op::SetGlobal { key, src, ic } => key < c.consts.len() && reg_ok(c, src) && ic < c.nics, + Op::NewObject { dst } => reg_ok(c, dst), + Op::NewArray { dst, .. } => reg_ok(c, dst), + Op::NewEnv { dst, parent, .. } => reg_ok(c, dst) && reg_ok(c, parent), + Op::NewClosure { dst, env, .. } => reg_ok(c, dst) && reg_ok(c, env), + Op::New { dst, callee, args, argc } => + reg_ok(c, dst) && reg_ok(c, callee) && regs_ok(c, args, argc), + Op::CallSpread { dst, callee, this, args } => + reg_ok(c, dst) && reg_ok(c, callee) && reg_ok(c, this) && reg_ok(c, args), + Op::IterNext { value, done, iter } => + reg_ok(c, value) && reg_ok(c, done) && reg_ok(c, iter), + Op::IterClose { iter } => reg_ok(c, iter), + Op::Yield { src, value, mode } | Op::Await { src, value, mode } => + reg_ok(c, src) && reg_ok(c, value) && reg_ok(c, mode), + Op::Throw { src } => reg_ok(c, src), + Op::ThrowError { msg, .. } => msg < c.consts.len(), + } +} + +/// The op can continue at the next op (every op but the unconditional +/// transfers of control and the throws). +pub open spec fn falls_through(op: Op) -> bool { + match op { + Op::Jump { .. } | Op::Loop { .. } | Op::Return { .. } | Op::Throw { .. } + | Op::ThrowError { .. } => false, + _ => true, + } +} + +/// Every op of the function is well-formed, an op that can continue is not +/// the last (so `pc` never leaves the function), and the function fits the +/// return-address limit. +pub open spec fn code_wf(c: Code) -> bool { + &&& c.ops.len() < ret_limit() + &&& forall|i: int| 0 <= i < c.ops.len() ==> op_wf(c, #[trigger] c.ops[i]) + &&& forall|i: int| 0 <= i < c.ops.len() && falls_through(#[trigger] c.ops[i]) ==> i + 1 < c.ops.len() +} + +/// The frame at `fp` is well-formed: its callee is a live function whose code +/// exists, and the whole window is inside the region. +pub open spec fn frame_wf(s: State, fp: nat) -> bool { + &&& fp + hdr_slots() <= s.region.len() + &&& match live_cell(s.heap, s.region[(fp + hdr_callee()) as int]) { + Some(c) => match c.class { + Class::Function(f) => f.code < s.codes.len() + && fp + frame_size(s.codes[f.code as int]) <= s.region.len(), + _ => false, + }, + None => false, + } +} + +/// The machine's invariant, which the handlers preserve (their contract, 7.8) +/// and `step` preserves for core ops (`lemma_core_step_wf`): the current +/// frame is well-formed, `pc` is inside the function, the code and the +/// tables are consistent, and the region is within the return-address limit. +pub open spec fn state_wf(s: State) -> bool { + &&& s.region.len() < ret_limit() + &&& s.ics.len() == s.codes.len() + &&& forall|i: int| 0 <= i < s.codes.len() ==> code_wf(#[trigger] s.codes[i]) + &&& forall|i: int| 0 <= i < s.codes.len() ==> s.ics[i].len() == (#[trigger] s.codes[i]).nics + &&& frame_wf(s, s.fp) + &&& s.pc < cur_code(s).ops.len() +} + +/// An inline-cache entry hits a cell: the entry is not empty, the shapes +/// agree, and the slot is there. +pub open spec fn ic_hit(c: Cell, e: IcEntry) -> bool { + e.shape != 0 && c.shape == e.shape && e.slot < c.slots.len() +} + +/// The cell is an ordinary property holder that a cache may name. +pub open spec fn is_prop_holder(c: Cell) -> bool { + match c.class { + Class::Plain => true, + Class::Array => true, + Class::Function(_) => true, + _ => false, + } +} + +/// The inline-cache invariant of phase-7.md "Inline caches are data": an +/// entry's shape implies the slot exists in every live cell of that shape. +pub open spec fn ic_wf(s: State) -> bool { + forall|ci: int, ii: int, h: u32| #![trigger s.ics[ci][ii], s.heap.cells[h]] + 0 <= ci < s.ics.len() && 0 <= ii < s.ics[ci].len() && s.heap.cells.dom().contains(h) + && s.ics[ci][ii].shape != 0 && s.heap.cells[h].shape == s.ics[ci][ii].shape + && is_prop_holder(s.heap.cells[h]) + ==> s.ics[ci][ii].slot < s.heap.cells[h].slots.len() +} + +/// The caller a plain `Return` goes back to. +pub struct RetTarget { + /// The caller's frame base. + pub base: nat, + /// The `pc` of the caller's call op. + pub pc: nat, + /// The register that receives the value. + pub dst: nat, +} + +/// The caller named by the current frame's return address, if it is a +/// well-formed one: a RAW address that is not `RET_NONE`, naming a frame +/// whose callee is a live function, whose op at `pc` is a call, with its +/// destination register in the region. +pub open spec fn ret_target(s: State) -> Option { + match decode(s.region[(s.fp + hdr_ret()) as int]) { + Val::Raw(p) => { + if p == RET_NONE { + None + } else { + let base: nat = (p >> 24) as nat; + let pc: nat = (p & 0xFF_FFFF) as nat; + if base + hdr_slots() > s.region.len() { + None + } else { + match live_cell(s.heap, s.region[(base + hdr_callee()) as int]) { + Some(c) => match c.class { + Class::Function(f) => { + if f.code < s.codes.len() && pc < s.codes[f.code as int].ops.len() { + match call_dst(s.codes[f.code as int].ops[pc as int]) { + Some(dst) => { + if reg_slot(base, dst) < s.region.len() { + Some(RetTarget { base: base, pc: pc, dst: dst }) + } else { + None + } + } + None => None, + } + } else { + None + } + } + _ => None, + }, + None => None, + } + } + } + } + _ => None, + } +} + +/// The function a `Call` would enter on its callee operand, if the callee is +/// a live function the fast call accepts. +pub open spec fn call_target(s: State, callee: u64) -> Option { + match live_cell(s.heap, callee) { + Some(c) => match c.class { + Class::Function(f) => if f.fast_callable { Some(f) } else { None }, + _ => None, + }, + None => None, + } +} + +/// The region after pushing a frame at `nb` for the function `f` (code `cc`): +/// header, the first `argc` arguments copied from the caller's registers +/// `args..`, `undefined` in the missing parameters and in every local. +pub open spec fn pushed_region(s: State, nb: nat, callee: u64, this_v: u64, args: nat, argc: nat, cc: Code, ret: u64) -> Seq { + Seq::new(s.region.len(), |i: int| + if i == nb + hdr_callee() { callee } + else if i == nb + hdr_this() { this_v } + else if i == nb + hdr_argc() { enc_argc(argc, kind_plain()) } + else if i == nb + hdr_ret() { ret } + else if nb + hdr_slots() <= i && i < nb + hdr_slots() + argc { + s.region[reg_slot(s.fp, args + (i - nb - hdr_slots()) as nat) as int] + } + else if nb + hdr_slots() + argc <= i && i < nb + frame_size(cc) { UNDEFINED } + else { s.region[i] }) +} + +// ===================================================================== +// 4. fast_path, fast_step, handler, step +// ===================================================================== + +/// The uninterpreted handler: the next state after calling handler `h` for +/// `op` in state `s`, including `pc`. Test262 is the evidence for each +/// handler (phase-7.md 7.4); its contract is written with the handler, 7.8. +pub uninterp spec fn handler(h: HandlerId, s: State, op: Op) -> State; + +/// The condition under which `op` takes its fast path (`fast_step`) in `s`. +/// True for every core op, false for every handler op, and for a guarded op +/// the condition the JIT tests inline. +pub open spec fn fast_path(s: State, op: Op) -> bool { + match op { + // --- Core --- + Op::Nop | Op::Move { .. } | Op::LoadConst { .. } | Op::LoadInt { .. } + | Op::LoadUndefined { .. } | Op::LoadNull { .. } | Op::LoadBool { .. } + | Op::LoadHole { .. } | Op::GetThis { .. } | Op::GetCallee { .. } + | Op::GetArgc { .. } | Op::GetException { .. } | Op::Jump { .. } + | Op::JumpIfUndefined { .. } | Op::JumpIfNotUndefined { .. } + | Op::JumpIfNullish { .. } | Op::JumpIfNotNullish { .. } => true, + // --- Guarded: numbers --- + Op::Add { a, b, .. } | Op::Sub { a, b, .. } | Op::Mul { a, b, .. } + | Op::Div { a, b, .. } | Op::Mod { a, b, .. } | Op::BitAnd { a, b, .. } + | Op::BitOr { a, b, .. } | Op::BitXor { a, b, .. } | Op::Shl { a, b, .. } + | Op::Shr { a, b, .. } | Op::UShr { a, b, .. } | Op::Lt { a, b, .. } + | Op::Le { a, b, .. } | Op::Gt { a, b, .. } | Op::Ge { a, b, .. } => + is_number(reg(s, a)) && is_number(reg(s, b)), + Op::Neg { src, .. } | Op::Inc { src, .. } | Op::Dec { src, .. } + | Op::BitNot { src, .. } | Op::ToNumeric { src, .. } => is_number(reg(s, src)), + Op::StrictEq { a, b, .. } | Op::StrictNe { a, b, .. } => + strict_eq_fast(reg(s, a), reg(s, b)) is Some, + Op::Not { src, .. } => to_boolean_fast(reg(s, src)) is Some, + Op::JumpIfTrue { cond, .. } | Op::JumpIfFalse { cond, .. } => + to_boolean_fast(reg(s, cond)) is Some, + Op::Loop { .. } => !s.terminate, + Op::ThrowIfHole { src } => reg(s, src) != HOLE, + // --- Guarded: properties --- + Op::GetProp { obj, ic, .. } | Op::SetProp { obj, ic, .. } => { + match live_cell(s.heap, reg(s, obj)) { + Some(c) => is_prop_holder(c) && ic_hit(c, s.ics[frame_code_id(s, s.fp) as int][ic as int]), + None => false, + } + } + Op::GetElem { obj, idx, .. } | Op::SetElem { obj, idx, .. } => { + match live_cell(s.heap, reg(s, obj)) { + Some(c) => (c.class is Plain || c.class is Array) && c.elements_plain + && is_int32(reg(s, idx)) && 0 <= int32_of(reg(s, idx)) + && int32_of(reg(s, idx)) < c.elements.len() + && c.elements[int32_of(reg(s, idx)) as int] != HOLE, + None => false, + } + } + // --- Guarded: calls --- + Op::Call { callee, args, argc, .. } => { + match call_target(s, reg(s, callee)) { + Some(f) => { + &&& !s.terminate + &&& f.code < s.codes.len() + &&& argc <= s.codes[f.code as int].nparams + &&& s.fp < ret_limit() && s.pc < ret_limit() + &&& s.fp + frame_size(cur_code(s)) + frame_size(s.codes[f.code as int]) <= s.region.len() + } + None => false, + } + } + Op::Return { .. } => { + &&& kind_of(s.region[(s.fp + hdr_argc()) as int]) == kind_plain() + &&& ret_target(s) is Some + } + // --- Guarded: environments --- + Op::GetEnvSlot { env, idx, .. } | Op::SetEnvSlot { env, idx, .. } => { + match live_cell(s.heap, reg(s, env)) { + Some(c) => (c.class is Env) && idx < c.slots.len(), + None => false, + } + } + Op::GetEnvParent { env, .. } => { + match live_cell(s.heap, reg(s, env)) { + Some(c) => c.class is Env, + None => false, + } + } + Op::GetCalleeEnv { .. } => { + match live_cell(s.heap, s.region[(s.fp + hdr_callee()) as int]) { + Some(c) => c.class is Function, + None => false, + } + } + // --- Handler ops: never fast --- + _ => false, + } +} + +/// The result of a core op, or of a guarded op when `fast_path` holds. +/// Defined for every op so it is a total function; for a handler op the value +/// is `s` and never used (`step` does not reach it). +pub open spec fn fast_step(s: State, op: Op) -> State { + match op { + Op::Nop => next(s), + Op::Move { dst, src } => next(set_reg(s, dst, reg(s, src))), + Op::LoadConst { dst, k } => next(set_reg(s, dst, cur_code(s).consts[k as int])), + Op::LoadInt { dst, imm } => next(set_reg(s, dst, enc_int32(imm))), + Op::LoadUndefined { dst } => next(set_reg(s, dst, UNDEFINED)), + Op::LoadNull { dst } => next(set_reg(s, dst, NULL)), + Op::LoadBool { dst, flag } => next(set_reg(s, dst, enc_bool(flag))), + Op::LoadHole { dst } => next(set_reg(s, dst, HOLE)), + Op::GetThis { dst } => next(set_reg(s, dst, s.region[(s.fp + hdr_this()) as int])), + Op::GetCallee { dst } => next(set_reg(s, dst, s.region[(s.fp + hdr_callee()) as int])), + Op::GetArgc { dst } => next(set_reg(s, dst, + enc_int32(argc_of(s.region[(s.fp + hdr_argc()) as int]) as i32))), + Op::GetException { dst } => next(set_reg(s, dst, s.exception)), + Op::Jump { target } => jump(s, target), + Op::JumpIfUndefined { src, target } => + if reg(s, src) == UNDEFINED { jump(s, target) } else { next(s) }, + Op::JumpIfNotUndefined { src, target } => + if reg(s, src) != UNDEFINED { jump(s, target) } else { next(s) }, + Op::JumpIfNullish { src, target } => + if reg(s, src) == UNDEFINED || reg(s, src) == NULL { jump(s, target) } else { next(s) }, + Op::JumpIfNotNullish { src, target } => + if reg(s, src) != UNDEFINED && reg(s, src) != NULL { jump(s, target) } else { next(s) }, + + Op::Add { dst, a, b } => next(set_reg(s, dst, arith_add(reg(s, a), reg(s, b)))), + Op::Sub { dst, a, b } => next(set_reg(s, dst, arith_sub(reg(s, a), reg(s, b)))), + Op::Mul { dst, a, b } => next(set_reg(s, dst, arith_mul(reg(s, a), reg(s, b)))), + Op::Div { dst, a, b } => next(set_reg(s, dst, arith_div(reg(s, a), reg(s, b)))), + Op::Mod { dst, a, b } => next(set_reg(s, dst, arith_mod(reg(s, a), reg(s, b)))), + Op::Neg { dst, src } => next(set_reg(s, dst, arith_neg(reg(s, src)))), + Op::Inc { dst, src } => next(set_reg(s, dst, arith_inc(reg(s, src)))), + Op::Dec { dst, src } => next(set_reg(s, dst, arith_dec(reg(s, src)))), + Op::BitAnd { dst, a, b } => next(set_reg(s, dst, + enc_int32(number_bitwise_and(num_bits(reg(s, a)), num_bits(reg(s, b)))))), + Op::BitOr { dst, a, b } => next(set_reg(s, dst, + enc_int32(number_bitwise_or(num_bits(reg(s, a)), num_bits(reg(s, b)))))), + Op::BitXor { dst, a, b } => next(set_reg(s, dst, + enc_int32(number_bitwise_xor(num_bits(reg(s, a)), num_bits(reg(s, b)))))), + Op::Shl { dst, a, b } => next(set_reg(s, dst, + enc_int32(number_left_shift(num_bits(reg(s, a)), num_bits(reg(s, b)))))), + Op::Shr { dst, a, b } => next(set_reg(s, dst, + enc_int32(number_signed_right_shift(num_bits(reg(s, a)), num_bits(reg(s, b)))))), + Op::UShr { dst, a, b } => next(set_reg(s, dst, + enc_number_int(number_unsigned_right_shift(num_bits(reg(s, a)), num_bits(reg(s, b))) as int))), + Op::BitNot { dst, src } => next(set_reg(s, dst, + enc_int32(number_bitwise_not(num_bits(reg(s, src)))))), + Op::Lt { dst, a, b } => next(set_reg(s, dst, + enc_bool(rel_lt(num_bits(reg(s, a)), num_bits(reg(s, b)))))), + Op::Le { dst, a, b } => next(set_reg(s, dst, + enc_bool(rel_le(num_bits(reg(s, a)), num_bits(reg(s, b)))))), + Op::Gt { dst, a, b } => next(set_reg(s, dst, + enc_bool(rel_gt(num_bits(reg(s, a)), num_bits(reg(s, b)))))), + Op::Ge { dst, a, b } => next(set_reg(s, dst, + enc_bool(rel_ge(num_bits(reg(s, a)), num_bits(reg(s, b)))))), + Op::StrictEq { dst, a, b } => next(set_reg(s, dst, + enc_bool(match strict_eq_fast(reg(s, a), reg(s, b)) { Some(r) => r, None => false }))), + Op::StrictNe { dst, a, b } => next(set_reg(s, dst, + enc_bool(match strict_eq_fast(reg(s, a), reg(s, b)) { Some(r) => !r, None => false }))), + Op::Not { dst, src } => next(set_reg(s, dst, + enc_bool(match to_boolean_fast(reg(s, src)) { Some(r) => !r, None => false }))), + Op::ToNumeric { dst, src } => next(set_reg(s, dst, reg(s, src))), + Op::JumpIfTrue { cond, target } => + if to_boolean_fast(reg(s, cond)) == Some(true) { jump(s, target) } else { next(s) }, + Op::JumpIfFalse { cond, target } => + if to_boolean_fast(reg(s, cond)) == Some(false) { jump(s, target) } else { next(s) }, + Op::Loop { target } => jump(s, target), + Op::ThrowIfHole { src } => next(s), + + Op::GetProp { dst, obj, key, ic } => { + let c = live_cell(s.heap, reg(s, obj))->Some_0; + let e = s.ics[frame_code_id(s, s.fp) as int][ic as int]; + next(set_reg(s, dst, c.slots[e.slot as int])) + } + Op::SetProp { obj, key, val, ic } => { + let c = live_cell(s.heap, reg(s, obj))->Some_0; + let e = s.ics[frame_code_id(s, s.fp) as int][ic as int]; + let c2 = Cell { slots: c.slots.update(e.slot as int, reg(s, val)), ..c }; + next(State { + heap: Heap { cells: s.heap.cells.insert(ref_index(reg(s, obj)), c2) }, + ..s + }) + } + Op::GetElem { dst, obj, idx } => { + let c = live_cell(s.heap, reg(s, obj))->Some_0; + next(set_reg(s, dst, c.elements[int32_of(reg(s, idx)) as int])) + } + Op::SetElem { obj, idx, val } => { + let c = live_cell(s.heap, reg(s, obj))->Some_0; + let c2 = Cell { elements: c.elements.update(int32_of(reg(s, idx)) as int, reg(s, val)), ..c }; + next(State { + heap: Heap { cells: s.heap.cells.insert(ref_index(reg(s, obj)), c2) }, + ..s + }) + } + Op::Call { dst, callee, this, args, argc } => { + // Push a frame after the caller's (see `pushed_region`). + let f = call_target(s, reg(s, callee))->Some_0; + let nb: nat = s.fp + frame_size(cur_code(s)); + let cc = s.codes[f.code as int]; + State { + region: pushed_region(s, nb, reg(s, callee), reg(s, this), args, argc, cc, + enc_raw(pack_ret(s.fp, s.pc))), + fp: nb, + pc: 0, + ..s + } + } + Op::Return { src } => { + // Pop the frame: the value goes to the call op's destination. + let t = ret_target(s)->Some_0; + State { + region: s.region.update(reg_slot(t.base, t.dst) as int, reg(s, src)), + fp: t.base, + pc: t.pc + 1, + ..s + } + } + Op::GetEnvSlot { dst, env, idx } => { + let c = live_cell(s.heap, reg(s, env))->Some_0; + next(set_reg(s, dst, c.slots[idx as int])) + } + Op::SetEnvSlot { env, idx, src } => { + let c = live_cell(s.heap, reg(s, env))->Some_0; + let c2 = Cell { slots: c.slots.update(idx as int, reg(s, src)), ..c }; + next(State { + heap: Heap { cells: s.heap.cells.insert(ref_index(reg(s, env)), c2) }, + ..s + }) + } + Op::GetEnvParent { dst, env } => { + let c = live_cell(s.heap, reg(s, env))->Some_0; + next(set_reg(s, dst, match c.class { Class::Env { parent } => parent, _ => UNDEFINED })) + } + Op::GetCalleeEnv { dst } => { + let c = live_cell(s.heap, s.region[(s.fp + hdr_callee()) as int])->Some_0; + next(set_reg(s, dst, match c.class { Class::Function(f) => f.env, _ => UNDEFINED })) + } + _ => s, + } +} + +/// The semantics of one op: the fast result when the op is core or its fast +/// path holds, and the handler's result otherwise. This is what jit.md's +/// front-end proofs (J.10) refine: per op, the lowered LIR computes +/// `fast_step` when `fast_path` holds, and exits to `op_handler(op)` +/// otherwise. +pub open spec fn step(s: State, op: Op) -> State { + if fast_path(s, op) { fast_step(s, op) } else { handler(op_handler(op), s, op) } +} + +} // verus! diff --git a/docs/ERRATA.md b/docs/ERRATA.md index edee374a3..3bacca9aa 100644 --- a/docs/ERRATA.md +++ b/docs/ERRATA.md @@ -929,3 +929,25 @@ it evidently means. Each entry records what we specified instead. columns it spans (`span_contribution` in `crates/clazel-layout/src/table/measure.rs`). - **Reported upstream:** not yet. + +## ECMA-262 Number::multiply drops the sign of a zero product with `+0` + +- **Spec:** ECMA-262, ES2026 (`tc39/ecma262` commit + `0248456c758431e4bb8e5d26333ff1865123c9cd`), §6.1.6.1.4 Number::multiply, + +- **Text:** steps 4 and 5 handle only an operand that is `-0` + ("If x is -0, then ... If y is -0, then ..."); step 6 is "Return + 𝔽(ℝ(x) × ℝ(y))", and §6.1.6.1's "the Number value for x" gives `-0` only + when x < 0 (its rule "replace +0 with -0 if and only if x < 0"). +- **Problem:** for `x = +0` and `y = -5`, steps 1 to 5 do not apply and + ℝ(x) × ℝ(y) = 0, so step 6 returns `+0`. IEEE 754, and every engine, give + `-0` (`0 * -5` is `-0`); the same holds for a negative finite `x` and + `y = +0`. The sign rule of the older text ("the sign of the result is + positive if both operands have the same sign, negative if the operands have + different signs") is what is meant. The rest of the whole `spec.html` was + searched for another place that supplies the sign of a zero product, and + none does. +- **We specify:** a zero result has the sign of the exclusive or of the + operand signs, as an added step 5a (`number_multiply` in + `crates/clazel-js-vm/src/spec.rs`). +- **Reported upstream:** not yet. diff --git a/xtask/src/status.rs b/xtask/src/status.rs index eb413c0db..717126812 100644 --- a/xtask/src/status.rs +++ b/xtask/src/status.rs @@ -72,6 +72,7 @@ const PLACES: &[(&str, Place)] = &[ ("clazel-css", Place::Renderer), ("clazel-selectors", Place::Renderer), ("clazel-js-lexer", Place::Renderer), + ("clazel-js-vm", Place::Renderer), ("clazel-style", Place::Renderer), ("clazel-font", Place::Renderer), ("clazel-layout", Place::Renderer), From 4b97386da484af1e1fca978e86f333a5cdf3affd Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Mon, 16 Nov 2026 23:18:37 +0000 Subject: [PATCH 2/4] clazel-js-vm: rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/clazel-js-vm/src/lemmas.rs | 1 - crates/clazel-js-vm/src/spec.rs | 1 - 2 files changed, 2 deletions(-) diff --git a/crates/clazel-js-vm/src/lemmas.rs b/crates/clazel-js-vm/src/lemmas.rs index b0595686c..328f81018 100644 --- a/crates/clazel-js-vm/src/lemmas.rs +++ b/crates/clazel-js-vm/src/lemmas.rs @@ -15,7 +15,6 @@ //! ordering key of `f64_key` must satisfy. //! - [`lemma_examples`]: the value of a few conversions, evaluated. - #[allow(unused_imports)] use super::spec::*; diff --git a/crates/clazel-js-vm/src/spec.rs b/crates/clazel-js-vm/src/spec.rs index 33fe327f6..2f82e2934 100644 --- a/crates/clazel-js-vm/src/spec.rs +++ b/crates/clazel-js-vm/src/spec.rs @@ -144,7 +144,6 @@ #[allow(unused_imports)] use vstd::prelude::*; - pub use crate::ops::*; verus! { From ea37614ed726ef2f5293ce5185a2abb75e3ced1e Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Tue, 17 Nov 2026 20:20:46 +0000 Subject: [PATCH 3/4] Give the bytecode VM its mutation tests (7.3) CI's proof job requires a mutations.json for every crate Verus checks. Three mutations of Number::multiply's zero signs (steps 4.b, 5.b and the step 5a erratum), each killed by lemma_multiply_zero_signs, a new lemma that evaluates the four zero-product cases. Co-Authored-By: Claude Opus 5.5 --- crates/clazel-js-vm/mutations.json | 43 ++++++++++++++++++++++++++++++ crates/clazel-js-vm/src/lemmas.rs | 18 +++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 crates/clazel-js-vm/mutations.json diff --git a/crates/clazel-js-vm/mutations.json b/crates/clazel-js-vm/mutations.json new file mode 100644 index 000000000..58c6b6fd4 --- /dev/null +++ b/crates/clazel-js-vm/mutations.json @@ -0,0 +1,43 @@ +{ + "mutations": [ + { + "id": "multiply-neg-zero-left-positive", + "file": "src/spec.rs", + "find": "else { 0x8000_0000_0000_0000 } // 4.b.", + "replace": "else { 0 } // 4.b.", + "expect": "killed", + "reason": "Returns +0 instead of -0 for `-0 × y` with y positive (§6.1.6.1.4 step 4.b): lemma_multiply_zero_signs is false.", + "certificate": { + "file": "src/lemmas.rs", + "lemma": "lemma_multiply_zero_signs()", + "witness": "number_multiply(0x8000_0000_0000_0000u64, 0x4014_0000_0000_0000u64) == 0u64" + } + }, + { + "id": "multiply-neg-zero-right-positive", + "file": "src/spec.rs", + "find": "else { 0x8000_0000_0000_0000 } // 5.b.", + "replace": "else { 0 } // 5.b.", + "expect": "killed", + "reason": "Returns +0 instead of -0 for `x × -0` with x positive (§6.1.6.1.4 step 5.b): lemma_multiply_zero_signs is false.", + "certificate": { + "file": "src/lemmas.rs", + "lemma": "lemma_multiply_zero_signs()", + "witness": "number_multiply(0x4014_0000_0000_0000u64, 0x8000_0000_0000_0000u64) == 0u64" + } + }, + { + "id": "multiply-pos-zero-ignores-sign", + "file": "src/spec.rs", + "find": "(f64_sign(x) ^ f64_sign(y)) << 63", + "replace": "0", + "expect": "killed", + "reason": "Drops the step 5a erratum's sign, so `+0 × -5` would be +0 where every engine and IEEE 754 give -0: lemma_multiply_zero_signs is false.", + "certificate": { + "file": "src/lemmas.rs", + "lemma": "lemma_multiply_zero_signs()", + "witness": "number_multiply(0u64, 0xC014_0000_0000_0000u64) == 0u64" + } + } + ] +} diff --git a/crates/clazel-js-vm/src/lemmas.rs b/crates/clazel-js-vm/src/lemmas.rs index 328f81018..db21d2818 100644 --- a/crates/clazel-js-vm/src/lemmas.rs +++ b/crates/clazel-js-vm/src/lemmas.rs @@ -14,6 +14,8 @@ //! properties the standard implies of Number comparison, which the integer //! ordering key of `f64_key` must satisfy. //! - [`lemma_examples`]: the value of a few conversions, evaluated. +//! - [`lemma_multiply_zero_signs`]: the sign of a zero product, evaluated +//! (steps 4 and 5 and the step 5a erratum of Number::multiply). #[allow(unused_imports)] use super::spec::*; @@ -427,4 +429,20 @@ pub proof fn lemma_examples() assert(to_uint32(0xBFF0_0000_0000_0000u64) == 4294967295u32); } +/// The sign of a zero product, §6.1.6.1.4: `-0 × 5` is `-0` (step 4.b), +/// `5 × -0` is `-0` (step 5.b), `-0 × -5` is `+0` (step 4.a), and `+0 × -5` +/// is `-0` (the step 5a erratum, docs/ERRATA.md). +pub proof fn lemma_multiply_zero_signs() + ensures + number_multiply(0x8000_0000_0000_0000u64, 0x4014_0000_0000_0000u64) == 0x8000_0000_0000_0000u64, + number_multiply(0x4014_0000_0000_0000u64, 0x8000_0000_0000_0000u64) == 0x8000_0000_0000_0000u64, + number_multiply(0x8000_0000_0000_0000u64, 0xC014_0000_0000_0000u64) == 0u64, + number_multiply(0u64, 0xC014_0000_0000_0000u64) == 0x8000_0000_0000_0000u64, +{ + assert(number_multiply(0x8000_0000_0000_0000u64, 0x4014_0000_0000_0000u64) == 0x8000_0000_0000_0000u64) by (compute_only); + assert(number_multiply(0x4014_0000_0000_0000u64, 0x8000_0000_0000_0000u64) == 0x8000_0000_0000_0000u64) by (compute_only); + assert(number_multiply(0x8000_0000_0000_0000u64, 0xC014_0000_0000_0000u64) == 0u64) by (compute_only); + assert(number_multiply(0u64, 0xC014_0000_0000_0000u64) == 0x8000_0000_0000_0000u64) by (compute_only); +} + } // verus! From 16321bf9cf1c136e6c5df2b64b5284b9a1999fd3 Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Wed, 18 Nov 2026 13:35:17 +0000 Subject: [PATCH 4/4] Evaluate the VM's zero-product example outside its lemmas (7.3) The mutation tool checks a kill certificate in its own module, and Verus evaluates every compute_only assert of that module first. The zero-product lemma evaluated in lemmas.rs, so each mutant would stop Verus before its certificate ran. It moves to examples.rs, as in clazel-base64, and the certificates call it from there. Co-Authored-By: Claude Opus 5.5 --- crates/clazel-js-vm/mutations.json | 12 +++++------ crates/clazel-js-vm/src/examples.rs | 32 +++++++++++++++++++++++++++++ crates/clazel-js-vm/src/lemmas.rs | 18 ---------------- crates/clazel-js-vm/src/lib.rs | 2 ++ 4 files changed, 40 insertions(+), 24 deletions(-) create mode 100644 crates/clazel-js-vm/src/examples.rs diff --git a/crates/clazel-js-vm/mutations.json b/crates/clazel-js-vm/mutations.json index 58c6b6fd4..68a32350c 100644 --- a/crates/clazel-js-vm/mutations.json +++ b/crates/clazel-js-vm/mutations.json @@ -6,10 +6,10 @@ "find": "else { 0x8000_0000_0000_0000 } // 4.b.", "replace": "else { 0 } // 4.b.", "expect": "killed", - "reason": "Returns +0 instead of -0 for `-0 × y` with y positive (§6.1.6.1.4 step 4.b): lemma_multiply_zero_signs is false.", + "reason": "Returns +0 instead of -0 for `-0 × y` with y positive (§6.1.6.1.4 step 4.b): example_multiply_zero_signs is false.", "certificate": { "file": "src/lemmas.rs", - "lemma": "lemma_multiply_zero_signs()", + "lemma": "crate::examples::example_multiply_zero_signs()", "witness": "number_multiply(0x8000_0000_0000_0000u64, 0x4014_0000_0000_0000u64) == 0u64" } }, @@ -19,10 +19,10 @@ "find": "else { 0x8000_0000_0000_0000 } // 5.b.", "replace": "else { 0 } // 5.b.", "expect": "killed", - "reason": "Returns +0 instead of -0 for `x × -0` with x positive (§6.1.6.1.4 step 5.b): lemma_multiply_zero_signs is false.", + "reason": "Returns +0 instead of -0 for `x × -0` with x positive (§6.1.6.1.4 step 5.b): example_multiply_zero_signs is false.", "certificate": { "file": "src/lemmas.rs", - "lemma": "lemma_multiply_zero_signs()", + "lemma": "crate::examples::example_multiply_zero_signs()", "witness": "number_multiply(0x4014_0000_0000_0000u64, 0x8000_0000_0000_0000u64) == 0u64" } }, @@ -32,10 +32,10 @@ "find": "(f64_sign(x) ^ f64_sign(y)) << 63", "replace": "0", "expect": "killed", - "reason": "Drops the step 5a erratum's sign, so `+0 × -5` would be +0 where every engine and IEEE 754 give -0: lemma_multiply_zero_signs is false.", + "reason": "Drops the step 5a erratum's sign, so `+0 × -5` would be +0 where every engine and IEEE 754 give -0: example_multiply_zero_signs is false.", "certificate": { "file": "src/lemmas.rs", - "lemma": "lemma_multiply_zero_signs()", + "lemma": "crate::examples::example_multiply_zero_signs()", "witness": "number_multiply(0u64, 0xC014_0000_0000_0000u64) == 0u64" } } diff --git a/crates/clazel-js-vm/src/examples.rs b/crates/clazel-js-vm/src/examples.rs new file mode 100644 index 000000000..a3f79f29a --- /dev/null +++ b/crates/clazel-js-vm/src/examples.rs @@ -0,0 +1,32 @@ +//! The standard's results, evaluated on the spec with `compute_only`. Kept +//! apart from [`super::lemmas`] so that a mutant that breaks one of them does +//! not stop Verus before it checks a kill certificate there +//! (`mutations.json`). +//! +//! - [`example_multiply_zero_signs`]: the sign of a zero product (steps 4 +//! and 5 and the step 5a erratum of Number::multiply). + +#[allow(unused_imports)] +use super::spec::*; +#[allow(unused_imports)] +use vstd::prelude::*; + +verus! { + +/// The sign of a zero product, §6.1.6.1.4: `-0 × 5` is `-0` (step 4.b), +/// `5 × -0` is `-0` (step 5.b), `-0 × -5` is `+0` (step 4.a), and `+0 × -5` +/// is `-0` (the step 5a erratum, docs/ERRATA.md). +pub proof fn example_multiply_zero_signs() + ensures + number_multiply(0x8000_0000_0000_0000u64, 0x4014_0000_0000_0000u64) == 0x8000_0000_0000_0000u64, + number_multiply(0x4014_0000_0000_0000u64, 0x8000_0000_0000_0000u64) == 0x8000_0000_0000_0000u64, + number_multiply(0x8000_0000_0000_0000u64, 0xC014_0000_0000_0000u64) == 0u64, + number_multiply(0u64, 0xC014_0000_0000_0000u64) == 0x8000_0000_0000_0000u64, +{ + assert(number_multiply(0x8000_0000_0000_0000u64, 0x4014_0000_0000_0000u64) == 0x8000_0000_0000_0000u64) by (compute_only); + assert(number_multiply(0x4014_0000_0000_0000u64, 0x8000_0000_0000_0000u64) == 0x8000_0000_0000_0000u64) by (compute_only); + assert(number_multiply(0x8000_0000_0000_0000u64, 0xC014_0000_0000_0000u64) == 0u64) by (compute_only); + assert(number_multiply(0u64, 0xC014_0000_0000_0000u64) == 0x8000_0000_0000_0000u64) by (compute_only); +} + +} // verus! diff --git a/crates/clazel-js-vm/src/lemmas.rs b/crates/clazel-js-vm/src/lemmas.rs index db21d2818..328f81018 100644 --- a/crates/clazel-js-vm/src/lemmas.rs +++ b/crates/clazel-js-vm/src/lemmas.rs @@ -14,8 +14,6 @@ //! properties the standard implies of Number comparison, which the integer //! ordering key of `f64_key` must satisfy. //! - [`lemma_examples`]: the value of a few conversions, evaluated. -//! - [`lemma_multiply_zero_signs`]: the sign of a zero product, evaluated -//! (steps 4 and 5 and the step 5a erratum of Number::multiply). #[allow(unused_imports)] use super::spec::*; @@ -429,20 +427,4 @@ pub proof fn lemma_examples() assert(to_uint32(0xBFF0_0000_0000_0000u64) == 4294967295u32); } -/// The sign of a zero product, §6.1.6.1.4: `-0 × 5` is `-0` (step 4.b), -/// `5 × -0` is `-0` (step 5.b), `-0 × -5` is `+0` (step 4.a), and `+0 × -5` -/// is `-0` (the step 5a erratum, docs/ERRATA.md). -pub proof fn lemma_multiply_zero_signs() - ensures - number_multiply(0x8000_0000_0000_0000u64, 0x4014_0000_0000_0000u64) == 0x8000_0000_0000_0000u64, - number_multiply(0x4014_0000_0000_0000u64, 0x8000_0000_0000_0000u64) == 0x8000_0000_0000_0000u64, - number_multiply(0x8000_0000_0000_0000u64, 0xC014_0000_0000_0000u64) == 0u64, - number_multiply(0u64, 0xC014_0000_0000_0000u64) == 0x8000_0000_0000_0000u64, -{ - assert(number_multiply(0x8000_0000_0000_0000u64, 0x4014_0000_0000_0000u64) == 0x8000_0000_0000_0000u64) by (compute_only); - assert(number_multiply(0x4014_0000_0000_0000u64, 0x8000_0000_0000_0000u64) == 0x8000_0000_0000_0000u64) by (compute_only); - assert(number_multiply(0x8000_0000_0000_0000u64, 0xC014_0000_0000_0000u64) == 0u64) by (compute_only); - assert(number_multiply(0u64, 0xC014_0000_0000_0000u64) == 0x8000_0000_0000_0000u64) by (compute_only); -} - } // verus! diff --git a/crates/clazel-js-vm/src/lib.rs b/crates/clazel-js-vm/src/lib.rs index 30e5e1e71..f4ff16a5a 100644 --- a/crates/clazel-js-vm/src/lib.rs +++ b/crates/clazel-js-vm/src/lib.rs @@ -6,6 +6,7 @@ //! guarded or handler) and the handler an op calls out to; //! - [`spec`]: NaN-boxed values, ECMA-262's Number operations on bit //! patterns, the abstract machine, and `spec fn step`; +//! - [`examples`]: the standard's results, evaluated on the spec; //! - [`lemmas`]: facts proven about the spec (the value encoding round-trips, //! the op classes mean what they say, core ops keep the machine well-formed). //! @@ -16,6 +17,7 @@ //! Tier: see `[package.metadata.clazel]` in `Cargo.toml` and //! `docs/VERIFICATION.md`. +pub mod examples; pub mod lemmas; pub mod ops; pub mod spec;