JavaScript: a trailing comma ends call arguments and parameter lists (#9189)

This commit is contained in:
.CooCoo
2026-11-25 00:56:02 +07:00
committed by GitHub
parent 4c60269d1a
commit 8e7a6142fc
7 changed files with 55 additions and 5 deletions
+8
View File
@@ -95,6 +95,14 @@ fn variables_functions_and_closures() {
assert_eq!(num("(function(a, b, c) {}).length"), 3.0);
}
#[test]
fn a_trailing_comma_adds_no_argument_or_parameter() {
assert_eq!(num("function f(a, b,) { return arguments.length * 10 + f.length; } f(1,)"), 12.0);
assert_eq!(num("function P(x,) { this.n = arguments.length; } new P(5,).n"), 1.0);
assert_eq!(num("var f = new Function('a,', 'return arguments.length'); f(1, 2) * 10 + f.length"), 21.0);
assert_eq!(num("Function('a', '', 'return a')(4)"), 4.0);
}
#[test]
fn call_and_apply_set_this_and_arguments() {
assert_eq!(num("function f(a, b) { return this.k + a + b; } f.call({k: 1}, 2, 3)"), 6.0);
+10 -1
View File
@@ -1008,9 +1008,17 @@ impl<'s> Parser<'s> {
let default = if self.es2015 && self.eat(Punct::Eq)? { Some(self.parse_assignment(false)?) } else { None };
params.push(param);
defaults.push(default);
// A comma may follow the last parameter (ECMAScript 2017, section 14.1), except in
// a setter, which takes one parameter and no comma (section 14.3).
if !self.eat(Punct::Comma)? {
break;
}
if self.at(Punct::RParen) {
if kind == FunctionKind::Setter {
return Err(self.error_at_token(&self.tok, "a setter must have exactly one parameter"));
}
break;
}
}
}
let close = self.expect(Punct::RParen)?;
@@ -1473,7 +1481,8 @@ impl<'s> Parser<'s> {
if !self.at(Punct::RParen) {
loop {
args.push(self.parse_element()?);
if !self.eat(Punct::Comma)? {
// A comma may follow the last argument (ECMAScript 2017, section 12.3).
if !self.eat(Punct::Comma)? || self.at(Punct::RParen) {
break;
}
}
+18
View File
@@ -134,6 +134,24 @@ fn accessors_take_the_right_number_of_parameters() {
assert!(err("({set a(x, y) {}});").message.contains("setter"));
}
#[test]
fn a_comma_may_end_arguments_and_parameters() {
let p = ok("f(1,);");
assert!(matches!(expr(&p, first_expr(&p)), Expr::Call { args, .. } if args.len() == 1));
let p = ok("new F(1, 2,);");
assert!(matches!(expr(&p, first_expr(&p)), Expr::New { args, .. } if args.len() == 2));
let p = ok("function g(a, b,) {}");
let Stmt::FunctionDecl(g) = stmt(&p, p.body[0]) else { panic!() };
assert_eq!(p.ast.function(*g).unwrap().params.len(), 2);
for src in ["(function (a,) {});", "({get a() {}, m: function (x,) {}});", "f(g(1,),);", "'use strict'; function h(a,) {}"] {
ok(src);
}
for src in ["f(,);", "f(1,,);", "f(, 1);", "function g(,) {}", "function g(a,,) {}", "new F(,);"] {
err(src);
}
assert!(err("({set a(v,) {}});").message.contains("setter"));
}
#[test]
fn property_names_may_repeat() {
for src in ["({a: 1, a: 2});", "({a: 1, 'a': 2});", "({get a() {}, set a(v) {}});", "({a: 1, get a() {}});", "({get a() {}, get a() {}});"] {
+3 -1
View File
@@ -249,9 +249,11 @@ enum Pending<'s> {
/// `Window`: `(` and a string literal with the window's type may follow.
Window(Option<usize>),
WindowType(Option<usize>),
/// `.executeMenuCommand(`: a string literal and `)` may follow.
/// `.executeMenuCommand(`: a string literal and `)` may follow, with a trailing comma
/// between them.
Menu(Option<usize>),
MenuString(Option<usize>, &'s str),
MenuStringComma(Option<usize>, &'s str),
/// `.open(`: a string literal with the open mode may follow.
Open(Option<usize>),
/// A File object's `length`, `hidden` or `readonly` (`f.length`, `f['length']`): an assignment
+3 -2
View File
@@ -66,7 +66,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.menu(None, l);
}
}
Pending::MenuString(l, s) => self.menu(t.is(")").then_some(s), l),
Pending::MenuString(l, s) if t.is(",") => self.pending = Pending::MenuStringComma(l, s),
Pending::MenuString(l, s) | Pending::MenuStringComma(l, s) => self.menu(t.is(")").then_some(s), l),
Pending::Open(l) => {
if t.kind == T::Str {
self.open_mode(&unquote(t.text, 2), l);
@@ -123,7 +124,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
match pending {
Pending::Window(l) | Pending::WindowType(l) => self.acc.feature(FeatureId::ScriptuiWindow, l),
Pending::Menu(l) | Pending::MenuString(l, _) => self.menu(None, l),
Pending::Menu(l) | Pending::MenuString(l, _) | Pending::MenuStringComma(l, _) => self.menu(None, l),
Pending::Setter(l, true) => self.file_setter(l),
Pending::Open(_) | Pending::Setter(_, false) | Pending::Name(..) | Pending::None => {}
}
+12
View File
@@ -1556,6 +1556,18 @@ fn menu_commands_are_counted_with_their_lines() {
assert_eq!(feature(&r, "menuCommand").map(|f| f.count), Some(6));
}
#[test]
fn a_menu_command_string_with_a_trailing_comma_is_listed() {
let r = report(concat!(
"app.executeMenuCommand('acmecopyall',);\n",
"app.executeMenuCommand('acmecopyall', n);\n",
"app.executeMenuCommand('acmecopyall',\n",
));
let strings: Vec<(&str, usize, &[usize])> = r.menu_strings.iter().map(|s| (s.value.as_str(), s.count, s.lines.as_slice())).collect();
assert_eq!(strings, [("acmecopyall", 1, &[1][..])]);
assert_eq!(r.menu_dynamic, 2);
}
#[test]
fn effects_outside_the_document_are_listed_in_order() {
let r = report(concat!(
+1 -1
View File
@@ -1082,7 +1082,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- File › Scripts › Check Script… reads a script written for Illustrator (`.jsx`, `.jsxinc` or a compiled `.jsxbin`) without running any of it and reports what it needs (the document model, files, dialogs, menu commands, features only Illustrator has), what it would do outside the document, the menu commands and document-model members it uses, its directives and included files, and the problems that would stop it loading (`script.check`, which also reads `.js` files); File › Open and drag-and-drop show the report for `.jsx`, `.jsxinc` and `.jsxbin` files.
- Check Script reads names by the same identifier rule as `vectorcraft-js`: Unicode 17.0 `ID_Start` characters, `$` and `_` start a name, and `ID_Continue` characters and `$` continue it (https://www.unicode.org/reports/tr31/, https://tc39.es/ecma262/#sec-names-and-keywords). U+2118, U+203F, U+00B7 and the zero width non-joiner and joiner are name characters, and U+00B2 and U+2E2F are not. Of the characters Unicode 17.0 assigned, U+088F starts a name and U+1ACF may follow its first character. A `\uXXXX` escape is read as its character only where a name may hold it, so `\u0030abc` does not become a name that starts with a digit; a `\u{…}` escape takes any number of hexadecimal digits up to U+10FFFF, and one that is empty, unclosed, out of range or a surrogate is not part of a name. Each `\u{…}` escape read in a name is reported as syntax newer than ES3, which has only the four-digit form (https://ecma-international.org/wp-content/uploads/ECMA-262_3rd_edition_december_1999.pdf, section 7.6). A private name may start with an escape (`this.#\u{61}pp` is the private name `#app`), and a private name at the start of a line inside braces is not read as a directive unless its name is a directive's. Tests: `crates/scriptcheck/src/tests.rs` (`names_are_made_of_the_unicode_identifier_characters`, `an_escape_stands_for_a_character_only_where_a_name_may_hold_it`, `braced_escapes_in_names_are_read_by_their_value`, `braced_name_escape_reports_later_syntax_and_member`, `private_names_with_escaped_starts_are_single_tokens`, `private_name_at_line_start_is_not_a_directive`), `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs` (`both_lexers_take_the_same_characters_into_names`).
- Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. It leaves out only objects that are always Folder objects, `new Folder(…)` and the `Folder` places such as `Folder.temp` other than `Folder.current`, which a script can assign; `Folder(…)` gives a File object when the path names a file and `Folder.selectDialog()` gives a File or Folder object (https://extendscript.docsforadobe.dev/file-system-access/folder-object/), so setting those counts, as it does on a variable that any assignment, in any branch or included file, gives such an object. Nothing counts as a Folder object in a check whose files use `with`, name `eval`, `Function`, `evalFile` or `constructor` as a word or as a string literal in brackets (`this['eval'](s)`, `(function () {}).constructor(s)`), read, call or assign a property in brackets on any object (a `[` after a value, not an array literal) when the brackets hold anything but one number or string literal (`g[k] = …`, `$['global'][k] = …`, `this[k](s)`, `this['ev' + 'al'](s)`, `this[('eval')](s)`, `this[0, 'eval'](s)`, `$[k](f)`, `(function () {})[k](s)`, or a preprocessor line inside the brackets) or the `[` opens while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256 characters, assign properties of more than 1,000 different names on members, or assign or declare `Folder`, and a variable whose name a member assignment writes (`$.global.d = …`, `this.d = …`, `this['d'] = …`, with the string's escapes undone) counts as one that may hold a File object (`setting_a_folders_length_or_flags_does_not_write`, `a_variable_that_may_hold_a_file_counts_as_one`, `a_file_in_a_local_variable_leaves_an_outer_folder_alone`, `a_folder_that_other_code_may_rebind_counts_as_a_file`, `a_folder_that_unnamed_code_may_rebind_counts_as_a_file`, `a_bracketed_name_is_read_whole_or_counts_as_any_name`, `a_bracketed_variable_read_counts_as_any_name`, `a_bracketed_joined_name_counts_as_any_name`, `a_bracketed_name_in_parentheses_counts_as_any_name`, `a_bracketed_comma_expression_counts_as_any_name`, `a_bracketed_variable_call_on_dollar_counts_as_any_name`, `a_bracketed_variable_constructor_counts_as_any_name`, `a_literal_name_in_brackets_leaves_the_folder_alone`, `a_directive_in_a_bracketed_name_counts_as_any_name`). A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`).
- `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` 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. A comma may follow the last argument of a call or `new` expression and the last parameter of a function other than a setter, as ECMAScript 2017 allows (https://tc39.es/ecma262/2017/#sec-left-hand-side-expressions, https://tc39.es/ecma262/2017/#sec-function-definitions); `f(,)` and `f(1,,)` give a `SyntaxError`. 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 by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.