From 7d3094afe6b42f7b0d538966b9a9c0834fabcb01 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:43:20 -0800 Subject: [PATCH] Scripts: .js scripts run let, const, arrows, templates, default and rest parameters and spread vectorcraft-js gains Options::es2015, which reads and runs these ECMAScript 2015 forms: let and const with block scope and their temporal dead zone, a new let binding for each loop iteration, function declarations scoped to their block (with the Annex B.3.3 variable outside strict mode code), 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, by index, and throws a TypeError for anything else until iterators are added. Eval code outside strict mode code cannot declare a var that clashes with a let or const around it, or with a parameter inside a default value. Spread, template objects and the new scopes take fuel and count against the heap limit, and nested arrows and templates count against the depth limit. script.run sets the option for a .js file; eval, Function, #include files, $.evalFile and a kept #targetengine read code the way the running script does. A .jsx file and a source string stay ES5.1. The test262 runner gains an ES2015 subset run, read without and with the option. docs/mcp.md and docs/target-app-parity.md describe the new forms. --- crates/engine/src/script/include.rs | 17 +- crates/engine/src/script/mod.rs | 9 +- crates/engine/src/tests/script_run.rs | 34 ++ crates/js/src/ast.rs | 57 +++ crates/js/src/builtins.rs | 2 +- crates/js/src/bytecode.rs | 81 +++- crates/js/src/compiler.rs | 549 +++++++++++++++++++++--- crates/js/src/es2015_tests.rs | 466 +++++++++++++++++++++ crates/js/src/heap.rs | 32 +- crates/js/src/interp.rs | 577 ++++++++++++++++++++++++-- crates/js/src/interp_tests.rs | 8 + crates/js/src/lexer.rs | 95 ++++- crates/js/src/lib.rs | 23 +- crates/js/src/parser.rs | 503 ++++++++++++++++++++-- crates/js/src/realm.rs | 6 + crates/js/src/token.rs | 15 + crates/js/src/xml.rs | 2 +- crates/js/tests/test262.rs | 169 +++++++- docs/mcp.md | 10 +- docs/target-app-parity.md | 1 + 20 files changed, 2507 insertions(+), 149 deletions(-) create mode 100644 crates/js/src/es2015_tests.rs diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index 4223d829ba..a024949a35 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -217,6 +217,15 @@ pub(crate) struct Files { levels: usize, /// The files `$.evalFile` is running, the script first. frames: Vec, + /// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way. + es2015: bool, +} + +/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in +/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as +/// ECMAScript 5.1 with the ExtendScript extensions. +pub(crate) fn es2015_script(path: Option<&str>) -> bool { + path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js")) } /// The output being built: its UTF-16 text, the line it is on, the units since that line began, @@ -311,9 +320,15 @@ impl Files { chain: real.into_iter().collect(), levels: 0, frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }], + es2015: es2015_script(path), } } + /// The options a file of this run is parsed with, preprocessor lines aside. + pub(crate) fn options(&self) -> Options { + Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() } + } + /// The `JSINCLUDE` folders of this process: absolute folders separated by `;`. pub(crate) fn jsinclude_env() -> Vec { #[cfg(test)] @@ -456,7 +471,7 @@ impl Files { return Ok(()); } let fail = |kind, message: String, line, column| Failure { kind, message, index, file: shown.clone(), line, column }; - let options = Options { preprocessor_lines: true, max_source_units: MAX_TOTAL_BYTES, ..Options::default() }; + let options = Options { preprocessor_lines: true, ..self.options() }; let program = vectorcraft_js::parse_utf16(&units, &options).map_err(|e| fail(FailKind::Syntax, e.message, e.line, e.column))?; let mut cursor = 0usize; for d in &program.directives { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..a01453a627 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1475,7 +1475,7 @@ fn eval_file(host: &Host, args: Vec) -> std::result::Result 0 { host.placed(error, f.file, f.line, f.column) } else { error } })?; // A file without preprocessor lines is parsed here first, so its syntax error names its place. - let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() }; + let options = host.files.borrow().options(); if let Err(e) = vectorcraft_js::parse(&expanded.source, &options) { host.files.borrow_mut().end_eval(); let (_, file, line, column) = expanded.map.locate(e.line, e.column); @@ -1967,11 +1967,16 @@ impl Session { // A realm made here gets the script extensions, `$` and the dialogs; a kept one has them // from its first run, and they act for the run that calls them. let fresh = realm.is_none(); - let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() }; + // A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read + // code the way the script does. + let es2015 = include::es2015_script(request.file.as_deref()); + let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() }; let strict = options.strict; + // A kept engine reads each run's code the way that run's script does. let mut realm = match realm { Some(mut realm) => { realm.set_limits(limits); + realm.set_es2015(es2015); realm } None => { diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index bf8154f9a7..7b0e4bc2f8 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -297,6 +297,40 @@ fn files_are_checked_before_they_are_read() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { + let dir = fresh_folder("es2015"); + 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}); + write("lib.jsxinc", "const k = 2;\nvar twice = n => n * k;\n"); + write("more.jsx", "let m = `m${k}`;\nm;\n"); + let modern = "#include \"lib.jsxinc\"\nlet x = [1, ...[2]];\nvc.log(`${twice(x[1])}`);\nvc.log(eval('let e = 5; e'));\nvc.log(new Function('a = 6', 'return a')());\nvc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n"; + let r = s.execute("script.run", &path(&write("modern.js", modern))).unwrap(); + assert_eq!(r["log"], json!(["4", 5, 6, "m2"]), "{r}"); + let upper = s.execute("script.run", &path(&write("UPPER.JS", "let u = 1; vc.log(u);"))).unwrap(); + assert_eq!(upper["log"], json!([1]), "{upper}"); + for (name, text) in [("legacy.jsx", "let x = 1;"), ("arrow.jsx", "var f = () => 1;"), ("template.jsx", "vc.log(`t`);")] { + 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, "const c = 1;").unwrap_err().to_string().contains("SyntaxError")); + // A named engine reads each run the way that run's script does. + s.execute("script.run", &path(&write("first.jsx", "#targetengine kept\nvar kept = 1;"))).unwrap(); + let modern = s.execute("script.run", &path(&write("second.js", "#targetengine kept\nlet k2 = kept + 1;\nvc.log(k2);"))).unwrap(); + assert_eq!(modern["log"], json!([2]), "{modern}"); + let legacy = s.execute("script.run", &path(&write("third.jsx", "#targetengine kept\nvc.log(k2);\nconst c = 1;"))); + assert!(legacy.unwrap_err().to_string().contains("SyntaxError")); + let legacy = s.execute("script.run", &path(&write("fourth.jsx", "#targetengine kept\nvc.log(k2 + kept);"))).unwrap(); + assert_eq!(legacy["log"], json!([3]), "{legacy}"); + 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())); diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index 8d9ffc06c0..c015e3fa38 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -200,6 +200,40 @@ pub enum Expr { object: ExprId, predicate: ExprId, }, + /// An arrow function. + Arrow(FunctionId), + /// A template literal: its pieces (one more than its substitutions) and its substitutions, + /// in source order. + Template { + quasis: Vec, + exprs: Vec, + }, + /// A tagged template (`` tag`a${b}c` ``): `tag` called with the template object and the + /// substitutions. + TaggedTemplate { + tag: ExprId, + quasis: Vec, + exprs: Vec, + }, + /// `...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), +} + +/// A piece of a template literal's text between its substitutions. +#[derive(Clone, Debug, PartialEq)] +pub struct TemplatePiece { + /// The text with its escapes read. + pub cooked: Vec, + /// The text as written. + pub raw: Vec, +} + +/// Which lexical declaration a name has. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LexKind { + Let, + Const, } /// A piece of an XML literal, in source order. @@ -247,12 +281,17 @@ pub enum ForInTarget { /// `for (var x in o)`, with the declaration's initializer if it has one. Var(VarDecl), Expr(ExprId), + /// `for (let x in o)` or `for (const x in o)`: a new binding for each name. + Lexical(LexKind, Name), } #[derive(Clone, Debug, PartialEq)] pub enum ForInit { Var(Vec), Expr(ExprId), + /// `let` or `const` declarations, in a scope of the loop's own with a new copy of each `let` + /// binding for each iteration. + Lexical(LexKind, Vec), } #[derive(Clone, Debug, PartialEq)] @@ -272,6 +311,8 @@ pub struct CatchClause { #[derive(Clone, Debug, PartialEq)] pub enum Stmt { Var(Vec), + /// `let` or `const` declarations (a `const` always has an initializer). + Lexical(LexKind, Vec), FunctionDecl(FunctionId), Expr(ExprId), Block(Vec), @@ -334,13 +375,20 @@ pub enum FunctionKind { Expression, Getter, Setter, + /// An arrow function; one with an expression body has a body of one `return` statement. + Arrow, } #[derive(Clone, Debug, PartialEq)] pub struct Function { pub kind: FunctionKind, pub name: Option, + /// The parameters before a rest parameter. pub params: Vec, + /// Each parameter's default value, in the order of `params` (empty when none has one). + pub defaults: Vec>, + /// The rest parameter (`...name`). + pub rest: Option, pub body: Vec, /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. @@ -348,6 +396,13 @@ pub struct Function { pub span: Span, } +impl Function { + /// The parameters are plain names: no default value and no rest parameter. + pub fn simple_params(&self) -> bool { + self.rest.is_none() && self.defaults.iter().all(Option::is_none) + } +} + /// The arenas of a parsed script. #[derive(Clone, Debug, Default, PartialEq)] pub struct Ast { @@ -412,6 +467,8 @@ pub struct Program { /// Its preprocessor lines, in source order. pub directives: Vec, pub(crate) lines: crate::LineTable, + /// It was read with [`crate::Options::es2015`]. + pub(crate) es2015: bool, } impl Program { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 380d161ecf..f2c02bdf4c 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -503,7 +503,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)), }; interp.charge_code(&code, 0)?; - let env = interp.global_env; + let env = interp.global_scope(); interp.make_closure(code, env).map(Value::Object) } diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 6992fd5606..28db7edf3d 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -178,6 +178,49 @@ pub(crate) enum Op { ForEachValue(u32), /// `value` → nothing: sets the default XML namespace of the running code. SetDefaultNamespace, + /// Enters a block's environment: the `let` and `const` names of `scopes[i]`, not yet + /// initialized, and its function declarations. + PushBlock(u32), + /// Replaces the current environment with a copy of it, for a `for` loop's next iteration. + CopyEnv, + /// `value` → nothing: initializes the nearest binding of `names[i]`, a `let`, a `const` or + /// a parameter of a function with default or rest parameters. + InitVar(u32), + /// Pushes the value of the parameter `names[i]` of the running function, initialized or not. + LoadParam(u32), + /// Ends the parameters of a function with default or rest parameters: enters the environment + /// of its body's variables and function declarations, and of its `let` and `const` names. + BodyEnv, + /// `value` → nothing: assigns the function declared in a block outside strict mode code to + /// the variable `names[i]` of the running code (ECMA-262 2015 Annex B.3.3). + AnnexB(u32), + /// `array value` → `array`, with the elements of the value appended (spread). + ArraySpread, + /// `function this array` → result: a call with the array's elements as its arguments, a + /// direct eval when `eval` is true and the function is the global `eval`. + CallSpread(bool), + /// `function array` → the new object, constructed with the array's elements as arguments. + NewSpread, + /// `value` → its string (a template literal's substitution). + ToStr, + /// Pushes the template object of `templates[i]`, the same object for each evaluation. + TemplateObject(u32), +} + +/// The names a block declares, entered with [`Op::PushBlock`]. +#[derive(Debug, Default)] +pub(crate) struct BlockScope { + /// The `let` and `const` names, each with whether it is a `const`. + pub(crate) lets: Vec<(Key, bool)>, + /// The function declarations: their names and indices in `functions`. + pub(crate) funcs: Vec<(Key, u32)>, +} + +/// A tagged template's strings: as read and as written. +#[derive(Debug)] +pub(crate) struct Template { + pub(crate) cooked: Vec, + pub(crate) raw: Vec, } /// What code is: a function body, a script, or eval code. @@ -239,6 +282,23 @@ pub(crate) struct Code { pub(crate) source: Rc, /// Where the function's text starts and ends in the source. pub(crate) span: (u32, u32), + /// The block scopes [`Op::PushBlock`] enters. + pub(crate) scopes: Vec, + /// The scope of the `let` and `const` names at the top of the body, script or eval code. + pub(crate) top_scope: Option, + /// The tagged templates [`Op::TemplateObject`] makes objects of. + pub(crate) templates: Vec