From 248936eec3db137fb1e523481aa534f347b62faf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:32:16 -0800 Subject: [PATCH] Tests: the test262 runner parses and runs the Annex B tests The test262 runner read only test/language and a few built-ins folders, so the Annex B tests were never counted, among them the for-in variable with an initializer that must parse in sloppy code and give a SyntaxError in strict code. - annex_b_parse_subset parses every test under test/annexB/language without a feature tag, of any edition, in the modes its flags give, and writes annexb-parse-failures.txt. - annex_b_runs runs those tests and the test/annexB/built-ins tests for String, Date, RegExp and Function through the interpreter and writes annexb-language-failures.txt and annexb-builtins-failures.txt. The escape and unescape folders still run once, with the ES5 built-ins. - A suite without test/annexB skips both; a folder there with nothing to parse or run fails them. Conformance failures stay in the reports. - The runner reads only regular files inside the suite: it does not follow symbolic links, refuses an includes: name that leaves harness/, refuses a file over 8 MiB before reading it, and fails on a folder it cannot read instead of skipping it. Docs: docs/target-app-parity.md, the xtask test262 module comment. --- crates/js/tests/test262.rs | 495 +++++++++++++++++++++++++++++-------- docs/target-app-parity.md | 1 + xtask/src/test262.rs | 4 +- 3 files changed, 400 insertions(+), 100 deletions(-) diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index bf32bcfcd6..8ae4d36f6a 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -27,6 +27,17 @@ //! an ES5 section apart from the other tests without a feature tag; its failures go to //! `builtins-failures.txt`. The interpreter tests fail when the interpreter panics, when a harness //! or test file cannot be read, or when no ES5 test runs. +//! +//! Two more tests read the Annex B trees, where tests name any edition's section: one parses every +//! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset +//! (failures in `annexb-parse-failures.txt`), and one runs those tests and the tests under the +//! folders [`ANNEX_B_BUILT_INS`] names through the interpreter (failures in +//! `annexb-language-failures.txt` and `annexb-builtins-failures.txt`). A suite without +//! `test/annexB/` skips them; a folder there with no test to parse or run fails them. +//! +//! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses +//! an `includes:` name that leaves the `harness/` folder, and refuses a file over +//! [`MAX_FILE_BYTES`] before reading it. A folder or file it cannot read fails the test. use std::collections::HashSet; use std::path::{Path, PathBuf}; @@ -56,23 +67,89 @@ fn suite_dir() -> Option { dirs.pop() } -/// The `.js` files under `dir`, sorted, with the `_FIXTURE` helper files left out. -fn test_files(dir: &Path) -> Vec { +/// The largest test or harness file read (the largest file in the pinned suite is 3,234,014 bytes). +const MAX_FILE_BYTES: u64 = 8 << 20; + +/// The value of `result`; an error fails the test with its message. +fn or_fail(result: Result) -> T { + assert!(result.is_ok(), "{}", result.as_ref().err().map_or("", String::as_str)); + result.unwrap_or_default() +} + +/// `dir` joined with the `/`-separated path `rel`. An empty, `.` or `..` component, one holding a +/// `\` or `:`, and a component that is a symbolic link give an error, so the path stays inside +/// `dir`. A component that does not exist is not checked further. +fn inside(dir: &Path, rel: &str) -> Result { + let mut path = dir.to_path_buf(); + for part in rel.split('/') { + if part.is_empty() || part == "." || part == ".." || part.contains(['\\', ':']) { + return Err(format!("{rel} is not a path inside {}", dir.display())); + } + path.push(part); + if std::fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) { + return Err(format!("{} is a symbolic link; the runner reads only files inside the suite", path.display())); + } + } + Ok(path) +} + +/// Reads a test or harness file: a regular file (not a symbolic link) of at most +/// [`MAX_FILE_BYTES`], with invalid UTF-8 replaced. +fn read_source(path: &Path) -> Result { + let meta = std::fs::symlink_metadata(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; + if !meta.is_file() { + return Err(format!("{} is not a regular file", path.display())); + } + if meta.len() > MAX_FILE_BYTES { + return Err(format!("{} is {} bytes, over the {MAX_FILE_BYTES}-byte limit", path.display(), meta.len())); + } + let bytes = std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; + Ok(String::from_utf8_lossy(&bytes).into_owned()) +} + +/// The `.js` files under `dir`, sorted, with the `_FIXTURE` helper files and symbolic links left +/// out. A folder or entry that cannot be read gives an error. +fn test_files(dir: &Path) -> Result, String> { let mut out = Vec::new(); let mut stack = vec![dir.to_path_buf()]; while let Some(d) = stack.pop() { - let Ok(entries) = std::fs::read_dir(&d) else { continue }; - for entry in entries.flatten() { + let entries = std::fs::read_dir(&d).map_err(|e| format!("cannot read {}: {e}", d.display()))?; + for entry in entries { + let entry = entry.map_err(|e| format!("cannot read {}: {e}", d.display()))?; let path = entry.path(); - if path.is_dir() { + let kind = entry.file_type().map_err(|e| format!("cannot read {}: {e}", path.display()))?; + if kind.is_dir() { stack.push(path); - } else if path.extension().is_some_and(|e| e == "js") && !path.to_string_lossy().contains("_FIXTURE") { + } else if kind.is_file() && path.extension().is_some_and(|e| e == "js") && !path.to_string_lossy().contains("_FIXTURE") { out.push(path); } } } out.sort(); - out + Ok(out) +} + +/// The modes a test runs in, `true` for strict mode code: both, unless its `onlyStrict`, +/// `noStrict` or `raw` flag says otherwise. +fn modes(meta: &Meta) -> &'static [bool] { + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + if has("raw") || has("noStrict") { + &[false] + } else if has("onlyStrict") { + &[true] + } else { + &[false, true] + } +} + +/// The test is a script without a feature tag and, unless `any_edition` is set, names an ES5 +/// section. The Annex B tests name the edition they were written for with `esid:`, so they are +/// read with `any_edition`. +fn eligible(meta: &Meta, any_edition: bool) -> bool { + (meta.es5 || any_edition) + && meta.features.is_empty() + && !meta.flags.iter().any(|f| f == "module") + && meta.negative_phase.as_deref() != Some("resolution") } /// A YAML flow list (`[a, b]`) or the block list (`- a` lines) after a key. @@ -127,70 +204,15 @@ fn es5_parse_subset() { println!("test262: SKIPPED (no suite; run cargo xtask test262)"); return; }; - let language = dir.join("test").join("language"); + let language = or_fail(inside(&dir, "test/language")); assert!(language.is_dir(), "{} is not a test262 checkout", dir.display()); - let files = test_files(&language); + let files = or_fail(test_files(&language)); assert!(!files.is_empty(), "no tests under {}", language.display()); - // VECTORCRAFT_TEST262_VERBOSE=1 prints each test before it is parsed. - let verbose = std::env::var_os("VECTORCRAFT_TEST262_VERBOSE").is_some(); - - let (mut positive, mut negative, mut with_features, mut modules) = (0usize, 0usize, 0usize, 0usize); - let (mut passed, mut failed) = (0usize, 0usize); - // The tests without a feature tag that name no ES5 section: files, runs passed and failed. - let (mut later, mut later_passed, mut later_failed) = (0usize, 0usize, 0usize); - let mut failures = String::new(); - let mut later_failures = String::new(); - for path in &files { - let source = String::from_utf8_lossy(&std::fs::read(path).unwrap()).into_owned(); - let meta = meta(&source); - if !meta.features.is_empty() { - with_features += 1; - continue; - } - if meta.flags.iter().any(|f| f == "module") || meta.negative_phase.as_deref() == Some("resolution") { - modules += 1; - continue; - } - let expect_error = meta.negative_phase.as_deref() == Some("parse"); - if !meta.es5 { - later += 1; - } else if expect_error { - negative += 1; - } else { - positive += 1; - } - let has = |flag: &str| meta.flags.iter().any(|f| f == flag); - let modes: &[bool] = if has("raw") || has("noStrict") { - &[false] - } else if has("onlyStrict") { - &[true] - } else { - &[false, true] - }; - for &strict in modes { - if verbose { - eprintln!("{} ({})", path.display(), if strict { "strict" } else { "sloppy" }); - } - let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() }; - let result = parse(&text, &Options::default()); - let (pass, fail, list) = - if meta.es5 { (&mut passed, &mut failed, &mut failures) } else { (&mut later_passed, &mut later_failed, &mut later_failures) }; - if result.is_err() == expect_error { - *pass += 1; - } else { - *fail += 1; - let rel = path.strip_prefix(&dir).unwrap_or(path).display().to_string().replace('\\', "/"); - let mode = if strict { "strict" } else { "sloppy" }; - let outcome = match &result { - Ok(_) => "parsed; a SyntaxError was expected".to_string(), - Err(e) => e.to_string(), - }; - list.push_str(&format!("{rel} ({mode}): {outcome}\n")); - } - } - } + let ParseRun { main: es5, later: other, with_features, modules } = or_fail(parse_files(&dir, &files, false)); + let (positive, negative, passed, failed) = (es5.positive, es5.negative, es5.passed, es5.failed); + let (later, later_passed, later_failed) = (other.positive + other.negative, other.passed, other.failed); let report = dir.join("failures.txt"); - std::fs::write(&report, format!("# ES5 subset\n{failures}\n# Other tests without a feature tag\n{later_failures}")).unwrap(); + std::fs::write(&report, format!("# ES5 subset\n{}\n# Other tests without a feature tag\n{}", es5.failures, other.failures)).unwrap(); println!( "test262 ES5 parse subset ({}): {} tests ({positive} that must parse, {negative} that must give a SyntaxError), \ {passed} runs passed, {failed} failed. Other tests without a feature tag: {later} tests, {later_passed} runs passed, \ @@ -201,6 +223,112 @@ fn es5_parse_subset() { ); } +#[test] +fn annex_b_parse_subset() { + let Some(dir) = suite_dir() else { + println!("test262 Annex B parse: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let language = or_fail(inside(&dir, "test/annexB/language")); + if !language.exists() { + println!("test262 Annex B parse: SKIPPED ({} has no test/annexB/language)", dir.display()); + return; + } + let files = or_fail(test_files(&language)); + let ParseRun { main, with_features, modules, .. } = or_fail(parse_files(&dir, &files, true)); + assert!(main.positive + main.negative > 0, "no Annex B tests to parse under {}", language.display()); + let report = dir.join("annexb-parse-failures.txt"); + if let Err(e) = std::fs::write(&report, &main.failures) { + println!("could not write {}: {e}", report.display()); + } + println!( + "test262 Annex B language parse: {} tests ({} that must parse, {} that must give a SyntaxError), {} runs passed, {} failed. \ + Skipped {with_features} tests with feature tags and {modules} module tests. Failures: {}", + main.positive + main.negative, + main.positive, + main.negative, + main.passed, + main.failed, + report.display() + ); +} + +/// The parse counts of one group of tests. +#[derive(Default)] +struct ParseCounts { + /// Tests that must parse. + positive: usize, + /// Tests that must give a `SyntaxError`. + negative: usize, + passed: usize, + failed: usize, + failures: String, +} + +/// The counts of [`parse_files`]. +#[derive(Default)] +struct ParseRun { + /// The tests that name an ES5 section, or every eligible test when any edition is read. + main: ParseCounts, + /// The other tests without a feature tag. + later: ParseCounts, + with_features: usize, + modules: usize, +} + +/// Parses each of `files` in the modes its flags give. With `any_edition`, every test without a +/// feature tag is counted in [`ParseRun::main`]; otherwise only those that name an ES5 section. +fn parse_files(dir: &Path, files: &[PathBuf], any_edition: bool) -> Result { + // VECTORCRAFT_TEST262_VERBOSE=1 prints each test before it is parsed. + let verbose = std::env::var_os("VECTORCRAFT_TEST262_VERBOSE").is_some(); + let mut run = ParseRun::default(); + for path in files { + let source = read_source(path)?; + let meta = meta(&source); + if !meta.features.is_empty() { + run.with_features += 1; + continue; + } + if !eligible(&meta, true) { + run.modules += 1; + continue; + } + let counts = if eligible(&meta, any_edition) { &mut run.main } else { &mut run.later }; + if meta.negative_phase.as_deref() == Some("parse") { + counts.negative += 1; + } else { + counts.positive += 1; + } + let rel = path.strip_prefix(dir).unwrap_or(path).display().to_string().replace('\\', "/"); + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + if verbose { + eprintln!("{} ({mode})", path.display()); + } + match parse_check(&source, &meta, strict) { + Ok(()) => counts.passed += 1, + Err(outcome) => { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): {outcome}\n")); + } + } + } + } + Ok(run) +} + +/// Parses `source` as sloppy or strict mode code (with `"use strict";` before it); `Err` describes +/// a result other than the one the metadata expects (a `SyntaxError` for `negative: phase: parse`). +fn parse_check(source: &str, meta: &Meta, strict: bool) -> Result<(), String> { + let expect_error = meta.negative_phase.as_deref() == Some("parse"); + let text = if strict { format!("\"use strict\";\n{source}") } else { source.to_string() }; + match parse(&text, &Options::default()) { + Ok(_) if expect_error => Err("parsed; a SyntaxError was expected".to_string()), + Err(e) if !expect_error => Err(e.to_string()), + _ => Ok(()), + } +} + /// Globals and method names the interpreter does not provide yet: a test that names one, in its /// own source or in a harness file it includes, is skipped. const MISSING_BUILTINS: &str = "String Number Boolean Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \ @@ -233,6 +361,14 @@ const ES5_BUILT_INS: &[&str] = &[ "annexB/built-ins/unescape", ]; +/// The tests of the Annex B syntax and semantics (ECMA-262 Annex B.1 and B.3). +const ANNEX_B_LANGUAGE: &str = "annexB/language"; + +/// The folders under `test/annexB/built-ins/` with tests without a feature tag, other than the +/// `escape` and `unescape` folders [`ES5_BUILT_INS`] runs: `substr`, `getYear`, `setYear`, +/// `toGMTString`, the legacy `RegExp` features and the `Function` tests. +const ANNEX_B_BUILT_INS: &[&str] = &["annexB/built-ins/Date", "annexB/built-ins/Function", "annexB/built-ins/RegExp", "annexB/built-ins/String"]; + /// The names in [`MISSING_BUILTINS`] that `String`, `Number`, `RegExp` and `Date` provide. const TEXT_BUILTINS: &str = "String Number Date RegExp charAt charCodeAt fromCharCode substring substr split replace match search exec test \ toUpperCase toLowerCase trim toFixed toPrecision toExponential now"; @@ -335,10 +471,20 @@ impl RunCounts { self.tests, self.passed, self.failed, self.panicked, self.skipped ) } + + /// Adds the counts and failures of `other`. + fn add(&mut self, other: RunCounts) { + self.tests += other.tests; + self.skipped += other.skipped; + self.passed += other.passed; + self.failed += other.failed; + self.panicked += other.panicked; + self.failures.push_str(&other.failures); + } } fn run_language_subset(dir: &Path) { - let language = dir.join("test").join("language"); + let language = or_fail(inside(dir, "test/language")); assert!(language.is_dir(), "{} is not a test262 checkout", dir.display()); let missing = missing_builtins(&[TEXT_BUILTINS]); let (es5, _) = run_tests(dir, &language, &missing, false); @@ -377,17 +523,11 @@ fn run_built_ins(dir: &Path) { let missing = missing_builtins(&[TEXT_BUILTINS]); let mut all = RunCounts::default(); for folder in ES5_BUILT_INS { - let root = dir.join("test").join(folder); + let root = or_fail(inside(dir, &format!("test/{folder}"))); assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); let (es5, later) = run_tests(dir, &root, &missing, folder.starts_with("annexB")); - for counts in [es5, later] { - all.tests += counts.tests; - all.skipped += counts.skipped; - all.passed += counts.passed; - all.failed += counts.failed; - all.panicked += counts.panicked; - all.failures.push_str(&counts.failures); - } + all.add(es5); + all.add(later); } assert!(all.tests > 0, "no ES5 built-ins tests ran under {}", dir.display()); let report = dir.join("built-ins-failures.txt"); @@ -414,7 +554,7 @@ fn run_text_builtins(dir: &Path) { let mut report = String::new(); let mut panicked = 0; for name in ["String", "Number", "RegExp", "Date"] { - let root = dir.join("test").join("built-ins").join(name); + let root = or_fail(inside(dir, &format!("test/built-ins/{name}"))); assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); let missing = if name == "String" { missing_builtins(&[TEXT_BUILTINS, STRING_METHODS_SHARED_WITH_ARRAY]) } else { missing_builtins(&[TEXT_BUILTINS]) }; @@ -436,39 +576,27 @@ fn run_text_builtins(dir: &Path) { /// negative parse tests, each in a new realm after the harness. Returns the counts for the tests /// that name an ES5 section and, when `later` is set, for the others (otherwise those are left out). fn run_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, later: bool) -> (RunCounts, RunCounts) { - let harness_dir = dir.join("harness"); - let read = |p: &Path| { - let bytes = std::fs::read(p).map_err(|e| format!("cannot read {}: {e}", p.display())); - assert!(bytes.is_ok(), "{}", bytes.as_ref().err().map_or("", String::as_str)); - String::from_utf8_lossy(&bytes.unwrap_or_default()).into_owned() - }; - let prelude = format!("{}\n{}\n", read(&harness_dir.join("assert.js")), read(&harness_dir.join("sta.js"))); + // A harness file is named by the test's `includes:`, so it is read only inside `harness/`. + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); let verbose = std::env::var_os("VECTORCRAFT_TEST262_VERBOSE").is_some(); let (mut es5_counts, mut later_counts) = (RunCounts::default(), RunCounts::default()); - for path in test_files(root) { - let source = read(&path); + for path in or_fail(test_files(root)) { + let source = or_fail(read_source(&path)); let meta = meta(&source); - let negative_parse = matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")); - if (!meta.es5 && !later) || !meta.features.is_empty() || negative_parse || meta.flags.iter().any(|f| f == "module") { + if !eligible(&meta, later) || meta.negative_phase.as_deref() == Some("parse") { continue; } let counts = if meta.es5 { &mut es5_counts } else { &mut later_counts }; - let includes: String = meta.includes.iter().map(|i| read(&harness_dir.join(i)) + "\n").collect(); + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); if meta.flags.iter().any(|f| f == "async") || needs_missing_builtin(&[&source, &includes], missing) { counts.skipped += 1; continue; } counts.tests += 1; let has = |flag: &str| meta.flags.iter().any(|f| f == flag); - let modes: &[bool] = if has("raw") || has("noStrict") { - &[false] - } else if has("onlyStrict") { - &[true] - } else { - &[false, true] - }; let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); - for &strict in modes { + for &strict in modes(&meta) { let mode = if strict { "strict" } else { "sloppy" }; if verbose { eprintln!("{rel} ({mode})"); @@ -494,6 +622,63 @@ fn run_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, later: bool) -> ( (es5_counts, later_counts) } +#[test] +fn annex_b_runs() { + let Some(dir) = suite_dir() else { + println!("test262 Annex B interpreter: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_annex_b(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests without a feature tag under [`ANNEX_B_LANGUAGE`] and under each folder +/// [`ANNEX_B_BUILT_INS`] names, of any edition, prints the counts of each and writes the failures +/// to `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. +fn run_annex_b(dir: &Path) { + let annex_b = or_fail(inside(dir, "test/annexB")); + if !annex_b.exists() { + println!("test262 Annex B interpreter: SKIPPED ({} has no test/annexB)", dir.display()); + return; + } + let mut panicked = 0; + let mut built_ins_report = String::new(); + for folder in std::iter::once(&ANNEX_B_LANGUAGE).chain(ANNEX_B_BUILT_INS) { + let root = or_fail(inside(dir, &format!("test/{folder}"))); + if !root.exists() { + println!("test262 {folder}: SKIPPED (not in this suite)"); + continue; + } + let missing = if folder.ends_with("/String") { + missing_builtins(&[TEXT_BUILTINS, STRING_METHODS_SHARED_WITH_ARRAY]) + } else { + missing_builtins(&[TEXT_BUILTINS]) + }; + let (es5, later) = run_tests(dir, &root, &missing, true); + let mut counts = RunCounts::default(); + counts.add(es5); + counts.add(later); + assert!(counts.tests + counts.skipped > 0, "no Annex B tests to run under {}", root.display()); + panicked += counts.panicked; + println!("test262 {folder} through the interpreter: {}.", counts.summary()); + if *folder == ANNEX_B_LANGUAGE { + let path = dir.join("annexb-language-failures.txt"); + if let Err(e) = std::fs::write(&path, &counts.failures) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 {folder} failures: {}", path.display()); + } else { + built_ins_report.push_str(&format!("# {folder}\n{}\n", counts.failures)); + } + } + let path = dir.join("annexb-builtins-failures.txt"); + if let Err(e) = std::fs::write(&path, &built_ins_report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 Annex B built-ins failures: {}", path.display()); + assert_eq!(panicked, 0, "the interpreter panicked; see the Annex B failure files in {}", dir.display()); +} + /// `needs_missing_builtin` with `Map`, `Symbol` and `Set` missing. fn skips(sources: &[&str]) -> bool { let missing: HashSet<&str> = ["Map", "Symbol", "Set"].into_iter().collect(); @@ -558,3 +743,115 @@ fn a_source_that_does_not_parse_as_es5_skips() { assert!(skips(&["var x = 1;", "const y = 2;"])); assert!(skips(&["var s = `${x}`;"])); } + +#[test] +fn annex_b_runs_read_the_language_tree_and_the_built_ins_folders_not_run_elsewhere() { + assert_eq!(ANNEX_B_LANGUAGE, "annexB/language"); + for folder in ["annexB/built-ins/String", "annexB/built-ins/Date", "annexB/built-ins/RegExp", "annexB/built-ins/Function"] { + assert!(ANNEX_B_BUILT_INS.contains(&folder), "{folder} is not read"); + } + // `escape` and `unescape` run with the ES5 built-ins, so they are not run twice. + for folder in ANNEX_B_BUILT_INS { + assert!(!ES5_BUILT_INS.contains(folder), "{folder} runs twice"); + assert!(folder.starts_with("annexB/built-ins/"), "{folder} is not an Annex B built-ins folder"); + } +} + +/// A test written for a later edition, naming its section with `esid:` only. +const ESID_ONLY: &str = "/*---\nesid: sec-example\ndescription: a test of a later edition\n---*/\nvar a = 1;\n"; + +#[test] +fn tests_that_name_only_a_later_section_are_read_with_any_edition() { + let later = meta(ESID_ONLY); + assert!(!later.es5); + assert!(eligible(&later, true)); + assert!(!eligible(&later, false)); + let es5 = meta("/*---\nes5id: 12.6.4\n---*/\nvar a = 1;\n"); + assert!(eligible(&es5, false)); + let tagged = meta("/*---\nesid: sec-example\nfeatures: [let]\n---*/\nlet a = 1;\n"); + assert!(!eligible(&tagged, true)); + let module = meta("/*---\nesid: sec-example\nflags: [module]\n---*/\nvar a = 1;\n"); + assert!(!eligible(&module, true)); +} + +/// A strict-only test that expects a `SyntaxError` for an initializer on a for-in variable. +const STRICT_FOR_IN_INITIALIZER: &str = + "/*---\nesid: sec-example\nnegative:\n phase: parse\n type: SyntaxError\nflags: [onlyStrict]\n---*/\nfor (var a = 0 in {}) {}\n"; + +/// A sloppy-only test with an initializer on a for-in variable, which must parse. +const SLOPPY_FOR_IN_INITIALIZER: &str = "/*---\nesid: sec-example\nflags: [noStrict]\n---*/\nvar n = 0;\nfor (var a = 1 in {}) { n += 1; }\n"; + +#[test] +fn a_for_in_initializer_is_a_syntax_error_in_strict_code_only() { + let strict = meta(STRICT_FOR_IN_INITIALIZER); + assert_eq!(strict.negative_phase.as_deref(), Some("parse")); + assert_eq!(modes(&strict), &[true]); + assert_eq!(parse_check(STRICT_FOR_IN_INITIALIZER, &strict, true), Ok(())); + assert!(parse_check(STRICT_FOR_IN_INITIALIZER, &strict, false).is_err(), "the initializer parses in sloppy code"); + + let sloppy = meta(SLOPPY_FOR_IN_INITIALIZER); + assert_eq!(sloppy.negative_phase, None); + assert_eq!(modes(&sloppy), &[false]); + assert_eq!(parse_check(SLOPPY_FOR_IN_INITIALIZER, &sloppy, false), Ok(())); + assert!(parse_check(SLOPPY_FOR_IN_INITIALIZER, &sloppy, true).is_err(), "the initializer parses in strict code"); + + assert_eq!(modes(&meta(ESID_ONLY)), &[false, true]); + assert_eq!(modes(&meta("/*---\nflags: [raw]\n---*/\n")), &[false]); +} + +/// A new, empty folder under the system's temporary folder for one test. +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vectorcraft-test262-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + or_fail(std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))); + dir +} + +#[test] +fn the_walk_reads_only_test_files_inside_the_folder() { + let dir = scratch("walk"); + std::fs::create_dir_all(dir.join("suite/sub")).unwrap(); + std::fs::write(dir.join("suite/b.js"), "").unwrap(); + std::fs::write(dir.join("suite/sub/a.js"), "").unwrap(); + std::fs::write(dir.join("suite/c_FIXTURE.js"), "").unwrap(); + std::fs::write(dir.join("suite/notes.txt"), "").unwrap(); + assert_eq!(test_files(&dir.join("suite")), Ok(vec![dir.join("suite/b.js"), dir.join("suite/sub/a.js")])); + assert!(test_files(&dir.join("absent")).is_err(), "a missing folder is skipped silently"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[cfg(unix)] +#[test] +fn the_walk_does_not_follow_symbolic_links() { + let dir = scratch("links"); + std::fs::create_dir_all(dir.join("suite")).unwrap(); + std::fs::create_dir_all(dir.join("outside")).unwrap(); + std::fs::write(dir.join("outside/x.js"), "").unwrap(); + std::fs::write(dir.join("suite/a.js"), "").unwrap(); + std::os::unix::fs::symlink(dir.join("outside"), dir.join("suite/linked")).unwrap(); + std::os::unix::fs::symlink(dir.join("outside/x.js"), dir.join("suite/x.js")).unwrap(); + assert_eq!(test_files(&dir.join("suite")), Ok(vec![dir.join("suite/a.js")])); + assert!(read_source(&dir.join("suite/x.js")).is_err(), "a linked file is read"); + assert!(inside(&dir.join("suite"), "linked/x.js").is_err(), "a path through a linked folder is allowed"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn harness_names_stay_inside_the_suite() { + let dir = Path::new("suite"); + assert_eq!(inside(dir, "harness/compareArray.js"), Ok(dir.join("harness").join("compareArray.js"))); + for name in ["harness/../../secret.js", "harness/./a.js", "/etc/passwd", "harness//a.js", "harness/a\\..\\b.js", "harness/C:a.js", ""] { + assert!(inside(dir, name).is_err(), "{name:?} is allowed"); + } +} + +#[test] +fn a_file_over_the_limit_is_refused_before_it_is_read() { + let dir = scratch("size"); + let path = dir.join("big.js"); + std::fs::File::create(&path).unwrap().set_len(MAX_FILE_BYTES + 1).unwrap(); + assert!(read_source(&path).is_err_and(|e| e.contains("over the")), "an oversized file is read"); + std::fs::File::create(&path).unwrap().set_len(4).unwrap(); + assert_eq!(read_source(&path), Ok("\0\0\0\0".to_string())); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..4ac30a925d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1077,6 +1077,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `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`. - `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 and do not fail the tests. 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`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. diff --git a/xtask/src/test262.rs b/xtask/src/test262.rs index dfed1d8ae3..7ee456a6c2 100644 --- a/xtask/src/test262.rs +++ b/xtask/src/test262.rs @@ -4,7 +4,9 @@ //! runs `vectorcraft-js`'s `test262` tests, which parse the ES5 parse subset, run the ES5 //! `test/language` tests and the tests of the ES5 built-ins under `test/built-ins` and //! `test/annexB/built-ins` that need only the interpreter's built-ins, run the `test/built-ins` -//! tests for `String`, `Number`, `RegExp` and `Date`, and print each one's counts. +//! tests for `String`, `Number`, `RegExp` and `Date`, parse and run the `test/annexB/language` +//! tests and run the other `test/annexB/built-ins` tests (`String`, `Date`, `RegExp` and +//! `Function`), and print each one's counts. //! //! It also fetches `json2.js`, Douglas Crockford's public-domain JSON polyfill //! (https://github.com/douglascrockford/JSON-js), at a pinned commit, checks it against its SHA-256