From 15fefc99301bca0d5217f88d0c5df3207b75a2fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:21:30 -0800 Subject: [PATCH] JavaScript: block functions, spread and global declarations follow ECMAScript 2015 - A block function whose name a function of an enclosing block declares is not assigned to the variable of that name. - A labelled function in a block is made when the block is entered, and the parser checks it against the `let` and `const` names of its statement list. - A function standing alone as an `if` branch gets a block of its own. - Spread reads a `String` object by code point, and reads an array's length again before each element. - A `var` or function declared on the global object stops a later `let` or `const` of its name until its property is deleted, and a `var` the global object cannot take is a `TypeError` before anything is declared. - A call keeps its callee, receiver and arguments reachable until its frame holds them, and global and eval code keep their environment and their heap charge until their frame is pushed. - Template objects are released when no code that can run holds their sites, even when one code has several sites. - `Realm::set_es2015` during a run applies once the run ends. - A template piece that spans lines does not let a preprocessor line start after it on its last line. --- crates/js/src/compiler.rs | 106 +++++++++++++++------- crates/js/src/es2015_tests.rs | 158 ++++++++++++++++++++++++++++++++ crates/js/src/interp.rs | 166 +++++++++++++++++++++++++++------- crates/js/src/lexer.rs | 2 + crates/js/src/lib.rs | 5 +- crates/js/src/parser.rs | 4 + crates/js/src/realm.rs | 14 ++- crates/js/src/token.rs | 2 +- docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 10 files changed, 390 insertions(+), 74 deletions(-) diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index b5bdd16958..f4ca5fb860 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -243,13 +243,15 @@ impl<'a> FnCompiler<'a> { /// With [`crate::Options::es2015`], only the function declarations at the top of the body are /// hoisted; one in a block is instantiated when the block is entered, and outside strict mode /// code its name is also a variable (Annex B.3.3) unless that clashes with a parameter or with - /// a `let` or a `const` of the body or of a block or loop around the declaration. + /// a `let` or a `const` of the body or of a block or loop around the declaration, or with a + /// function of a block around the one that holds it. fn hoist(&mut self, body: &[StmtId], params: &[Key]) -> CResult { let mut out = Hoisted::default(); let mut seen = HashSet::new(); - // The `let` and `const` names of each statement list and loop the walk enters, with the - // index of the one around it; the body's are first. - let mut scopes: Vec<(Option, HashSet)> = vec![(None, self.lexical_names(body))]; + // The `let` and `const` names and the block functions of each statement list and loop the + // walk enters, with the index of the one around it; the body's are first, and its + // functions are var-scoped. + let mut scopes: Vec<(Option, HashSet, HashSet)> = vec![(None, self.lexical_names(body), HashSet::new())]; let mut work: Vec<(StmtId, bool, usize)> = body.iter().rev().map(|&s| (s, false, 0)).collect(); let mut add_var = |out: &mut Hoisted, k: Key| { if seen.insert(k.clone()) { @@ -260,8 +262,8 @@ impl<'a> FnCompiler<'a> { while let Some((id, nested, scope)) = work.pop() { let Some(stmt) = self.ast.stmt(id) else { return internal("statement out of range") }; let inner = self.es2015; - let mut enter = |names: HashSet| { - scopes.push((Some(scope), names)); + let mut enter = |names: HashSet, funcs: HashSet| { + scopes.push((Some(scope), names, funcs)); scopes.len() - 1 }; match stmt { @@ -283,12 +285,17 @@ impl<'a> FnCompiler<'a> { } } Stmt::Block(list) => { - let s = enter(self.lexical_names(list)); + let s = enter(self.lexical_names(list), self.block_function_names(list)); work.extend(list.iter().rev().map(|&st| (st, nested || inner, s))); } Stmt::If { consequent, alternate, .. } => { - work.extend(alternate.iter().map(|&s| (s, nested || inner, scope))); - work.push((*consequent, nested || inner, scope)); + // A function declaration standing alone as a branch is in a block of its own + // (Annex B.3.4). + for &branch in alternate.iter().chain(std::iter::once(consequent)) { + let alone = matches!(self.ast.stmt(branch), Some(Stmt::FunctionDecl(_))); + let s = if alone { enter(HashSet::new(), HashSet::new()) } else { scope }; + work.push((branch, nested || inner, s)); + } } Stmt::Labeled { body, .. } => work.push((*body, nested, scope)), Stmt::DoWhile { body, .. } | Stmt::While { body, .. } | Stmt::With { body, .. } => work.push((*body, nested || inner, scope)), @@ -298,7 +305,7 @@ impl<'a> FnCompiler<'a> { decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name))); scope } - Some(ForInit::Lexical(_, decls)) => enter(decls.iter().map(|d| key_of(&d.name.name)).collect()), + Some(ForInit::Lexical(_, decls)) => enter(decls.iter().map(|d| key_of(&d.name.name)).collect(), HashSet::new()), _ => scope, }; work.push((*body, nested || inner, s)); @@ -309,28 +316,29 @@ impl<'a> FnCompiler<'a> { add_var(&mut out, key_of(&d.name.name)); scope } - ForInTarget::Lexical(_, name) => enter(HashSet::from([key_of(&name.name)])), + ForInTarget::Lexical(_, name) => enter(HashSet::from([key_of(&name.name)]), HashSet::new()), ForInTarget::Expr(_) => scope, }; work.push((*body, nested || inner, s)); } Stmt::Switch { cases, .. } => { let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect(); - let s = enter(names); + let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect(); + let s = enter(names, funcs); for case in cases.iter().rev() { work.extend(case.body.iter().rev().map(|&st| (st, nested || inner, s))); } } Stmt::Try { block, handler, finalizer } => { if let Some(f) = finalizer { - let s = enter(self.lexical_names(f)); + let s = enter(self.lexical_names(f), self.block_function_names(f)); work.extend(f.iter().rev().map(|&st| (st, nested || inner, s))); } if let Some(h) = handler { - let s = enter(self.lexical_names(&h.body)); + let s = enter(self.lexical_names(&h.body), self.block_function_names(&h.body)); work.extend(h.body.iter().rev().map(|&st| (st, nested || inner, s))); } - let s = enter(self.lexical_names(block)); + let s = enter(self.lexical_names(block), self.block_function_names(block)); work.extend(block.iter().rev().map(|&st| (st, nested || inner, s))); } Stmt::Expr(_) @@ -346,8 +354,12 @@ impl<'a> FnCompiler<'a> { for (k, scope, id) in annex { let mut cur = Some(scope); let mut clash = params.contains(&k) || *k == *key_of("arguments"); - while let Some((outer, names)) = cur.and_then(|i| scopes.get(i)).filter(|_| !clash) { - clash = names.contains(&k); + // The functions of the declaration's own block are judged with it (Annex B.3.3.4); + // those of the blocks around it clash. + let mut own = true; + while let Some((outer, names, funcs)) = cur.and_then(|i| scopes.get(i)).filter(|_| !clash) { + clash = names.contains(&k) || (!own && funcs.contains(&k)); + own = false; cur = *outer; } if !clash { @@ -369,27 +381,48 @@ impl<'a> FnCompiler<'a> { .collect() } + /// The function declaration a statement is, or the one at the end of its chain of labels, + /// with the statement that holds it. + fn declared_function(&self, mut s: StmtId) -> Option<(StmtId, FunctionId)> { + loop { + match self.ast.stmt(s)? { + Stmt::FunctionDecl(fid) => return Some((s, *fid)), + Stmt::Labeled { body, .. } => s = *body, + _ => return None, + } + } + } + + /// The names of the function declarations a statement list holds, labelled ones included. + fn block_function_names(&self, list: &[StmtId]) -> HashSet { + list.iter() + .filter_map(|&s| self.declared_function(s)) + .filter_map(|(_, fid)| self.ast.function(fid).and_then(|f| f.name.as_ref())) + .map(|name| key_of(&name.name)) + .collect() + } + /// The scope a statement list declares with [`crate::Options::es2015`]: its `let` and - /// `const` names, and (`functions`) its function declarations. `None` when it declares none. + /// `const` names, and (`functions`) its function declarations, labelled ones included. `None` + /// when it declares none. fn list_scope(&mut self, list: &[StmtId], functions: bool) -> CResult> { if !self.es2015 { return Ok(None); } let mut scope = BlockScope::default(); for &s in list { - match self.ast.stmt(s) { - Some(Stmt::Lexical(kind, decls)) => scope.lets.extend(decls.iter().map(|d| (key_of(&d.name.name), *kind == LexKind::Const))), - Some(Stmt::FunctionDecl(fid)) if functions && !self.top_funcs.contains(&s) => { - let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else { - return internal("function declaration without a name"); - }; - let k = key_of(&name.name); - let i = self.function(*fid)?; - scope.funcs.push((k, i)); - self.block_funcs.insert(s); - } - _ => {} + if let Some(Stmt::Lexical(kind, decls)) = self.ast.stmt(s) { + scope.lets.extend(decls.iter().map(|d| (key_of(&d.name.name), *kind == LexKind::Const))); + continue; } + let Some((decl, fid)) = self.declared_function(s).filter(|(decl, _)| functions && !self.top_funcs.contains(decl)) else { continue }; + let Some(name) = self.ast.function(fid).and_then(|f| f.name.as_ref()) else { + return internal("function declaration without a name"); + }; + let k = key_of(&name.name); + let i = self.function(fid)?; + scope.funcs.push((k, i)); + self.block_funcs.insert(decl); } if scope.lets.is_empty() && scope.funcs.is_empty() { return Ok(None); @@ -554,7 +587,7 @@ impl<'a> FnCompiler<'a> { self.expr(*test)?; let otherwise = self.new_label(); self.jump(Op::JumpIfFalse, otherwise); - self.stmt(*consequent)?; + self.branch(*consequent)?; let Some(alt) = *alternate else { self.bind(otherwise); break; @@ -565,7 +598,7 @@ impl<'a> FnCompiler<'a> { if matches!(self.ast.stmt(alt), Some(Stmt::If { .. })) { cur = alt; } else { - self.stmt(alt)?; + self.branch(alt)?; break; } } @@ -573,6 +606,15 @@ impl<'a> FnCompiler<'a> { Ok(()) } + /// An `if` branch. With [`crate::Options::es2015`], a function declaration standing alone as + /// the branch is in a block of its own (Annex B.3.4). + fn branch(&mut self, id: StmtId) -> CResult<()> { + if self.es2015 && matches!(self.ast.stmt(id), Some(Stmt::FunctionDecl(_))) { + return self.block(&[id]); + } + self.stmt(id) + } + fn labeled(&mut self, id: StmtId) -> CResult<()> { let mut labels = Vec::new(); let mut cur = id; diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 32a6caa1ee..d717ba2090 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -132,6 +132,29 @@ fn functions_declared_in_blocks_are_scoped_to_the_block() { truth("{ function t() { return 1; } } { let t; { function t() { return 2; } } } t() === 1"); } +#[test] +fn a_block_function_inside_another_of_its_name_leaves_the_variable_alone() { + truth("var f; { function f() { return 'outer'; } { function f() { return 'inner'; } } } f() === 'outer'"); + truth("function g() { { function f() { return 1; } { function f() { return 2; } } } return f(); } g() === 1"); +} + +#[test] +fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() { + truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0"); + truth("{ var early = g(); a: b: function g() { return 8; } } early === 8 && g() === 8"); + truth("label: function top() { return 1; } top() === 1"); + syntax("let f; label: function f() {}"); + syntax("label: function f() {} let f;"); + syntax("{ let f; label: function f() {} }"); +} + +#[test] +fn a_function_standing_alone_as_an_if_branch_has_a_block_of_its_own() { + truth("var f; if (true) function f() { return f; } var saved = f; f = 0; saved() === saved"); + truth("var g; if (false) ; else function g() { return g; } var kept = g; g = 0; kept() === kept"); + truth("if (true) function h() { return 3; } h() === 3"); +} + #[test] fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() { let mut realm = es(); @@ -200,6 +223,43 @@ fn a_global_function_is_judged_by_the_global_objects_own_property() { assert_eq!(realm.run("this.hasOwnProperty('fixed') || this.hasOwnProperty('fresh') || kept !== 1"), Ok(JsValue::Bool(false))); } +fn is_thrown(result: &Result, name: &str) -> bool { + matches!(result, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with(name)) +} + +#[test] +fn a_global_var_stops_a_later_let_even_on_a_configurable_property() { + // ECMA-262 2015 section 15.1.8 checks the names global `var` declarations made, not only the + // property attributes. + let mut realm = es(); + assert_eq!(realm.run("this.x = 1; this.y = 1; 0"), Ok(JsValue::Number(0.0))); + assert_eq!(realm.run("var x; 0"), Ok(JsValue::Number(0.0))); + let again = realm.run("let x = 2;"); + assert!(is_thrown(&again, "SyntaxError"), "{again:?}"); + // A property no `var` declared still takes a `let`. + assert_eq!(realm.run("let y = 2; y"), Ok(JsValue::Number(2.0))); + // A variable eval code declared can be deleted, and then its name takes a `let`. + assert_eq!(realm.run("(0, eval)('var z = 1'); 0"), Ok(JsValue::Number(0.0))); + assert!(is_thrown(&realm.run("let z;"), "SyntaxError")); + assert_eq!(realm.run("delete z"), Ok(JsValue::Bool(true))); + assert_eq!(realm.run("let z = 3; z"), Ok(JsValue::Number(3.0))); + assert_eq!(realm.run("(0, eval)('var w = 1'); delete this.w"), Ok(JsValue::Bool(true))); + assert_eq!(realm.run("let w = 4; w"), Ok(JsValue::Number(4.0))); +} + +#[test] +fn a_global_var_that_cannot_be_declared_declares_nothing() { + let mut realm = es(); + assert_eq!(realm.run("var kept = 1; Object.preventExtensions(this); 0"), Ok(JsValue::Number(0.0))); + for decl in ["let x = 1; var y;", "(0, eval)('var y;');", "(0, eval)('let w; var y;');"] { + let failed = realm.run(decl); + assert!(is_thrown(&failed, "TypeError"), "{decl}: {failed:?}"); + } + assert_eq!(realm.run("this.hasOwnProperty('y')"), Ok(JsValue::Bool(false))); + // `x` was not declared, and a `var` the global object already has stays allowed. + assert_eq!(realm.run("let x = 2; var kept; x + kept"), Ok(JsValue::Number(3.0))); +} + #[test] fn eval_code_keeps_its_let_and_const_to_itself() { truth("eval('let e = 1; e') === 1 && typeof e === 'undefined'"); @@ -305,6 +365,29 @@ fn tagged_templates_get_one_frozen_strings_object_for_each_site() { truth("function tag(s) { return s.raw.join('|'); } tag`a\r\nb${0}\\\r\nc` === 'a\\nb|\\\\\\nc'"); } +#[test] +fn template_objects_go_once_their_code_cannot_run() { + // Each eval makes code with two template sites; once it has run, nothing can run that code. + let mut realm = es(); + let src = "function tag(s) { return s; } for (var i = 0; i < 50; i++) eval('tag`a`; tag`b`;'); 0"; + assert_eq!(realm.run(src), Ok(JsValue::Number(0.0))); + realm.collect_garbage(); + assert_eq!(realm.interp().template_objects.len(), 0); + // While the code can run, both of its sites keep their objects. + assert_eq!(realm.run("var sites = function () { return [tag`a`, tag`b`]; }; var first = sites(); 0"), Ok(JsValue::Number(0.0))); + realm.collect_garbage(); + assert_eq!(realm.interp().template_objects.len(), 2); + assert_eq!(realm.run("var again = sites(); again[0] === first[0] && again[1] === first[1]"), Ok(JsValue::Bool(true))); +} + +#[test] +fn a_preprocessor_line_does_not_start_after_a_template_that_spans_lines() { + let options = Options { es2015: true, preprocessor_lines: true, ..Options::default() }; + assert!(crate::parse("var t = `${1}\n` #strict on", &options).is_err()); + let p = crate::parse("var t = `${1}\n`\n#strict on", &options); + assert!(p.as_ref().is_ok_and(|p| p.directives.len() == 1), "{p:?}"); +} + #[test] fn bad_template_literals_are_syntax_errors() { syntax("`abc"); @@ -373,6 +456,24 @@ fn spread_expands_arrays_strings_and_array_like_objects() { truth("eval(...['1 + 1']) === 2"); } +#[test] +fn spread_reads_a_string_object_by_code_point() { + truth("var b = [...new String('a\\uD83D\\uDE00')]; b.length === 2 && b[0] === 'a' && b[1] === '\\uD83D\\uDE00'"); + truth("function f() { return arguments.length; } f(...new String('\\uD83D\\uDE00\\uD83D\\uDE00')) === 2"); +} + +#[test] +fn spread_reads_an_array_s_length_again_before_each_element() { + let shrink = "var a = [1, 2]; Object.defineProperty(a, 0, { get: function () { a.length = 1; return 'v'; } }); \ + var b = [...a]; b.length === 1 && b[0] === 'v'"; + truth(shrink); + let grow = "var a = [1]; Object.defineProperty(a, 0, { get: function () { a.push(2); return 'v'; } }); \ + var b = [...a]; b.join() === 'v,2'"; + truth(grow); + // An object that is not an array keeps the length it had when spread began. + truth("var o = { length: 2, get 0() { o.length = 1; return 'v'; }, 1: 'w' }; [...o].join() === 'v,w'"); +} + #[test] fn spreading_other_values_is_a_type_error() { throws("[...1];", "TypeError"); @@ -451,6 +552,40 @@ fn new_scopes_survive_collections_while_they_are_made() { assert!(completed > 0); } +/// Runs `src` with a collection at every heap reservation, and checks that it gives `true`. +fn truth_collecting(src: &str) { + let mut realm = es(); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true)); + let r = realm.run(src); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false)); + assert_eq!(r, Ok(JsValue::Bool(true)), "{src}"); + assert!(realm.interp().heap.collections > 0, "{src}"); +} + +#[test] +fn values_a_call_enters_with_stay_reachable_while_its_scopes_are_made() { + truth_collecting("function C() { let x = 1; this.x = x; } var o = new C(); o.x === 1 && o instanceof C"); + truth_collecting("function f(a) { let x = 1; return arguments[1].v; } f(0, { v: 3 }) === 3"); + truth_collecting("function g() { 'use strict'; let x = 1; return this.v + x; } g.call({ v: 4 }) === 5"); +} + +#[test] +fn strict_eval_environments_stay_reachable_while_their_scopes_are_made() { + truth_collecting("(function () { 'use strict'; var v = 5; return eval('let x = 1; var y = 2; x + y + v'); })() === 8"); + truth_collecting("(0, eval)(\"'use strict'; let x = 1; var y = 2; x + y\") === 3"); +} + +#[test] +fn new_scopes_survive_a_collection_at_each_reservation() { + // The sweep below makes collections fall where the heap size puts them; this one runs one at + // every reservation, so every scope is made across a collection. + truth_collecting( + "var total = 0; \ + function f(a = 1, ...r) { let x = a + r.length; const y = 1; function g() { return x + y; } function h() { return g(); } return h(); } \ + for (var i = 0; i < 20; i++) { { let b = i; function k() { return b; } total += f(1, 2) + k() - i; } } total === 60", + ); +} + #[test] fn nested_arrows_and_templates_stay_within_the_depth_limit() { let deep = format!("{}0", "x => ".repeat(400)); @@ -494,6 +629,29 @@ fn code_made_at_run_time_reads_the_realm_s_language() { assert!(matches!(&legacy, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{legacy:?}"); } +/// Starts `src` with the option `start`, turns it to `!start` once the run has paused, and gives +/// the run's value. +fn run_switching_language(src: &str, start: bool) -> Result { + let mut realm = Realm::with_options(Options { es2015: start, ..Options::default() }, Limits::default()); + realm.start(src)?; + assert_eq!(realm.advance(20)?, crate::Progress::Paused); + realm.set_es2015(!start); + loop { + if let crate::Progress::Done(v) = realm.advance(1000)? { + assert_eq!(realm.interp().options.es2015, !start, "the new language applies once the run ends"); + return Ok(v); + } + } +} + +#[test] +fn a_run_keeps_its_language_for_the_code_it_evaluates() { + let src = "for (var i = 0; i < 200; i++) {} "; + assert_eq!(run_switching_language(&format!("{src} eval('let a = 1; a')"), true), Ok(JsValue::Number(1.0))); + let legacy = run_switching_language(&format!("{src} var r; try {{ eval('let a = 1; a'); }} catch (e) {{ r = e.name; }} r"), false); + assert_eq!(legacy, Ok(JsValue::String("SyntaxError".into()))); +} + // ---- robustness ---- const FRAGMENTS: &[&str] = &[ diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index a79328cf60..1030101bab 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -225,12 +225,20 @@ pub(crate) struct Interp { pub(crate) temp_roots: Vec, /// Environments native code is still building. temp_envs: Vec, + /// Global and eval code whose frame is not pushed yet, counted against the heap. + temp_codes: Vec>, pub(crate) global: ObjId, pub(crate) global_env: EnvId, /// The declarative environment inside `global_env` that holds the `let` and `const` names of /// the scripts the realm runs with [`Options::es2015`]. Global code runs in it in either /// language, so a function made by one run sees the names a later run declares. pub(crate) global_lex: EnvId, + /// The names global code has declared with `var` or as functions on the global object, which + /// a later script's `let` or `const` cannot take (ECMA-262 2015 section 8.1.1.4, its + /// [[VarNames]]). Deleting the global object's property removes its name. + global_vars: std::collections::HashSet, + /// The [`Options::es2015`] a host set while a run was going, for the runs after it. + pub(crate) next_es2015: Option, /// The template objects tagged templates have made, by code and template index, each with /// its code (ECMA-262 2015 section 12.2.9.3 keeps one object for each site). pub(crate) template_objects: std::collections::HashMap<(usize, u32), (Rc, ObjId)>, @@ -388,6 +396,8 @@ const NAMED_KEY_UNITS: usize = 256; thread_local! { /// Tests: the [`Interp::finally_sites`] entries that leaving a block or a frame has looked at. pub(crate) static SITE_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: [`Interp::reserve_heap`] collects garbage each time it is called. + pub(crate) static COLLECT_ON_RESERVE: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// The estimated bytes of the index names `0` to `len - 1` while `for-in` lists them. @@ -511,9 +521,12 @@ impl Interp { frames: Vec::new(), temp_roots: Vec::new(), temp_envs: Vec::new(), + temp_codes: Vec::new(), global, global_env, global_lex, + global_vars: std::collections::HashSet::new(), + next_es2015: None, template_objects: std::collections::HashMap::new(), intrinsics: Intrinsics::placeholder(), fuel: u64::MAX, @@ -696,6 +709,10 @@ impl Interp { /// collection. Everything the caller still needs must be reachable from the roots. pub(crate) fn reserve_heap(&mut self, bytes: usize) -> JsResult<()> { self.settle_held(); + #[cfg(test)] + if COLLECT_ON_RESERVE.with(std::cell::Cell::get) { + self.collect_garbage(); + } if self.heap.bytes.saturating_add(bytes) <= self.limits.heap_bytes { return Ok(()); } @@ -780,6 +797,7 @@ impl Interp { roots.values.push(&self.passing); roots.objects.extend(self.finally_marks.iter().map(|&(id, _, _)| id)); roots.codes.extend(self.finally_sites.iter().map(|((code, _), _)| &**code)); + roots.codes.extend(self.temp_codes.iter().map(|code| &**code)); for f in &self.frames { roots.values.push(&f.this); roots.values.push(&f.completion); @@ -794,8 +812,13 @@ impl Interp { roots.envs.push(self.global_env); roots.envs.push(self.global_lex); roots.envs.extend(self.temp_envs.iter().copied()); - // A template object stays while its code can still run. - self.template_objects.retain(|_, (code, _)| Rc::strong_count(code) > 1); + // A template object stays while its code can still run: while the code has an owner other + // than the entries of its own sites. + let mut sites: std::collections::HashMap = std::collections::HashMap::new(); + for &(code, _) in self.template_objects.keys() { + *sites.entry(code).or_default() += 1; + } + self.template_objects.retain(|(site, _), (code, _)| Rc::strong_count(code) > sites.get(site).copied().unwrap_or(0)); roots.objects.extend(self.template_objects.values().map(|&(_, id)| id)); self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. @@ -1815,6 +1838,12 @@ impl Interp { match self.get_own_property(id, k)? { None => Ok(true), Some(p) if p.configurable() => { + // A deleted global variable no longer stops a `let` or `const` of its name + // (ECMA-262 2015 section 8.1.1.4.7), and the names kept are never more than the + // global object's properties. + if id == self.global { + self.global_vars.remove(k); + } let o = self.object_mut(id)?; o.props.remove(k); if let Class::Arguments(map) = &mut o.class @@ -2291,13 +2320,23 @@ impl Interp { // ---- ECMAScript 2015 spread and templates ---- /// Appends the elements of the value on top to the array under it: an array's elements by - /// index (holes read as `undefined`), a string's characters by code point, and an object with - /// a `length` by index. Any other value is a `TypeError`. Each element takes a unit of fuel, - /// and a concatenated string's flattened copy is counted against the heap before it is made. + /// index (holes read as `undefined`), with its length read again before each one as its + /// iterator reads it, a string's or a `String` object's characters by code point, and an + /// object with a `length` by index. Any other value is a `TypeError`. Each element takes a + /// unit of fuel, and a concatenated string's flattened copy is counted against the heap before + /// it is made. fn op_array_spread(&mut self) -> JsResult<()> { let v = self.peek(0)?; let Value::Object(a) = self.peek(1)? else { return internal("spread into something that is not an array") }; - let items: Vec = match &v { + // A `String` object iterates as the string it holds does (ECMA-262 2015 section 21.1.3.27). + let boxed = match &v { + Value::Object(o) => match &self.object(*o)?.class { + Class::String(s) => Some(Value::String(s.clone())), + _ => None, + }, + _ => None, + }; + let items: Vec = match boxed.as_ref().unwrap_or(&v) { Value::String(s) => { let units = crate::string_builtins::flat_charged(self, s)?; let mut out = Vec::new(); @@ -2325,18 +2364,29 @@ impl Interp { let Some(n) = u32::MAX.checked_sub(current).filter(|room| n < f64::from(*room)).map(|_| n as u32) else { return Err(self.throw(ErrorType::Range, "array literal too long")); }; + // An array's iterator reads its length again before each element (ECMA-262 2015 + // section 22.1.5.2.1), so a getter that shrinks or grows the array changes the count. + let array = matches!(self.object(o)?.class, Class::Array { .. }); // The elements read so far stay reachable while a getter runs. // The list is counted against the heap limit as it grows. let mark = self.temp_roots.len(); let mut held = HeldBytes::new(self); let mut read = || -> JsResult<()> { - for i in 0..n { + let mut i = 0; + loop { + let end = match &self.object(o)?.class { + Class::Array { length, .. } if array => *length, + _ => n, + }; + if i >= end { + return Ok(()); + } self.use_fuel()?; held.add(self, PROP_BYTES)?; let item = self.get_from(o, &index_key(i), &v)?; self.temp_roots.push(item); + i += 1; } - Ok(()) }; let r = read(); drop(held); @@ -2736,28 +2786,35 @@ impl Interp { None => 0, }; let need = declaration_bytes(&code).saturating_add(ENV_BYTES).saturating_add(params).saturating_add(arguments).saturating_add(rest); - if self.heap.bytes.saturating_add(need) > self.limits.heap_bytes { - let mark = self.temp_roots.len(); - self.temp_roots.push(Value::Object(callee)); - self.temp_roots.push(this.clone()); - self.temp_roots.extend(construct.map(Value::Object)); - self.temp_roots.extend(args.iter().cloned()); - let reserved = self.reserve_heap(need); - self.temp_roots.truncate(mark); - reserved?; - } - let this = if code.arrow { - if code.uses_this { self.binding_value(env, ARROW_THIS)? } else { Value::Undefined } - } else if code.strict { - this - } else { - match this { - Value::Undefined | Value::Null => Value::Object(self.global), - Value::Object(_) => this, - prim => Value::Object(self.to_object(&prim)?), + // The callee, the receiver and the arguments stay reachable until the frame holds them: + // the reservation and the scopes, functions and objects the call makes can collect. + let mark = self.temp_roots.len(); + self.temp_roots.push(Value::Object(callee)); + self.temp_roots.push(this.clone()); + self.temp_roots.extend(construct.map(Value::Object)); + self.temp_roots.extend(args.iter().cloned()); + let instantiate = || -> JsResult<(Value, EnvId, EnvId)> { + if self.heap.bytes.saturating_add(need) > self.limits.heap_bytes { + self.reserve_heap(need)?; } + let this = if code.arrow { + if code.uses_this { self.binding_value(env, ARROW_THIS)? } else { Value::Undefined } + } else if code.strict { + this + } else { + match this { + Value::Undefined | Value::Null => Value::Object(self.global), + Value::Object(_) => this, + prim => Value::Object(self.to_object(&prim)?), + } + }; + self.temp_roots.push(this.clone()); + let (fenv, var_env) = self.instantiate_function(&code, env, &args, callee)?; + Ok((this, fenv, var_env)) }; - let (fenv, var_env) = self.instantiate_function(&code, env, &args, callee)?; + let r = instantiate(); + self.temp_roots.truncate(mark); + let (this, fenv, var_env) = r?; let base = self.stack.len(); self.frames.push(Frame { code, @@ -3074,10 +3131,23 @@ impl Interp { (caller_env, caller_var_env) }; self.stack.truncate(start); - let env = self.instantiate_global(&code, env, var_env, true)?; + let env = self.instantiate_pending(&code, env, var_env, true)?; self.push_code_frame(code, env, var_env, this, false) } + /// [`Self::instantiate_global`] with `code` and its environment `env` kept reachable, and the + /// code counted against the heap, until its frame holds them: the scopes and functions it + /// makes can collect. + fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { + let mark = self.temp_envs.len(); + self.temp_envs.push(env); + self.temp_codes.push(code.clone()); + let r = self.instantiate_global(code, env, var_env, is_eval); + self.temp_codes.pop(); + self.temp_envs.truncate(mark); + r + } + /// Indirect eval and scripts: runs `code` in the global environment and returns its /// completion value. pub(crate) fn run_global(&mut self, code: Rc, is_eval: bool) -> JsResult { @@ -3104,7 +3174,7 @@ impl Interp { } else { (scope, self.global_env) }; - let env = self.instantiate_global(&code, env, var_env, is_eval)?; + let env = self.instantiate_pending(&code, env, var_env, is_eval)?; self.push_code_frame(code, env, var_env, Value::Object(global), true) } @@ -3121,11 +3191,11 @@ impl Interp { /// Declares a script's top-level `let` and `const` names in the global scope, uninitialized /// (ECMA-262 2015 section 15.1.8): a name another script declared with `let` or `const`, a - /// non-configurable property of the global object (a `var` or a function another script - /// declared, or a built-in such as `undefined`) or a `var` or function of this script that + /// name global code declared with `var` or as a function, a non-configurable property of the + /// global object (such as the built-in `undefined`) or a `var` or function of this script that /// another script declared with `let` or `const` is a `SyntaxError`, and nothing is declared. /// With [`Options::es2015`], a function of this script that cannot replace a property of the - /// global object is a `TypeError`, also before anything is declared. + /// global object, or a `var` it cannot add, is a `TypeError`, also before anything is declared. fn declare_global_lexical(&mut self, code: &Code, lex: EnvId) -> JsResult<()> { let lets: &[(Key, bool)] = code.top_scope.and_then(|i| code.scopes.get(i as usize)).map_or(&[], |s| &s.lets); let in_lex = |interp: &Self, name: &[u16]| matches!(interp.heap.env(lex), Some(Env::Decl { bindings, .. }) if bindings.contains(name)); @@ -3133,7 +3203,7 @@ impl Interp { for (name, _) in lets { self.use_fuel()?; let restricted = self.get_own_property(global, name)?.is_some_and(|p| !p.configurable()); - if in_lex(self, name) || restricted { + if in_lex(self, name) || restricted || self.global_vars.contains(name) { let ident = String::from_utf16_lossy(name); return Err(self.throw(ErrorType::Syntax, &format!("redeclaration of '{ident}'"))); } @@ -3146,6 +3216,7 @@ impl Interp { } if self.options.es2015 { self.check_global_functions(code)?; + self.check_global_vars(code)?; } for (name, constant) in lets { let b = Binding::lexical(*constant); @@ -3175,6 +3246,25 @@ impl Interp { Ok(()) } + /// The test for every `var` name `code` declares on the global object, made before any is + /// declared (ECMA-262 2015 sections 15.1.8, step 10, and 18.2.1.2, step 8, + /// CanDeclareGlobalVar): a name the global object does not have as its own property needs an + /// extensible global object, or it is a `TypeError`. + fn check_global_vars(&mut self, code: &Code) -> JsResult<()> { + let global = self.global; + if self.object(global)?.extensible { + return Ok(()); + } + for name in &code.vars { + self.use_fuel()?; + if self.get_own_property(global, name)?.is_none() { + let ident = String::from_utf16_lossy(name); + return Err(self.type_error(&format!("cannot declare variable {ident}"))); + } + } + Ok(()) + } + fn push_code_frame(&mut self, code: Rc, env: EnvId, var_env: EnvId, this: Value, boundary: bool) -> JsResult<()> { if self.frames.len() >= self.limits.frames { return Err(Abrupt::Limit(LimitKind::Frames)); @@ -3208,6 +3298,7 @@ impl Interp { self.check_eval_vars(code, env, var_env)?; if var_env == self.global_env { self.check_global_functions(code)?; + self.check_global_vars(code)?; } } let lex = match code.top_scope { @@ -3223,15 +3314,22 @@ impl Interp { // over the global scope in either language, which sees the global object's names too. let global = var_env == self.global_env && lex == self.global_lex; let scope = if self.options.es2015 || global { lex } else { var_env }; + let on_global = var_env == self.global_env; for (name, fi) in &code.fun_decls { self.use_fuel()?; let Some(fcode) = code.functions.get(*fi as usize).cloned() else { return internal("function out of range") }; let f = self.make_closure(fcode, scope)?; self.declare(var_env, name, Some(Value::Object(f)), configurable)?; + if on_global { + self.global_vars.insert(name.clone()); + } } for v in &code.vars { self.use_fuel()?; self.declare(var_env, v, None, configurable)?; + if on_global { + self.global_vars.insert(v.clone()); + } } Ok(lex) } diff --git a/crates/js/src/lexer.rs b/crates/js/src/lexer.rs index 4d5432c4a9..b24ba4b62e 100644 --- a/crates/js/src/lexer.rs +++ b/crates/js/src/lexer.rs @@ -194,6 +194,8 @@ impl<'s> Lexer<'s> { self.line_start = start.saturating_sub(usize::try_from(token.column.saturating_sub(1)).unwrap_or(0)); self.blank_line = false; let mut piece = self.template(start, token.line, token.column)?; + // A piece continued over a line ends on a new line, but not at its start. + self.blank_line = false; piece.newline_before = token.newline_before; Ok(piece) } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 5d48ec2d7a..f1fa58730f 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -53,8 +53,9 @@ //! loop, function declarations in blocks scoped to the block (Annex B.3.3 in sloppy code), arrow //! functions (section 14.2), template literals and tagged templates (sections 12.2.9 and //! 12.3.7), default and rest parameters (section 14.1) and spread in array literals, calls and -//! `new` (sections 12.2.5 and 12.3.6.1). Spread reads arrays, strings (by code point) and objects -//! with a `length`, by index; other values are a `TypeError`. Destructuring, `for … of`, classes, +//! `new` (sections 12.2.5 and 12.3.6.1). Spread reads arrays by index, reading the length again +//! before each element, strings and `String` objects by code point, and objects with a `length` by +//! index; other values are a `TypeError`. Destructuring, `for … of`, classes, //! generators and modules stay syntax errors. #![forbid(unsafe_code)] diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index db034d1e2d..edc6b22c9a 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -949,6 +949,10 @@ impl<'s> Parser<'s> { self.ctx.labels.remove(&label.name); } let mut body = body?; + // A labelled function in a statement list is declared there as one without labels is. + if let Some(Stmt::FunctionDecl(fid)) = self.ast.stmt(body).filter(|_| in_list) { + self.declare_function(*fid)?; + } for (label, label_start) in labels.into_iter().rev() { let span = Span::new(label_start.start, self.ast.stmt_span(body).end); body = self.ast.push_stmt(Stmt::Labeled { label, body }, span); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 5082caf1f5..728839949c 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -216,9 +216,16 @@ impl Realm { } /// Sets [`Options::es2015`] for the next runs, and for the code they evaluate. The `let` and - /// `const` names earlier runs declared stay visible when it is turned off. + /// `const` names earlier runs declared stay visible when it is turned off. A run begun with + /// [`Realm::start`] that is still going keeps the language it started with for the code it + /// evaluates; the new one applies once it ends. pub fn set_es2015(&mut self, es2015: bool) { - self.interp.set_es2015(es2015); + if self.is_running() || self.interp.waiting { + self.interp.next_es2015 = Some(es2015); + } else { + self.interp.next_es2015 = None; + self.interp.set_es2015(es2015); + } } /// The realm's interrupt flag. Setting it stops a running script, or the next one to start. @@ -299,6 +306,9 @@ impl Realm { interp.waiting = false; interp.resuming = None; interp.passing = Value::Undefined; + if let Some(es2015) = interp.next_es2015.take() { + interp.set_es2015(es2015); + } match result { Ok(v) => Ok(interp.to_js_value(&v)), Err(Abrupt::Throw(v)) => { diff --git a/crates/js/src/token.rs b/crates/js/src/token.rs index 608d4c1240..192f38aa83 100644 --- a/crates/js/src/token.rs +++ b/crates/js/src/token.rs @@ -363,7 +363,7 @@ pub enum TokenKind { /// A piece of a template literal (read only with [`crate::Options::es2015`]): from its /// backtick, or from the `}` that ends a substitution, to the next `${` or the closing /// backtick (`tail`). `cooked` is the text with its escapes read and `raw` the text as written, - /// both with each line terminator sequence read as a line feed. + /// both with each CR LF and each CR read as a line feed; U+2028 and U+2029 stay as written. Template { cooked: Vec, raw: Vec, diff --git a/docs/mcp.md b/docs/mcp.md index b12d512f84..ec6f2d7f76 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2620,8 +2620,9 @@ not UTF-8. The language is ES5.1, except that identifiers take the characters Un `.js` (in any case) also reads these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone, a new `let` binding for each `for` loop iteration, function declarations scoped to their block, arrow functions, template literals and tagged templates, default and rest -parameters, and spread in array literals, calls and `new`. Spread reads arrays, strings (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 +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. `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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4fbad2b8e0..98cb315cc1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1079,7 +1079,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `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, strings (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 557 other runs pass with it (373 and 27 without it); the 24 failing runs 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`. + - 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 557 other runs pass with it (373 and 27 without it); the 24 failing runs 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`. - `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`.