diff --git a/crates/js/src/chars.rs b/crates/js/src/chars.rs index eb61fe763d..a7b2c1374c 100644 --- a/crates/js/src/chars.rs +++ b/crates/js/src/chars.rs @@ -1,5 +1,8 @@ //! Character classes of ECMA-262 5.1 section 7: white space, line terminators and the characters -//! identifiers are made of. +//! identifiers are made of. Identifiers follow the Unicode `ID_Start` and `ID_Continue` rule of +//! later editions. + +use std::cmp::Ordering; use unicode_general_category::{GeneralCategory as G, get_general_category}; @@ -14,35 +17,97 @@ pub fn is_whitespace(c: u32) -> bool { matches!(c, 0x09 | 0x0B | 0x0C | 0x20 | 0xA0 | 0xFEFF | 0x1680 | 0x2000..=0x200A | 0x202F | 0x205F | 0x3000) } -/// A character an identifier may start with: a letter (categories Lu, Ll, Lt, Lm, Lo and Nl), -/// `$` or `_` (section 7.6). `\u` escapes are decoded before this check. +/// A character an identifier may start with: a Unicode `ID_Start` character, `$` or `_` +/// (the Names and Keywords clause of current ECMA-262 editions). `ID_Start` is the letters (categories Lu, Ll, Lt, Lm, Lo and Nl) +/// and `Other_ID_Start`, less `Pattern_Syntax` and `Pattern_White_Space` (Unicode Standard Annex +/// #31). The categories come from Unicode 16.0. `\u` escapes are decoded before this check. pub fn is_id_start(c: u32) -> bool { match c { 0x24 | 0x5F => true, 0x41..=0x5A | 0x61..=0x7A => true, 0..=0x7F => false, - // U+2E2F VERTICAL TILDE is a letter (Lm) that Unicode leaves out of identifiers. - 0x2E2F => false, - _ => category(c).is_some_and(|g| { - matches!(g, G::UppercaseLetter | G::LowercaseLetter | G::TitlecaseLetter | G::ModifierLetter | G::OtherLetter | G::LetterNumber) - }), + _ if is_other_id_start(c) => true, + _ => { + category(c).is_some_and(|g| { + matches!(g, G::UppercaseLetter | G::LowercaseLetter | G::TitlecaseLetter | G::ModifierLetter | G::OtherLetter | G::LetterNumber) + }) && !is_pattern_syntax(c) + } } } -/// A character an identifier may hold after its first: those it may start with, decimal digits -/// (Nd), combining marks (Mn, Mc), connector punctuation (Pc), and the zero width non-joiner and -/// joiner. +/// A character an identifier may hold after its first: a Unicode `ID_Continue` character or `$`. +/// `ID_Continue` adds to `ID_Start` the decimal digits (Nd), combining marks (Mn, Mc), connector +/// punctuation (Pc, which holds `_`) and `Other_ID_Continue` (which holds the zero width +/// non-joiner and joiner), less `Pattern_Syntax` and `Pattern_White_Space`. pub fn is_id_part(c: u32) -> bool { match c { 0x30..=0x39 => true, - 0x200C | 0x200D => true, - 0x2E2F => false, _ if is_id_start(c) => true, 0..=0x7F => false, - _ => category(c).is_some_and(|g| matches!(g, G::NonspacingMark | G::SpacingMark | G::DecimalNumber | G::ConnectorPunctuation)), + _ if is_other_id_continue(c) => true, + _ => { + category(c).is_some_and(|g| matches!(g, G::NonspacingMark | G::SpacingMark | G::DecimalNumber | G::ConnectorPunctuation)) + && !is_pattern_syntax(c) + } } } +/// `Other_ID_Start` (Unicode PropList): characters kept in `ID_Start` though their category is +/// not a letter. +fn is_other_id_start(c: u32) -> bool { + matches!(c, 0x1885 | 0x1886 | 0x2118 | 0x212E | 0x309B | 0x309C) +} + +/// `Other_ID_Continue` (Unicode PropList 16.0): characters kept in `ID_Continue` though their +/// category is not a letter, mark, digit or connector. +fn is_other_id_continue(c: u32) -> bool { + matches!(c, 0xB7 | 0x387 | 0x1369..=0x1371 | 0x19DA | 0x200C | 0x200D | 0x30FB | 0xFF65) +} + +/// Non-ASCII `Pattern_Syntax` ranges (Unicode PropList). Unicode does not change this set, and no +/// identifier character belongs to it. `Pattern_White_Space` outside ASCII (U+0085, U+200E, U+200F, +/// U+2028 and U+2029) holds no letter, mark, digit or connector, so the category checks leave it out. +const PATTERN_SYNTAX: [(u32, u32); 23] = [ + (0x00A1, 0x00A7), + (0x00A9, 0x00A9), + (0x00AB, 0x00AC), + (0x00AE, 0x00AE), + (0x00B0, 0x00B1), + (0x00B6, 0x00B6), + (0x00BB, 0x00BB), + (0x00BF, 0x00BF), + (0x00D7, 0x00D7), + (0x00F7, 0x00F7), + (0x2010, 0x2027), + (0x2030, 0x203E), + (0x2041, 0x2053), + (0x2055, 0x205E), + (0x2190, 0x245F), + (0x2500, 0x2775), + (0x2794, 0x2BFF), + (0x2E00, 0x2E7F), + (0x3001, 0x3003), + (0x3008, 0x3020), + (0x3030, 0x3030), + (0xFD3E, 0xFD3F), + (0xFE45, 0xFE46), +]; + +/// Whether a non-ASCII code point is `Pattern_Syntax`. +fn is_pattern_syntax(c: u32) -> bool { + PATTERN_SYNTAX + .binary_search_by(|&(lo, hi)| { + if hi < c { + Ordering::Less + } else if lo > c { + Ordering::Greater + } else { + Ordering::Equal + } + }) + .is_ok() +} + /// The Unicode general category of a code point; `None` for a lone surrogate. fn category(c: u32) -> Option { char::from_u32(c).map(get_general_category) diff --git a/crates/js/src/lexer.rs b/crates/js/src/lexer.rs index 8b82570a77..9a6ce8766d 100644 --- a/crates/js/src/lexer.rs +++ b/crates/js/src/lexer.rs @@ -341,7 +341,7 @@ impl<'s> Lexer<'s> { } else { self.decimal() }; - if self.peek().is_some_and(|c| c == BACKSLASH || is_id_start(c) || is_decimal_digit(c)) { + if self.code_point(self.pos).is_some_and(|(c, _)| c == BACKSLASH || is_id_start(c) || is_decimal_digit(c)) { return Err(self.error_at(self.pos, "identifier starts immediately after numeric literal")); } let mut token = self.token(TokenKind::Number(value), start, line, column, false); diff --git a/crates/js/src/tests.rs b/crates/js/src/tests.rs index c1cd095475..8c24b5d0bb 100644 --- a/crates/js/src/tests.rs +++ b/crates/js/src/tests.rs @@ -401,6 +401,118 @@ fn identifier_characters_follow_their_unicode_categories() { assert!(parse("var a\\u00B2 = 1;", &Options::default()).is_err()); } +#[test] +fn identifiers_take_the_other_id_start_and_continue_characters() { + // Other_ID_Start: not letters by category, but ID_Start, so they start and continue a name. + for c in [0x1885, 0x1886, 0x2118, 0x212E, 0x309B, 0x309C] { + let ch = char::from_u32(c).unwrap_or_default(); + for src in [format!("var {ch} = 1;"), format!("var a{ch} = 1;"), format!("var \\u{c:04X}\\u{{{c:X}}} = 1;")] { + let p = ok(&src); + let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!("{src:?}") }; + assert!(decls[0].name.name.contains(ch), "{src:?}"); + } + } + // Other_ID_Continue: may follow the first character, but cannot start a name. + for c in [0xB7, 0x387].into_iter().chain(0x1369..=0x1371).chain([0x19DA, 0x200C, 0x200D, 0x30FB, 0xFF65]) { + let ch = char::from_u32(c).unwrap_or_default(); + for src in [format!("var a{ch} = 1;"), format!("var a\\u{c:04X} = 1;"), format!("var a\\u{{{c:X}}} = 1;")] { + ok(&src); + } + assert!(err(&format!("var {ch} = 1;")).message.contains("unexpected character"), "{c:X}"); + assert!(err(&format!("var \\u{c:04X} = 1;")).message.contains("identifier escape"), "{c:X}"); + assert!(err(&format!("var \\u{{{c:X}}} = 1;")).message.contains("identifier escape"), "{c:X}"); + } +} + +#[test] +fn identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes() { + // U+2E2F is a letter by category but Pattern_Syntax; U+2010, U+00B6 and U+2190 are + // punctuation and symbols in Pattern_Syntax. + for c in [0x2E2F, 0x2010, 0xB6, 0x2190, 0x3001] { + let ch = char::from_u32(c).unwrap_or_default(); + assert!(err(&format!("var {ch} = 1;")).message.contains("unexpected character"), "{c:X}"); + assert!(err(&format!("var a{ch} = 1;")).message.contains("unexpected character"), "{c:X}"); + assert!(err(&format!("var a\\u{c:04X} = 1;")).message.contains("identifier escape"), "{c:X}"); + assert!(err(&format!("var \\u{{{c:X}}} = 1;")).message.contains("identifier escape"), "{c:X}"); + } + for bad in [r"var \uD800 = 1;", r"var a\uDC00 = 1;", r"var a\u{D800} = 1;", r"var a\u{110000} = 1;", r"var a\u{} = 1;"] { + assert!(parse(bad, &Options::default()).is_err(), "{bad}"); + } + // A supplementary letter is one identifier character, at the start and after a number. + let p = ok("var \u{10000}\u{1D7CE} = 1;"); + let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!() }; + assert_eq!(decls[0].name.name, "\u{10000}\u{1D7CE}"); + assert!(err("1\u{10000};").message.contains("immediately after numeric literal")); +} + +/// The code point ranges of `Pattern_Syntax` and `Pattern_White_Space` as Unicode's PropList lists +/// them; Unicode does not change either set. +fn pattern_syntax_and_white_space() -> Vec> { + let pattern = "0009..000D 0020 0021..002F 003A..0040 005B..005E 0060 007B..007E 0085 00A1..00A7 00A9 00AB..00AC 00AE \ + 00B0..00B1 00B6 00BB 00BF 00D7 00F7 200E..200F 2010..2027 2028..2029 2030..203E 2041..2053 2055..205E \ + 2190..245F 2500..2775 2794..2BFF 2E00..2E7F 3001..3003 3008..3020 3030 FD3E..FD3F FE45..FE46"; + pattern + .split_whitespace() + .map(|range| { + let (lo, hi) = range.split_once("..").unwrap_or((range, range)); + let (Ok(lo), Ok(hi)) = (u32::from_str_radix(lo, 16), u32::from_str_radix(hi, 16)) else { panic!("{range}") }; + lo..=hi + }) + .collect() +} + +#[test] +fn no_pattern_syntax_or_white_space_character_is_an_identifier_character() { + use crate::chars::{is_id_part, is_id_start}; + // `$` is Pattern_Syntax but an identifier character in scripts. + let mut checked = 0; + for range in pattern_syntax_and_white_space() { + for c in range.filter(|&c| c != 0x24) { + assert!(!is_id_start(c) && !is_id_part(c), "U+{c:04X}"); + checked += 1; + } + } + assert_eq!(checked, 2760 + 11 - 1); + for c in 0xD800..=0xDFFF { + assert!(!is_id_start(c) && !is_id_part(c), "U+{c:04X}"); + } + assert!(!is_id_start(0x110000) && !is_id_part(0x110000)); +} + +#[test] +fn identifier_characters_are_unicode_16_id_start_and_id_continue() { + use crate::chars::{is_id_part, is_id_start}; + use unicode_general_category::{GeneralCategory as G, get_general_category}; + // Unicode Standard Annex #31: ID_Start is the categories Lu, Ll, Lt, Lm, Lo and Nl plus + // Other_ID_Start; ID_Continue adds Mn, Mc, Nd, Pc and Other_ID_Continue; both leave out + // Pattern_Syntax and Pattern_White_Space. Other_ID_Start and Other_ID_Continue as PropList 16.0 + // lists them. + let other_start = [0x1885..=0x1886, 0x2118..=0x2118, 0x212E..=0x212E, 0x309B..=0x309C]; + let other_continue = [0xB7..=0xB7, 0x387..=0x387, 0x1369..=0x1371, 0x19DA..=0x19DA, 0x200C..=0x200D, 0x30FB..=0x30FB, 0xFF65..=0xFF65]; + let mut excluded = vec![false; 0x11_0000]; + for range in pattern_syntax_and_white_space() { + for c in range { + excluded[c as usize] = true; + } + } + let (mut id_starts, mut id_continues) = (0, 0); + for c in (0..=0x10_FFFF_u32).filter(|c| !(0xD800..=0xDFFF).contains(c)) { + let Some(ch) = char::from_u32(c) else { panic!("U+{c:04X}") }; + let g = get_general_category(ch); + let letter = matches!(g, G::UppercaseLetter | G::LowercaseLetter | G::TitlecaseLetter | G::ModifierLetter | G::OtherLetter | G::LetterNumber); + let id_start = (letter || other_start.iter().any(|r| r.contains(&c))) && !excluded[c as usize]; + let continuing = matches!(g, G::NonspacingMark | G::SpacingMark | G::DecimalNumber | G::ConnectorPunctuation); + let id_continue = (id_start || continuing || other_continue.iter().any(|r| r.contains(&c))) && !excluded[c as usize]; + id_starts += usize::from(id_start); + id_continues += usize::from(id_continue); + // Scripts add `$` and `_` at the start and `$` later (ECMA-262, Names and Keywords). + assert_eq!(is_id_start(c), id_start || c == 0x24 || c == 0x5F, "start U+{c:04X}"); + assert_eq!(is_id_part(c), id_continue || c == 0x24, "part U+{c:04X}"); + } + // The totals of ID_Start and ID_Continue in DerivedCoreProperties 16.0. + assert_eq!((id_starts, id_continues), (141_269, 144_541)); +} + #[test] fn comments_and_line_terminators() { let p = ok("a /* one\ntwo */ b"); diff --git a/docs/mcp.md b/docs/mcp.md index 0b90e47091..566f2e3689 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1525,7 +1525,9 @@ File › Scripts › Other Script… (Cmd+F12) picks a `.js` or `.jsx` file and https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is -not UTF-8. The language is ES5.1. The script reaches the app through one global object: +not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and +`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. The script reaches the +app through one global object: - `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can catch. The documents and the session state the command changed, preferences included, go back, and any file it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 22815e7a77..3b9bc91bdf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -727,6 +727,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`). - 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. - `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 16.0, so characters assigned in later Unicode versions are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_16_id_start_and_id_continue`, which checks every code point, `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`. - `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`.