Merge pull request #9109 from dotCooCoo/feat/js-es2020-optional-chaining-nullish

Scripts: .js scripts read optional chains and the ?? operator
This commit is contained in:
BFlat authored and GitHub committed 2026-11-24 16:09:45 +07:00
commit 11a26acb0b
14 files changed
+711 -39

No files matched your search

+23
View File
@@ -331,6 +331,29 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() {
let dir = fresh_folder("es2020");
let write = |name: &str, text: &str| {
let p = dir.join(name);
std::fs::write(&p, text).unwrap();
p.to_string_lossy().into_owned()
};
let mut s = two_docs();
let path = |p: &str| json!({"path": p});
let modern = "var o = { a: { f: function () { return this.n; }, n: 3 } }, none = null;\n\
vc.log(none?.a.b ?? 'none');\nvc.log(o.a?.f());\nvc.log(0 ?? 1);\nvc.log(eval('none?.[0] ?? 2'));\n";
let r = s.execute("script.run", &path(&write("modern.js", modern))).unwrap();
assert_eq!(r["log"], json!(["none", 3, 0, 2]), "{r}");
for (name, text) in [("chain.jsx", "var o; vc.log(o?.a);"), ("coalesce.jsx", "vc.log(null ?? 1);"), ("mixed.js", "vc.log(1 || 2 ?? 3);")] {
let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string();
assert!(e.contains("SyntaxError"), "{name}: {e}");
}
// Script text given without a file keeps the ExtendScript language.
assert!(run(&mut s, "vc.log(null ?? 1);").unwrap_err().to_string().contains("SyntaxError"));
let _ = std::fs::remove_dir_all(&dir);
}
/// A new empty folder for test `name`.
fn fresh_folder(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id()));
+8
View File
@@ -69,6 +69,8 @@ pub enum BinaryOp {
pub enum LogicalOp {
And,
Or,
/// `??`: the right side only when the left is `undefined` or `null`.
Coalesce,
}
/// `=` (`None`) or a compound assignment's operator (`+=` is `Some(BinaryOp::Add)`).
@@ -218,6 +220,12 @@ pub enum Expr {
/// `...expression` in an array literal or an argument list, and as the last of an arrow
/// function's parenthesized parameters while they are read.
Spread(ExprId),
/// An optional chain (`a?.b.c`, `a?.[k]`, `f?.()`): its accesses and calls, the
/// [`Expr::Optional`] steps among them included. It is `undefined` when one of those steps
/// finds `undefined` or `null`, and the rest of the chain is skipped.
OptionalChain(ExprId),
/// The object or function before `?.` in an [`Expr::OptionalChain`].
Optional(ExprId),
}
/// A piece of a template literal's text between its substitutions.
+12 -1
View File
@@ -105,6 +105,15 @@ pub(crate) enum Op {
/// Jumps, keeping the top value, when it is falsy; otherwise pops it.
JumpIfFalseKeep(u32),
JumpIfTrueKeep(u32),
/// Jumps, keeping the top value, when it is neither `undefined` nor `null`; otherwise pops
/// it (`??`).
JumpIfNotNullishKeep(u32),
/// When the top value is `undefined` or `null`, pops `drop` values (the top one among them)
/// and jumps; otherwise goes on with the stack as it was (a step of an optional chain).
JumpIfNullish {
target: u32,
drop: u32,
},
Return,
/// Returns the value of the last expression statement (script and eval code).
ReturnCompletion,
@@ -360,7 +369,9 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
Op::PopEnv => e(0, 0),
Op::Jump(t) => Effect { pops: 0, next: None, jumps: vec![(t, 0)] },
Op::JumpIfFalse(t) | Op::JumpIfTrue(t) => Effect { pops: 1, next: Some(0), jumps: vec![(t, 0)] },
Op::JumpIfFalseKeep(t) | Op::JumpIfTrueKeep(t) => Effect { pops: 1, next: Some(0), jumps: vec![(t, 1)] },
Op::JumpIfFalseKeep(t) | Op::JumpIfTrueKeep(t) | Op::JumpIfNotNullishKeep(t) => Effect { pops: 1, next: Some(0), jumps: vec![(t, 1)] },
Op::JumpIfNullish { drop: 0, .. } => return Err("a nullish jump that drops no values".into()),
Op::JumpIfNullish { target, drop } => Effect { pops: drop, next: Some(drop), jumps: vec![(target, 0)] },
Op::Return | Op::Throw => end(1),
Op::ReturnCompletion | Op::ThrowReferenceError(_) => end(0),
Op::EndFinally(t) => {
+128 -20
View File
@@ -99,6 +99,9 @@ struct FnCompiler<'a> {
block_funcs: HashSet<StmtId>,
/// The function declarations in blocks whose names are also var-scoped (Annex B.3.3).
annex: HashSet<StmtId>,
/// The optional chains being compiled, innermost last: where a step that finds `undefined`
/// or `null` jumps, and the stack depth the chain started at.
optional: Vec<(Label, u32)>,
}
/// The `var` names and function declarations a body hoists.
@@ -146,6 +149,7 @@ impl<'a> FnCompiler<'a> {
top_funcs: HashSet::new(),
block_funcs: HashSet::new(),
annex: HashSet::new(),
optional: Vec::new(),
}
}
@@ -1237,6 +1241,12 @@ impl<'a> FnCompiler<'a> {
self.emit(Op::XmlScopeGet);
}
Expr::XmlDescendants { .. } | Expr::XmlFilter { .. } => self.chain(id)?,
Expr::OptionalChain(inner) => self.optional_chain(*inner, false)?,
Expr::Optional(object) => {
self.expr(*object)?;
self.at(self.ast.expr_span(id).end);
self.nullish_check()?;
}
}
Ok(())
}
@@ -1405,53 +1415,95 @@ impl<'a> FnCompiler<'a> {
/// A run of member accesses and calls (`a.b[c](d).e`), compiled from the innermost object out
/// with a loop.
fn chain(&mut self, id: ExprId) -> CResult<()> {
let mut suffixes = Vec::new();
self.chain_with(id, false)
}
/// [`Self::chain`]; with `keep_this` it leaves `value this`, the object of its last access as
/// a call's `this` (or `undefined` when it ends with something else). An [`Expr::Optional`]
/// step jumps out of the innermost optional chain being compiled.
fn chain_with(&mut self, id: ExprId, keep_this: bool) -> CResult<()> {
/// A suffix, or an optional step's check of the value before it.
#[derive(Clone, Copy)]
enum Link {
Suffix(ExprId),
Check(ExprId),
}
let mut links = Vec::new();
let mut cur = id;
loop {
match self.ast.expr(cur) {
Some(
Expr::Member { object, .. } | Expr::Index { object, .. } | Expr::XmlDescendants { object, .. } | Expr::XmlFilter { object, .. },
) => {
suffixes.push(cur);
links.push(Link::Suffix(cur));
cur = self.ast.unparenthesized(*object);
}
Some(Expr::Call { callee, .. } | Expr::TaggedTemplate { tag: callee, .. }) => {
suffixes.push(cur);
links.push(Link::Suffix(cur));
cur = self.ast.unparenthesized(*callee);
}
Some(Expr::Optional(object)) => {
links.push(Link::Check(cur));
cur = self.ast.unparenthesized(*object);
}
_ => break,
}
}
let is_call =
|c: &Self, e: Option<&ExprId>| e.is_some_and(|&e| matches!(c.ast.expr(e), Some(Expr::Call { .. } | Expr::TaggedTemplate { .. })));
let first_is_call = is_call(self, suffixes.last());
let mut base_has_this = false;
let is_call = |c: &Self, link: Option<&Link>| matches!(link, Some(Link::Suffix(e)) if matches!(c.ast.expr(*e), Some(Expr::Call { .. } | Expr::TaggedTemplate { .. })));
// The first suffix after the base, and for each link the next suffix out from it, with
// the checks between them skipped.
let first_is_call = is_call(self, links.iter().rev().find(|l| matches!(l, Link::Suffix(_))));
let mut receiver = false;
let mut eval_call = false;
match self.ast.expr(cur) {
Some(Expr::Ident(name)) if first_is_call => {
self.at(self.ast.expr_span(cur).start);
let n = self.var_name(name);
self.emit(Op::GetVarThis(n));
base_has_this = true;
receiver = true;
eval_call = name == "eval";
}
Some(Expr::OptionalChain(inner)) if first_is_call => {
self.optional_chain(*inner, true)?;
receiver = true;
}
_ => self.expr(cur)?,
}
let count = suffixes.len();
let count = links.len();
for j in (0..count).rev() {
let Some(&s) = suffixes.get(j) else { return internal("suffix out of range") };
let next_is_call = j > 0 && is_call(self, suffixes.get(j - 1));
let s = match links.get(j) {
Some(&Link::Suffix(s)) => s,
Some(&Link::Check(c)) => {
eval_call = false;
self.at(self.ast.expr_span(c).end);
if receiver {
self.emit(Op::Swap);
self.nullish_check()?;
self.emit(Op::Swap);
} else {
self.nullish_check()?;
}
continue;
}
None => return internal("suffix out of range"),
};
let next = links.get(..j).and_then(|outer| outer.iter().rev().find(|l| matches!(l, Link::Suffix(_))));
let next_is_call = if next.is_some() { is_call(self, next) } else { keep_this };
let span = self.ast.expr_span(s);
let eval = std::mem::take(&mut eval_call);
let had_receiver = std::mem::take(&mut receiver);
match self.ast.expr(s) {
Some(Expr::Member { property, .. }) => {
self.at(span.start);
let n = self.name_key(key_of(&property.name));
self.emit(if next_is_call { Op::GetMemberThis(n) } else { Op::GetMember(n) });
receiver = next_is_call;
}
Some(Expr::Index { index, .. }) => {
self.expr(*index)?;
self.at(span.start);
self.emit(if next_is_call { Op::GetIndexThis } else { Op::GetIndex });
receiver = next_is_call;
}
Some(Expr::XmlDescendants { name, .. }) => {
self.expr(*name)?;
@@ -1463,13 +1515,7 @@ impl<'a> FnCompiler<'a> {
self.xml_filter(*predicate)?;
}
Some(call @ (Expr::Call { .. } | Expr::TaggedTemplate { .. })) => {
let innermost = j + 1 == count;
let has_this = if innermost {
base_has_this
} else {
matches!(suffixes.get(j + 1).and_then(|&e| self.ast.expr(e)), Some(Expr::Member { .. } | Expr::Index { .. }))
};
if !has_this {
if !had_receiver {
self.emit(Op::Undefined);
}
let eval = match call {
@@ -1483,7 +1529,6 @@ impl<'a> FnCompiler<'a> {
continue;
}
Expr::Call { args, .. } => {
let eval = innermost && eval_call;
if eval {
self.uses_arguments = true;
self.uses_this = true;
@@ -1508,6 +1553,43 @@ impl<'a> FnCompiler<'a> {
_ => return internal("not a member or call"),
}
}
if keep_this && !receiver {
self.emit(Op::Undefined);
}
Ok(())
}
/// An optional chain: its links, with each `?.` step jumping to its end when it finds
/// `undefined` or `null`, the result then `undefined` (`undefined undefined` with
/// `keep_this`, for a call of the chain in parentheses).
fn optional_chain(&mut self, inner: ExprId, keep_this: bool) -> CResult<()> {
self.enter()?;
let short = self.new_label();
let end = self.new_label();
let entry = self.depth;
self.optional.push((short, entry));
let r = self.chain_with(self.ast.unparenthesized(inner), keep_this);
self.optional.pop();
self.leave();
r?;
self.jump(Op::Jump, end);
self.bind(short);
self.depth = entry;
self.emit(Op::Undefined);
if keep_this {
self.emit(Op::Undefined);
}
self.bind(end);
Ok(())
}
/// An optional step: jumps to the end of the innermost optional chain, dropping what the
/// chain has pushed, when the value on top is `undefined` or `null`.
fn nullish_check(&mut self) -> CResult<()> {
let Some(&(label, entry)) = self.optional.last() else { return internal("an optional step outside its chain") };
let Some(drop) = self.depth.checked_sub(entry).filter(|&d| d > 0) else { return internal("an optional step without a value") };
self.patches.push((self.ops.len(), label));
self.emit(Op::JumpIfNullish { target: 0, drop });
Ok(())
}
@@ -1576,6 +1658,23 @@ impl<'a> FnCompiler<'a> {
self.xml_scope_ref(arg, *name)?;
self.emit(Op::DeleteIndex);
}
// `delete a?.b` is true without deleting anything when the chain stops at a `?.` step.
Some(Expr::OptionalChain(inner))
if matches!(self.ast.expr(self.ast.unparenthesized(*inner)), Some(Expr::Member { .. } | Expr::Index { .. })) =>
{
let short = self.new_label();
let end = self.new_label();
let entry = self.depth;
self.optional.push((short, entry));
let r = self.delete_expr(*inner);
self.optional.pop();
r?;
self.jump(Op::Jump, end);
self.bind(short);
self.depth = entry;
self.emit(Op::True);
self.bind(end);
}
_ => {
self.expr(arg)?;
self.emit(Op::Pop);
@@ -1617,7 +1716,14 @@ impl<'a> FnCompiler<'a> {
}
Step::Logical(op) => {
let end = self.new_label();
self.jump(if op == LogicalOp::And { Op::JumpIfFalseKeep } else { Op::JumpIfTrueKeep }, end);
self.jump(
match op {
LogicalOp::And => Op::JumpIfFalseKeep,
LogicalOp::Or => Op::JumpIfTrueKeep,
LogicalOp::Coalesce => Op::JumpIfNotNullishKeep,
},
end,
);
self.expr(right)?;
self.bind(end);
}
@@ -1759,6 +1865,8 @@ impl<'a> FnCompiler<'a> {
| Op::JumpIfTrue(t)
| Op::JumpIfFalseKeep(t)
| Op::JumpIfTrueKeep(t)
| Op::JumpIfNotNullishKeep(t)
| Op::JumpIfNullish { target: t, .. }
| Op::ForInNext(t)
| Op::XmlFilterNext(t),
) => *t = target,
+122
View File
@@ -170,6 +170,33 @@ fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() {
assert!(restricted.is_err(), "{restricted:?}");
}
#[test]
fn a_script_stopped_at_the_heap_limit_declares_no_global_lexical_name() {
// The `let` names and the variables each fit in the heap at some limits, but not together.
// A run that stops at the heap limit adds none of the names, so the same script runs once the
// limit is raised.
let names = |prefix: &str| (0..100).map(|i| format!("{prefix}{i:0>60}")).collect::<Vec<_>>().join(", ");
let src = format!("let {} = 1; var {}; 0", names("l"), names("v"));
let mut measure = Realm::with_options(es_options(), Limits::default());
measure.interp().collect_garbage();
let base = measure.interp().heap.bytes;
let mut stopped = 0;
for extra in (0..200).map(|k| k * 512) {
let heap_bytes = base + extra;
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() });
match realm.run(&src) {
Ok(v) => assert_eq!(v, JsValue::Number(0.0), "{heap_bytes}"),
Err(e) => {
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{heap_bytes}: {e:?}");
stopped += 1;
realm.set_limits(Limits::default());
assert_eq!(realm.run(&src), Ok(JsValue::Number(0.0)), "{heap_bytes}: run again");
}
}
}
assert!(stopped > 0, "no limit stopped the script");
}
#[test]
fn functions_from_earlier_runs_see_later_global_lexical_bindings() {
let mut realm = Realm::new();
@@ -313,6 +340,50 @@ fn eval_code_keeps_its_let_and_const_to_itself() {
truth("let a; try { eval('var b; var a;'); } catch (e) {} typeof b === 'undefined'");
}
#[test]
fn eval_code_keeps_its_environments_through_collections() {
// With a collection on every heap reservation, eval code's own environment and the scope of
// its `let` and `const` names stay while its declarations are made: the scope of a function
// the code declares leads out to the global scope without coming back to itself.
use crate::heap::{Class, Env, Func, key};
use crate::value::Value;
let cases = [
("function g() { var o = 1; return eval(\"'use strict'; let x = 2; var y = 3; function f() { return x + y + o; } f\"); }", 6.0),
("function g() { return (0, eval)(\"'use strict'; let x = 5; var y = 6; function f() { return x + y; } f\"); }", 11.0),
("function g() { return (0, eval)(\"let x = 7; function f() { return x; } f\"); }", 7.0),
];
for (setup, want) in cases {
let mut realm = es();
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true));
let made = realm.run(&format!("{setup} var f = g(); 0"));
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false));
assert_eq!(made, Ok(JsValue::Number(0.0)), "{setup}");
let interp = realm.interp();
let global = interp.global;
let f = match interp.get_from(global, &key("f"), &Value::Object(global)) {
Ok(Value::Object(f)) => f,
other => panic!("{setup}: {other:?}"),
};
let mut cur = match interp.heap.object(f).map(|o| &o.class) {
Some(Class::Function(Func::Closure { env, .. })) => Some(*env),
_ => panic!("{setup}: not a closure"),
};
let mut seen = std::collections::HashSet::new();
while let Some(e) = cur {
assert!(seen.insert(e), "{setup}: the scope chain comes back to {e:?}");
if e == interp.global_lex {
break;
}
cur = match interp.heap.env(e) {
Some(Env::Decl { outer, .. } | Env::Obj { outer, .. }) => *outer,
None => panic!("{setup}: {e:?} was freed"),
};
}
assert_eq!(cur, Some(interp.global_lex), "{setup}");
assert_eq!(realm.run("f()"), Ok(JsValue::Number(want)), "{setup}");
}
}
// ---- arrow functions ----
#[test]
@@ -535,6 +606,22 @@ fn an_index_setter_without_a_getter_does_not_delay_the_spread_s_check() {
}
}
#[test]
fn a_prototype_getter_behind_an_own_element_does_not_delay_the_spread_s_check() {
// The array's own element 0 is read instead of the getter on its prototype, so no getter can
// shrink it, and it is checked when spread begins.
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
let src = "var a = [7]; Object.defineProperty(Array.prototype, 0, { get: function () { a.length = 1; return 0; } }); \
a.length = 4294967295; [...a]";
let long = realm.run(src);
assert!(is_thrown(&long, "RangeError"), "{long:?}");
// A getter on the prototype with no own element in front of it is read, and shrinks the array.
let shrink = "var a = []; a.length = 4294967295; \
Object.defineProperty(Array.prototype, 0, { get: function () { a.length = 1; return 7; } }); \
var b = [...a]; b.length === 1 && b[0] === 7";
truth(shrink);
}
#[test]
fn looking_for_index_getters_takes_fuel_for_each_property() {
// Each attempt to spread the long array looks at every one of its 10,000 elements, so each
@@ -576,6 +663,41 @@ fn spread_counts_each_index_name_against_the_heap() {
}
}
#[test]
fn spread_stops_at_the_heap_limit_before_the_next_step_runs() {
// With room for about half the elements, the spread stops with the heap limit while it reads
// them. Each run's fuel ends somewhere in the steps just after the spread, so a check made
// only at the next step would end the run for lack of fuel first, with the elements over the
// limit until a collection.
for spread in ["[...a]", "[...s]"] {
let setup = "var a = Array(4000); var s = new Array(4001).join('x'); 0";
let run = format!("var b = {spread}; 0");
let mut measure = Realm::with_options(es_options(), Limits::default());
assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0)));
measure.interp().collect_garbage();
let base = measure.interp().heap.bytes;
assert_eq!(measure.run(&run), Ok(JsValue::Number(0.0)));
let fuel = Limits::default().fuel - measure.interp().fuel;
measure.interp().collect_garbage();
let need = measure.interp().heap.bytes - base;
let heap_bytes = base + need / 2;
for f in fuel.saturating_sub(40).max(1)..=fuel {
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() });
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)), "{spread}");
realm.interp().collect_garbage();
realm.set_limits(Limits { heap_bytes, fuel: f, ..Limits::default() });
let e = realm.run(&run).unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{spread} at fuel {f}: {e:?}");
let bytes = realm.interp().settled_heap_bytes();
assert!(bytes <= heap_bytes, "{spread} at fuel {f}: {bytes} > {heap_bytes}");
}
// With room for twice the elements, the spread completes.
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes: base + need * 2, ..Limits::default() });
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)), "{spread}");
assert_eq!(realm.run(&format!("var b = {spread}; b.length")), Ok(JsValue::Number(4000.0)), "{spread}");
}
}
#[test]
fn spreading_other_values_is_a_type_error() {
throws("[...1];", "TypeError");
+222
View File
@@ -0,0 +1,222 @@
use proptest::prelude::*;
use crate::{JsValue, Limits, Options, Realm, RunError, RunErrorKind};
fn es_options() -> Options {
Options { es2015: true, ..Options::default() }
}
fn es() -> Realm {
Realm::with_options(es_options(), Limits::default())
}
fn truth(src: &str) {
assert_eq!(es().run(src), Ok(JsValue::Bool(true)), "{src}");
}
/// The script throws an error whose message starts with `name`.
fn throws(src: &str, name: &str) {
match es().run(src) {
Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"),
other => panic!("{src}: {other:?}"),
}
}
/// The script does not parse.
fn syntax(src: &str) {
match es().run(src) {
Err(RunError { kind: RunErrorKind::Syntax, .. }) => {}
other => panic!("{src}: {other:?}"),
}
}
// ---- optional chains ----
#[test]
fn an_optional_chain_stops_at_undefined_or_null() {
truth("var a = null; a?.b.c === undefined");
truth("var a; a?.b === undefined && a?.[x] === undefined && a?.() === undefined && a?.b.c(d).e === undefined");
truth("var o = { b: { c: 1 } }; o?.b.c === 1 && o.b?.c === 1 && o?.['b']?.c === 1 && o.x?.c === undefined");
// Values that are falsy but neither undefined nor null go on.
truth("(0)?.toFixed(1) === '0.0' && ''?.length === 0 && false?.toString() === 'false'");
// A short circuit skips every key and argument of the rest of the chain.
truth("var n = 0, a = null; a?.[n++]; a?.b(n++); a?.b[n++].c(n++); a?.b?.[n++]; n === 0");
// The base is evaluated once.
truth("var n = 0; function f() { n++; return { b: 2 }; } f()?.b === 2 && n === 1");
}
#[test]
fn only_an_optional_step_skips_the_rest() {
// Parentheses end the chain.
throws("var a = null; (a?.b).c", "TypeError");
// A plain access after a step that found a value still throws on undefined.
throws("var a = {}; a?.b.c", "TypeError");
throws("var a = {}; a?.b()", "TypeError");
// A chain inside a key or an argument is a chain of its own.
truth("var o = { u: 3 }, k = null; o?.[k?.x ?? 'u'] === 3");
}
#[test]
fn an_optional_call_keeps_its_this() {
let o = "var o = { v: 7, f: function () { return this.v; } };";
for call in ["o?.f()", "o.f?.()", "o?.f?.()", "(o?.f)()", "(o.f)?.()", "(o?.f)?.()", "o?.['f']()", "o['f']?.()"] {
truth(&format!("{o} {call} === 7"));
}
truth(&format!("{o} o.g?.() === undefined && o?.g?.(x) === undefined"));
throws("var o = { g: 1 }; o.g?.()", "TypeError");
truth("function h() { return this; } h?.() === this");
truth("var r = []; var f = function (a, b) { r.push(a, b); return r.length; }; f?.(1, 2) === 2 && r[1] === 2");
}
#[test]
fn an_optional_call_of_eval_is_an_indirect_eval() {
truth("var x = 'global'; function f() { var x = 'local'; return eval('x') + ' ' + eval?.('x'); } f() === 'local global'");
}
#[test]
fn delete_of_an_optional_chain() {
truth("var a = null, n = 0; delete a?.b === true && delete a?.[n++] === true && n === 0");
truth("var o = { b: 1, c: 2 }; delete o?.b && delete o?.['c'] && !('b' in o) && !('c' in o)");
throws("'use strict'; var o = {}; Object.defineProperty(o, 'b', { value: 1 }); delete o?.b", "TypeError");
truth("var o = {}; Object.defineProperty(o, 'b', { value: 1 }); delete o?.b === false");
}
#[test]
fn optional_chains_where_new_and_tags_can_use_them() {
truth("function F() { this.v = 2; } new F()?.v === 2");
truth("var o = { F: function () { this.v = 3; } }; new (o?.F)().v === 3");
truth("var o = { t: function (s) { return s[0]; } }; (o?.t)`x` === 'x'");
}
#[test]
fn a_question_mark_before_a_number_is_a_conditional() {
truth("var a = true; (a?.5:1) === 0.5");
truth("var a = false; (a?.5:1) === 1");
truth("var a = true; (a ?.5 : 1) === 0.5");
}
#[test]
fn an_optional_chain_cannot_be_assigned_constructed_or_tagged() {
for src in [
"a?.b = 1",
"a?.b += 1",
"a?.[0] = 1",
"(a?.b) = 1",
"a?.b++",
"--a?.b",
"for (a?.b in {}) {}",
"a?.b`x`",
"a?.b\n`x`",
"a?.`x`",
"new a?.b()",
"new a?.()",
"a?.",
"a?.1",
] {
syntax(src);
}
}
#[test]
fn a_long_chain_and_deep_parentheses_are_bounded() {
let src = format!("var o = {{}}; o.o = o; o{} === o", "?.o".repeat(20_000));
truth(&src);
syntax(&format!("var a; {}a?.b{}", "(".repeat(500), ")".repeat(500)));
}
// ---- nullish coalescing ----
#[test]
fn coalesce_takes_the_right_side_only_for_undefined_or_null() {
truth("(0 ?? 1) === 0 && (false ?? 1) === false && ('' ?? 1) === '' && isNaN(NaN ?? 1)");
truth("(null ?? 1) === 1 && (undefined ?? 2) === 2 && (void 0 ?? null) === null");
truth("var n = 0; 1 ?? n++; null ?? n++; n === 1");
truth("(null ?? undefined ?? 3) === 3 && (null ?? 4 ?? 5) === 4");
truth("var o = {}; (o.x ?? 'd') === 'd' && (o?.x?.y ?? 'e') === 'e'");
}
#[test]
fn coalesce_binds_looser_than_bitwise_and_tighter_than_the_conditional() {
truth("(1 ?? 2 | 4) === 1");
truth("(1 ?? 0 ? 'a' : 'b') === 'a'");
truth("var x = null ?? 7, y = 1 ?? 8; x === 7 && y === 1");
truth("((null || 1) ?? 2) === 1 && (null ?? (0 && 1)) === 0 && ((0 ?? 1) || 2) === 2 && ((null && 1) ?? 2) === 2");
}
#[test]
fn coalesce_mixed_with_and_or_or_needs_parentheses() {
for src in ["a || b ?? c", "a ?? b || c", "a && b ?? c", "a ?? b && c", "a ?? b ?? c || d", "a ??= 1", "a ?? "] {
syntax(src);
}
}
// ---- the language mode ----
#[test]
fn es5_and_extendscript_realms_do_not_read_the_new_operators() {
let legacy = [Options::default(), Options { e4x: true, preprocessor_lines: true, ..Options::default() }];
for options in legacy {
for src in ["var a; a?.b", "var a; a?.[0]", "var f; f?.()", "null ?? 1"] {
let r = Realm::with_options(options.clone(), Limits::default()).run(src);
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Syntax, .. })), "{src}: {r:?}");
}
// The conditional with a number after `?` reads as it always has.
let r = Realm::with_options(options.clone(), Limits::default()).run("var a = true; a?.5:1");
assert_eq!(r, Ok(JsValue::Number(0.5)));
}
}
#[test]
fn code_made_at_run_time_reads_the_new_operators() {
truth("eval('null ?? 4') === 4 && eval('var q = null; q?.r') === undefined");
truth("new Function('a', 'return a?.b ?? 5')(null) === 5");
}
// ---- robustness ----
const FRAGMENTS: &[&str] = &[
"a",
"b",
"f",
"1",
".5",
"?.",
"??",
"?",
":",
".",
"(",
")",
"[",
"]",
"`",
"=",
"++",
"delete ",
"new ",
"&&",
"||",
",",
";",
"null",
"this",
"\n",
"=>",
"...",
"{",
"}",
"'use strict';",
];
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn arbitrary_es2020_fragment_programs_never_panic(parts in proptest::collection::vec(0..FRAGMENTS.len(), 0..60)) {
let src: String = parts.iter().map(|&i| FRAGMENTS[i]).collect();
let mut realm = Realm::with_options(es_options(), Limits { fuel: 20_000, heap_bytes: 1 << 20, frames: 200, reentry: 8 });
if let Err(e) = realm.run(&src) {
prop_assert!(e.kind != RunErrorKind::Internal, "{src:?}: {e:?}");
}
}
}
+77 -8
View File
@@ -753,6 +753,14 @@ impl Interp {
self.heap.bytes = self.heap.bytes.saturating_sub(released).saturating_add(flattened);
}
/// The heap's total with the released and flattened bytes taken into account, without a
/// collection.
#[cfg(test)]
pub(crate) fn settled_heap_bytes(&mut self) -> usize {
self.settle_held();
self.heap.bytes
}
/// Collects garbage now and sets when the next collection runs.
#[cfg(test)]
pub(crate) fn collect_for_room(&mut self) {
@@ -1083,6 +1091,21 @@ impl Interp {
}
Op::JumpIfFalse(t) | Op::JumpIfTrue(t) => self.op_branch(t, matches!(op, Op::JumpIfTrue(_)), false),
Op::JumpIfFalseKeep(t) | Op::JumpIfTrueKeep(t) => self.op_branch(t, matches!(op, Op::JumpIfTrueKeep(_)), true),
Op::JumpIfNotNullishKeep(t) => {
if self.peek(0)?.is_nullish() {
self.pop().map(drop)
} else {
self.jump_to(t)
}
}
Op::JumpIfNullish { target, drop: count } => {
if self.peek(0)?.is_nullish() {
self.drop_n(count as usize)?;
self.jump_to(target)
} else {
Ok(())
}
}
Op::Throw => {
self.thrown_mark = None;
Err(Abrupt::Throw(self.pop()?))
@@ -2448,22 +2471,52 @@ impl Interp {
}
/// Whether reading the elements of `o` by index can run code: `o` or an object it inherits
/// from has an accessor property with a getter and an index name. Each object, and each
/// property inspected, takes a unit of fuel.
/// from has an accessor property with a getter and an index name, and no object before it
/// in the chain has an own property of that name, which an indexed read would find first.
/// Each object, each property inspected and each earlier object a getter is looked up in
/// takes a unit of fuel.
fn has_index_getter(&mut self, o: ObjId) -> JsResult<bool> {
// The objects already scanned, whose own properties shadow a getter further along.
let mut before: Vec<ObjId> = Vec::new();
let mut cur = Some(o);
while let Some(id) = cur {
// The scan stops where the fuel would run out.
let budget = usize::try_from(self.fuel).unwrap_or(usize::MAX);
let object = self.object(id)?;
let found =
object.props.iter().take(budget).position(|(k, p)| matches!(p, Prop::Accessor { get: Some(_), .. }) && array_index(k).is_some());
let inspected = found.map_or(object.props.len(), |i| i + 1);
let mut used = 0usize;
let mut found = false;
for (k, p) in object.props.iter() {
if used >= budget {
break;
}
used = used.saturating_add(1);
if !matches!(p, Prop::Accessor { get: Some(_), .. }) || array_index(k).is_none() {
continue;
}
let mut shadowed = false;
for &earlier in &before {
// Where the fuel runs out the scan stops, and the charge below fails.
if used >= budget {
shadowed = true;
break;
}
used = used.saturating_add(1);
if self.get_own_property(earlier, k)?.is_some() {
shadowed = true;
break;
}
}
if !shadowed {
found = true;
break;
}
}
let proto = object.proto;
crate::regexp_vm::use_fuel_n(self, (inspected as u64).saturating_add(1))?;
if found.is_some() {
crate::regexp_vm::use_fuel_n(self, (used as u64).saturating_add(1))?;
if found {
return Ok(true);
}
before.push(id);
cur = proto;
}
Ok(false)
@@ -3278,6 +3331,10 @@ impl Interp {
self.check_global_functions(code)?;
self.check_global_vars(code)?;
}
// The room for the names and the declarations is checked before any name is added, so a
// run that stops at the heap limit here adds no name to the global scope.
let names = lets.iter().fold(0usize, |total, (name, _)| total.saturating_add(binding_bytes(name.len())));
self.reserve_heap(names.saturating_add(declaration_bytes(code)))?;
for (name, constant) in lets {
let b = Binding::lexical(*constant);
self.env_insert(lex, name.clone(), b)?;
@@ -3353,6 +3410,17 @@ impl Interp {
/// environment of its `let` and `const` names. A script's `let` and `const` names go in the
/// global scope ([`Self::declare_global_lexical`]).
fn instantiate_global(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<EnvId> {
// Strict eval code's own environment is in no frame yet, so it is a root while the
// declarations reserve heap.
let mark = self.temp_envs.len();
self.temp_envs.extend([env, var_env]);
let r = self.instantiate_global_rooted(code, env, var_env, is_eval);
self.temp_envs.truncate(mark);
r
}
/// [`Self::instantiate_global`] with `env` and `var_env` in [`Self::temp_envs`].
fn instantiate_global_rooted(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<EnvId> {
let configurable = if is_eval { CONFIGURABLE } else { 0 };
if is_eval && !code.strict && self.options.es2015 {
self.check_eval_vars(code, env, var_env)?;
@@ -3370,7 +3438,8 @@ impl Interp {
None => env,
};
// The caller reserved room for the declarations before the `let` and `const` names took
// some of it. Their environment stays reachable if the check collects.
// some of it (a script's names in the global scope were checked with the declarations
// before they were added). Their environment stays reachable if the check collects.
self.temp_envs.push(lex);
let r = self.reserve_heap(declaration_bytes(code));
self.temp_envs.pop();
+5 -1
View File
@@ -690,7 +690,11 @@ impl<'s> Lexer<'s> {
if !self.e4x && matches!(punct, Punct::DotDot | Punct::ColonColon | Punct::At) {
continue;
}
if !self.es2015 && matches!(punct, Punct::Arrow | Punct::Ellipsis) {
if !self.es2015 && matches!(punct, Punct::Arrow | Punct::Ellipsis | Punct::QuestionDot | Punct::QuestionQuestion) {
continue;
}
// `?.5` is `?` followed by the number `.5`.
if *punct == Punct::QuestionDot && rest.get(2).is_some_and(|&u| (u16::from(b'0')..=u16::from(b'9')).contains(&u)) {
continue;
}
let bytes = spelling.as_bytes();
+4 -1
View File
@@ -114,7 +114,8 @@ pub struct Options {
pub e4x: bool,
/// Read and run the ECMAScript 2015 forms this engine has: `let` and `const`, arrow functions,
/// template literals (tagged ones included), default and rest parameters, and spread in array
/// literals, calls and `new`. Off, they are syntax errors and the language is ES5.1's. Code a
/// literals, calls and `new`, and from ECMAScript 2020 optional chains (`a?.b`, `a?.[k]`,
/// `f?.()`) and `??`. Off, they are syntax errors and the language is ES5.1's. Code a
/// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts.
pub es2015: bool,
}
@@ -222,6 +223,8 @@ mod builtins_tests;
#[cfg(test)]
mod es2015_tests;
#[cfg(test)]
mod es2020_tests;
#[cfg(test)]
mod extension_tests;
#[cfg(test)]
mod host_tests;
+90 -5
View File
@@ -1254,29 +1254,50 @@ impl<'s> Parser<'s> {
let mut ops: Vec<(BinKind, u8)> = Vec::new();
while let Some((op, precedence)) = binary_op(&self.tok, no_in) {
while ops.last().is_some_and(|&(_, top)| top >= precedence) {
self.reduce(&mut operands, &mut ops);
self.reduce(&mut operands, &mut ops)?;
}
self.bump()?;
ops.push((op, precedence));
operands.push(self.parse_unary()?);
}
while !ops.is_empty() {
self.reduce(&mut operands, &mut ops);
self.reduce(&mut operands, &mut ops)?;
}
operands.pop().ok_or_else(|| self.unexpected())
}
/// Joins the top two operands with the top operator.
fn reduce(&mut self, operands: &mut Vec<ExprId>, ops: &mut Vec<(BinKind, u8)>) {
fn reduce(&mut self, operands: &mut Vec<ExprId>, ops: &mut Vec<(BinKind, u8)>) -> Result<()> {
let (Some((op, _)), Some(right), Some(left)) = (ops.pop(), operands.pop(), operands.pop()) else {
return;
return Ok(());
};
let span = self.ast.expr_span(left).to(self.ast.expr_span(right));
let expr = match op {
BinKind::Binary(op) => Expr::Binary { op, left, right },
BinKind::Logical(op) => Expr::Logical { op, left, right },
BinKind::Logical(op) => {
self.check_coalesce_mix(op, left, right)?;
Expr::Logical { op, left, right }
}
};
operands.push(self.ast.push_expr(expr, span));
Ok(())
}
/// `??` and `&&` or `||` written together without parentheses around one of them, which
/// ECMA-262 2020 section 12.13 does not allow (`a ?? b || c`, `a && b ?? c`).
fn check_coalesce_mix(&self, op: LogicalOp, left: ExprId, right: ExprId) -> Result<()> {
let coalesce = op == LogicalOp::Coalesce;
for operand in [left, right] {
if let Some(Expr::Logical { op: inner, .. }) = self.ast.expr(operand)
&& (*inner == LogicalOp::Coalesce) != coalesce
{
return Err(self.error_at_offset(
self.ast.expr_span(operand).start,
"'??' cannot be used with '&&' or '||' without parentheses around one of them",
));
}
}
Ok(())
}
/// Prefix operators, read with a loop and applied innermost first.
@@ -1362,6 +1383,12 @@ impl<'s> Parser<'s> {
None => self.ast.push_expr(Expr::Call { callee: expr, args }, span),
};
}
TokenKind::Punct(Punct::QuestionDot) => {
if !news.is_empty() {
return Err(self.error_at_token(&self.tok, "an optional chain cannot follow 'new' without parentheses around it"));
}
expr = self.parse_optional_chain(expr)?;
}
_ => break,
}
}
@@ -1372,6 +1399,63 @@ impl<'s> Parser<'s> {
Ok(expr)
}
/// An optional chain (ECMA-262 2020 section 12.3.9), from the `?.` after `base` to the last
/// access or call that follows it. A `?.` inside it is a step of the same chain; a tagged
/// template and the E4X accesses (`..`, `.@`, `.(`) cannot follow one.
fn parse_optional_chain(&mut self, base: ExprId) -> Result<ExprId> {
let start = self.ast.expr_span(base).start;
let mut expr = base;
loop {
match &self.tok.kind {
TokenKind::Punct(Punct::QuestionDot) => {
self.bump()?;
let object = self.ast.push_expr(Expr::Optional(expr), self.ast.expr_span(expr));
expr = match &self.tok.kind {
TokenKind::Punct(Punct::LParen) => {
let args = self.parse_arguments()?;
self.ast.push_expr(Expr::Call { callee: object, args }, Span::new(start, self.prev_end))
}
TokenKind::Punct(Punct::LBracket) => self.optional_index(object, start)?,
_ => self.optional_member(object, start)?,
};
}
TokenKind::Punct(Punct::Dot) => {
self.bump()?;
if self.e4x && self.at_e4x_member() {
return Err(self.error_at_token(&self.tok, "an E4X access cannot follow an optional chain"));
}
expr = self.optional_member(expr, start)?;
}
TokenKind::Punct(Punct::LBracket) => expr = self.optional_index(expr, start)?,
TokenKind::Punct(Punct::LParen) => {
let args = self.parse_arguments()?;
expr = self.ast.push_expr(Expr::Call { callee: expr, args }, Span::new(start, self.prev_end));
}
TokenKind::Template { .. } => return Err(self.error_at_token(&self.tok, "a tagged template cannot follow an optional chain")),
TokenKind::Punct(Punct::DotDot) => return Err(self.error_at_token(&self.tok, "an E4X access cannot follow an optional chain")),
_ => break,
}
}
Ok(self.ast.push_expr(Expr::OptionalChain(expr), Span::new(start, self.prev_end)))
}
/// `.name` in an optional chain, with the `.` (or `?.`) already read.
fn optional_member(&mut self, object: ExprId, start: u32) -> Result<ExprId> {
let Some(name) = self.tok.identifier_name().map(str::to_string) else {
return Err(self.error_at_token(&self.tok, format!("expected a property name but found {}", describe(&self.tok))));
};
let token = self.bump()?;
Ok(self.ast.push_expr(Expr::Member { object, property: Name { name, span: token.span } }, Span::new(start, token.span.end)))
}
/// `[index]` in an optional chain.
fn optional_index(&mut self, object: ExprId, start: u32) -> Result<ExprId> {
self.expect(Punct::LBracket)?;
let index = self.parse_expression(false)?;
let close = self.expect(Punct::RBracket)?;
Ok(self.ast.push_expr(Expr::Index { object, index }, Span::new(start, close.span.end)))
}
/// An element of an array literal or an argument list: an assignment expression, or with
/// [`crate::Options::es2015`] a spread (`...expression`).
fn parse_element(&mut self) -> Result<ExprId> {
@@ -1649,6 +1733,7 @@ fn binary_op(token: &Token, no_in: bool) -> Option<(BinKind, u8)> {
TokenKind::Keyword(Keyword::In) if !no_in => Some((B(BinaryOp::In), 7)),
TokenKind::Punct(p) => Some(match p {
Punct::PipePipe => (L(LogicalOp::Or), 1),
Punct::QuestionQuestion => (L(LogicalOp::Coalesce), 1),
Punct::AmpAmp => (L(LogicalOp::And), 2),
Punct::Pipe => (B(BinaryOp::BitOr), 3),
Punct::Caret => (B(BinaryOp::BitXor), 4),
+7
View File
@@ -214,6 +214,11 @@ pub enum Punct {
Arrow,
/// `...`, read only with [`crate::Options::es2015`].
Ellipsis,
/// `?.` not followed by a decimal digit (ECMA-262 2020 section 11.7), read only with
/// [`crate::Options::es2015`].
QuestionDot,
/// `??`, read only with [`crate::Options::es2015`].
QuestionQuestion,
}
impl Punct {
@@ -245,6 +250,8 @@ impl Punct {
("|=", Punct::PipeEq),
("^=", Punct::CaretEq),
("/=", Punct::SlashEq),
("??", Punct::QuestionQuestion),
("?.", Punct::QuestionDot),
("..", Punct::DotDot),
("::", Punct::ColonColon),
("@", Punct::At),
+6 -2
View File
@@ -29,7 +29,8 @@
//! or test file cannot be read, or when no ES5 test runs.
//!
//! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`,
//! arrow functions, templates, default and rest parameters) without and with that option, and
//! arrow functions, templates, default and rest parameters, and from ECMAScript 2020 optional
//! chains and `??`) without and with that option, and
//! prints both counts; its failures with the option go to `es2015-failures.txt`.
//!
//! Two more tests read the Annex B trees, where tests name any edition's section: one parses every
@@ -664,10 +665,13 @@ const ES2015_FOLDERS: &[&str] = &[
"expressions/template-literal",
"expressions/tagged-template",
"rest-parameters",
"expressions/optional-chaining",
"expressions/coalesce",
];
/// The feature tags of the forms [`Options::es2015`] reads.
const ES2015_FEATURES: &[&str] = &["let", "const", "arrow-function", "template", "default-parameters", "rest-parameters"];
const ES2015_FEATURES: &[&str] =
&["let", "const", "arrow-function", "template", "default-parameters", "rest-parameters", "optional-chaining", "coalesce-expression"];
#[test]
fn es2015_subset_runs() {
+6 -1
View File
@@ -2634,7 +2634,12 @@ before each element, strings and `String` objects by code point, and objects wit
throws a `TypeError` for any other value; that rule is VectorCraft's own
until iterators are added. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and
an engine that `#targetengine` keeps reads each run the way that run's script does. A
`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. The script reaches the
`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. A `.js` file
also reads two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`,
`f?.(args)`), which give `undefined` and skip the rest of the chain when the value before `?.` is `undefined` or
`null`, and `??`, which evaluates its right side only when its left side is `undefined` or `null`. Mixing `??` with `&&`
or `||` without parentheses, and assigning to an optional chain, are syntax errors. In a `.jsx` file and a `source`
string, `?.` and `??` are syntax errors. Which files read these forms is VectorCraft's own rule. The script reaches the
app through the global object `vc`, and writes to the Script Console and runs other files through `$`:
- `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can
+1
View File
@@ -1086,6 +1086,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`).
- `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`.
- With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
- `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`.
- `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`.
- `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`.
- `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`.