Files
vectorcraft/crates/js/src/lib.rs
T
dotCooCoo b1e9a4cbb3 Merge main into feat/scripts-api-d6-save-export-open
main's Document member list held saveAs and close as members that are not
available yet; this branch's save_open members implement them, so the
merge drops them from that list and keeps main's other entries. The
script host test lists take main's members together with this branch's
open, userInteractionLevel, fullName, path, saved and option classes,
and the heap accounting keeps main's ModuleNamespace arm beside the
FsEntry string arm.
2026-11-29 14:13:21 -08:00

387 lines
20 KiB
Rust

//! JavaScript for VectorCraft's scripts: an ECMAScript 5.1 lexer and parser
//! (<https://262.ecma-international.org/5.1/>), with the legacy forms of Annex B that older scripts
//! use (octal literals and escapes outside strict mode, function declarations in blocks, the
//! lenient regular expression patterns).
//!
//! [`parse`] reads a script into a [`Program`]: a syntax tree whose expressions, statements and
//! functions live in arenas and carry their source spans. A script that breaks the grammar or one
//! of its early-error rules (section 16: strict mode's restrictions, duplicate parameters in strict
//! code, invalid assignment targets, `break` and `continue` without a target, regular expression
//! literals that are not valid) gives a [`SyntaxError`] with its line and column.
//!
//! With [`Options::preprocessor_lines`], the lexer also reads the preprocessor lines scripts begin
//! with (`#include`, `#includepath`, `#script`, `#strict`, `#target`, `#targetengine`) into
//! [`Directive`]s. They are kept in [`Program::directives`] and never run.
//!
//! The lexer reads the source as UTF-16 code units, as JavaScript does: columns and spans count
//! code units. Nesting is counted: input nested deeper than [`Options::max_depth`] gives a
//! `SyntaxError` ("nesting too deep") instead of exhausting the stack, binary operators, `if` …
//! `else if` chains, labels and prefix operators are read with loops, and the syntax tree is
//! dropped without recursion.
//!
//! A [`Realm`] runs scripts. It compiles the syntax tree to bytecode, checks the bytecode with a
//! verifier, and runs it on an interpreter that keeps JavaScript calls on its own frame stack, so
//! deep recursion in a script does not use the native stack. Objects and environments live in an
//! arena with a mark-and-sweep collector; strings built by repeated `+` are flattened and dropped
//! with loops. The realm provides the language (sections 10 to 14 of ECMA-262 5.1) and these
//! built-ins: the global functions and constants (15.1, with Annex B's `escape` and `unescape`),
//! `Object` (15.2), `Function` with `call`, `apply` and `bind` (15.3), `Array` (15.4), `String`
//! (15.5), `Boolean` (15.6), `Number` (15.7), `Math` (15.8),
//! `Date` (15.9), `RegExp` (15.10), the error types (15.11) and `JSON` (15.12). The array methods
//! visit only the indices an array or array-like object has, so a sparse array of length 2^32-1
//! costs as much as its elements, and `JSON.parse`, `JSON.stringify` and the reviver walk use no
//! native recursion. Regular expressions run on a backtracking matcher that keeps its choice points
//! on its own stack and takes fuel for every step; `Date` reads the clock and time zone the host
//! sets with [`Realm::set_clock`] and [`Realm::set_time_zone`]. The prototype methods are writable
//! and configurable, so scripts can replace them. Every run is bounded
//! by [`Limits`]: instructions run (fuel), heap bytes, frames, nested host calls, and an
//! [`Interrupt`] flag another thread can set. A run that reaches a limit ends with
//! [`RunErrorKind::Limit`], which a script's `try` cannot catch.
//!
//! With [`Options::e4x`], the parser also reads E4X (ECMA-357, second edition, December 2005):
//! XML and XMLList literals, the `.@`, `..`, `::` and `.( )` operators, `for each … in` and
//! `default xml namespace`; the realm then provides `XML`, `XMLList`, `Namespace`, `QName`,
//! `isXMLName` and `setDefaultXMLNamespace`, and XML and XMLList values have an `xpath` method that
//! evaluates an XPath 1.0 expression. Without the option, the language and the built-ins are
//! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and
//! serializing them, and evaluating XPath on them, use no native recursion and take fuel for each
//! node.
//!
//! With [`Options::es2015`], the parser and the realm also read and run a part of ECMAScript 2015
//! (<https://262.ecma-international.org/6.0/>): block-scoped `let` and `const` declarations with
//! their temporal dead zone (section 13.3.1), a new `let` binding for each iteration of a `for`
//! 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), `for … of` loops (section 13.7.5), array and object
//! destructuring in declarations, assignments, parameters and `catch` clauses (sections 12.15.5
//! and 13.3.3), shorthand and computed property names, methods and `__proto__: value` in object
//! literals (sections 12.2.6, 14.3 and B.3.1), classes with `extends`, `super` and `new.target`
//! (sections 14.5, 12.3.5 and 12.3.8), and the `name` property of functions (section 9.2.11).
//! Spread, `for … of` and array patterns use the iterator protocol of the 11th edition
//! (<https://262.ecma-international.org/11.0/>, section 7.4), and a loop or pattern left early
//! closes its iterator. In a realm made without the option and later given it with
//! [`Realm::set_es2015`], which has no `Symbol.iterator`, they walk arrays and `arguments` objects
//! by index and strings by code point, and throw a `TypeError` for other values.
//! Object rest properties (`{ a, ...rest }`) stay syntax errors, and so do `import` and `export`
//! in a script.
//!
//! [`parse_module`] reads a module (section 15.2): strict mode code with those forms and `import`
//! and `export` declarations at its top. [`Realm::start_module`] and [`Realm::run_module`] run a
//! module and the modules it imports, which the host gives through a [`ModuleLoader`]: each module
//! once, after the modules it imports, with each import reading the exporting module's binding. In
//! a cycle of imports, a module is marked as visited before the modules it imports are, so it does
//! not wait for a module that is still waiting for its own imports, and reading a binding of that
//! module before it is initialized throws a `ReferenceError`.
//! Dynamic `import()` is a syntax error.
//!
//! With [`Options::es2015`], the parser and the realm also have generators (ECMA-262 11th edition,
//! sections 14.4 and 25.4): `function*` declarations and expressions, `*name() {…}` methods in
//! object literals, `yield` and `yield*`, which passes `next`, `throw` and `return` on to the
//! iterator it delegates to, and generator objects with `next`, `return` and `throw` from
//! `%GeneratorPrototype%`, reached through `%GeneratorFunction%`. Outside a generator function's
//! body and parameters, `yield` stays an identifier in sloppy code. A generator's suspended frame
//! lives in the heap, each resumption takes fuel and counts against the frame limit, and resuming a
//! generator while its body runs is a `TypeError`.
//!
//! With [`Options::es2015`], the realm also has `Symbol` (ECMA-262 11th edition, section 19.4,
//! <https://262.ecma-international.org/11.0/>): `Symbol.for` and `Symbol.keyFor` over a registry
//! that lasts as long as the realm, the well-known Symbols `iterator`, `asyncIterator`,
//! `hasInstance`, `toPrimitive` and `toStringTag` with the hooks ToPrimitive, `instanceof` and
//! `Object.prototype.toString` read, Symbol-keyed properties with `Object.getOwnPropertySymbols`,
//! and iterator objects with a `next` method from `Array.prototype.values`, `keys`, `entries` and
//! `@@iterator`, `String.prototype[@@iterator]` (by code point) and every `arguments` object.
//! `Date.prototype[@@toPrimitive]` converts a Date without a hint as with the String hint, and an
//! object without an `@@toPrimitive` method, a Date included, converts without a hint as with the
//! Number hint. A Symbol converted to a string or a number without `String(symbol)` or `toString` throws a
//! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator
//! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry
//! entry counts against the heap limit. Registry lookups and insertions take fuel for the key's
//! code units, and a registered description shares the key's existing buffer.
//!
//! With [`Options::es2015`], the realm also provides `Promise` (ECMA-262 11th edition, section
//! 25.6, <https://262.ecma-international.org/11.0/#sec-promise-objects>): the constructor, `then`,
//! `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`. The promise
//! jobs a script queues run in order once its code has ended, before its run ends, on the run's
//! limits; a promise still rejected with no handler at the end is reported by
//! [`Realm::unhandled_rejections`]. [`Realm::add_es2015`] gives a realm made without the option
//! `Promise` for its next runs.
//!
//! With [`Options::es2015`], the realm also provides these ECMAScript 2015 built-ins
//! (<https://262.ecma-international.org/6.0/>): `Map` and `Set` (sections 23.1 and 23.2), whose
//! keys compare with SameValueZero and keep the order they were added in, with `forEach` visiting
//! entries added while it runs; `WeakMap` and `WeakSet` (23.3 and 23.4), whose entries the
//! collector removes once their keys are unreachable; and `ArrayBuffer`, `DataView` and the nine
//! typed arrays (24.1, 24.2 and 22.2). `keys`, `values` and `entries` give iterator objects with
//! a `next` method, and `Map`, `Set` and the typed arrays are iterable. The collection
//! constructors read their argument through its `@@iterator` method (sections 23.1.1.1 to
//! 23.4.1.1), so an object without one is a `TypeError`, and a `Map` entry that is not an object
//! is a `TypeError` too. A typed array constructor given an object that is not a buffer or a typed
//! array, and `%TypedArray%.from`, read a source with an `@@iterator` method through its iterator
//! and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1). A
//! typed array constructor converts a first argument that is not an object to a length. A buffer longer than the heap
//! limit is a `RangeError`, and its bytes are checked against the heap before they are allocated.
#![forbid(unsafe_code)]
pub mod ast;
mod builtins;
mod bytecode;
mod chars;
mod class_ops;
mod compiler;
mod date_builtins;
mod error;
mod file_classes;
mod generator;
mod heap;
mod host;
mod host_classes;
mod interp;
mod iteration;
mod lexer;
mod module;
mod number;
mod number_builtins;
mod parser;
mod realm;
mod reflect;
mod regexp;
mod regexp_builtins;
mod regexp_vm;
pub mod scriptui;
mod scriptui_resource;
mod string_builtins;
mod symbol;
mod token;
mod unit_value;
mod value;
mod xml;
mod xml_builtins;
mod xmp;
mod xmp_classes;
mod xpath;
pub use ast::{
AssignOp, Ast, BinaryOp, Binding, CatchClause, ClassDef, ClassElement, ClassKey, DEFAULT_BINDING, ExportEntry, Expr, ExprId, ForInTarget,
ForInit, Function, FunctionId, FunctionKind, ImportEntry, ImportName, LexKind, LogicalOp, MethodKind, ModuleInfo, ModuleRequest, Name, Program,
Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
};
pub use builtins::extensions::Localization;
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
pub use file_classes::{FOLDER_REF_KEY, file_ref, folder_ref};
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
pub use host_classes::{ArgInfo, FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, MemberInfo, file_ref_path, host_ref, host_ref_parts};
pub use lexer::{Goal, Lexer};
pub use module::{LoadError, LoadedModule, ModuleLimits, ModuleLoader};
pub use number::to_string as number_to_string;
pub use realm::{
Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE,
};
pub use reflect::MAX_REFLECTED_MEMBERS;
pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind};
pub use xmp::{MAX_BYTES as XMP_MAX_BYTES, PacketSpan, find_packet as find_xmp_packet};
/// How a script is read.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Options {
/// The script is strict mode code from its start, as code passed to a strict `eval` is.
pub strict: bool,
/// Read preprocessor lines (`#target …` and the other directives) into [`Directive`]s. Off,
/// a `#` is an unexpected character, as ECMA-262 has it.
pub preprocessor_lines: bool,
/// How deeply statements, expressions, functions and regular expression groups may nest.
pub max_depth: usize,
/// The most UTF-16 code units a source may hold.
pub max_source_units: usize,
/// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins.
pub e4x: bool,
/// Read and run the ECMAScript 2015 forms this engine has: `let` and `const`, arrow functions,
/// template literals (tagged ones included), default and rest parameters, spread in array
/// literals, calls and `new`, `for … of`, array and object destructuring, shorthand and
/// computed property names, methods in object literals, and classes with `super` and
/// `new.target`, and from ECMAScript 2020 optional chains (`a?.b`, `a?.[k]`, `f?.()`) and
/// `??`. Off, they are syntax errors and the language is ES5.1's. Code a
/// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts.
/// A realm made with it on also has the later editions' built-ins this engine has: `Symbol`
/// with Symbol-keyed properties, the iterators of arrays, strings and `arguments` objects,
/// `Promise` with its job queue, `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`
/// and the typed arrays. A realm made with it off has the ES5.1 built-ins only, as the
/// app's scripts expect. Those built-ins are chosen when the realm is made: turning the option
/// on or off later with [`Realm::set_es2015`] changes the language later runs read, and does
/// not add or remove them; [`Realm::add_es2015`] adds `Promise` to a realm made without it.
/// Runs with it on also convert `0b` and `0o` strings to numbers.
pub es2015: bool,
}
impl Default for Options {
fn default() -> Self {
Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false }
}
}
/// The default [`Options::max_depth`]: deeper than scripts nest, and shallow enough for the stack
/// of a wasm build or a secondary thread.
pub const DEFAULT_MAX_DEPTH: usize = 200;
/// Parses `source` as a script.
pub fn parse(source: &str, options: &Options) -> Result<Program, SyntaxError> {
let units = to_utf16(source, options)?;
parse_utf16(&units, options)
}
/// Parses `source`, in UTF-16 code units, as a script.
pub fn parse_utf16(source: &[u16], options: &Options) -> Result<Program, SyntaxError> {
check_length(source.len(), options)?;
parser::Parser::new(source, options, false)?.parse_program().map(|(program, _)| program)
}
/// Parses `source` as a module (ECMA-262 2015 section 15.2): strict mode code with
/// [`Options::es2015`]'s forms, `import` and `export` declarations at its top, and no preprocessor
/// lines, whatever `options` says about those three. Gives its statements and what it imports and
/// exports.
pub fn parse_module(source: &str, options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> {
let units = to_utf16(source, options)?;
parse_module_utf16(&units, options)
}
/// Parses `source`, in UTF-16 code units, as a module ([`parse_module`]).
pub fn parse_module_utf16(source: &[u16], options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> {
check_length(source.len(), options)?;
parser::Parser::new(source, &module_options(options), false)?.parse_module().map(|(program, info, _)| (program, info))
}
/// The tokens of `source` as [`tokenize`] gives them, with `source` read as a module
/// ([`parse_module`]). The source must be a valid module.
pub fn tokenize_module(source: &str, options: &Options) -> Result<Vec<Token>, SyntaxError> {
let units = to_utf16(source, options)?;
check_length(units.len(), options)?;
parser::Parser::new(&units, &module_options(options), true)?.parse_module().map(|(_, _, tokens)| tokens)
}
/// `options` as a module is read with them.
pub(crate) fn module_options(options: &Options) -> Options {
Options { strict: true, es2015: true, preprocessor_lines: false, ..options.clone() }
}
/// [`parse_utf16`] for code a direct `eval` runs, which may use `super` and `new.target` as the
/// code that calls it may (ECMA-262 2015 section 18.2.1.1).
pub(crate) fn parse_utf16_with_supers(source: &[u16], options: &Options, rules: parser::SuperRules) -> Result<Program, SyntaxError> {
check_length(source.len(), options)?;
parser::Parser::new(source, options, false)?.with_supers(rules).parse_program().map(|(program, _)| program)
}
/// The tokens of `source`, in order, as the parser reads them: preprocessor lines included, and
/// each `/` read as division or as the start of a regular expression literal as the grammar
/// decides. The source must be a valid script.
pub fn tokenize(source: &str, options: &Options) -> Result<Vec<Token>, SyntaxError> {
let units = to_utf16(source, options)?;
check_length(units.len(), options)?;
parser::Parser::new(&units, options, true)?.parse_program().map(|(_, tokens)| tokens)
}
fn to_utf16(source: &str, options: &Options) -> Result<Vec<u16>, SyntaxError> {
// A source's UTF-16 length is at most its UTF-8 length; count only a source that may be too
// long.
if source.len() > options.max_source_units {
check_length(source.encode_utf16().count(), options)?;
}
Ok(source.encode_utf16().collect())
}
fn check_length(units: usize, options: &Options) -> Result<(), SyntaxError> {
if units > options.max_source_units || u32::try_from(units).is_err() {
return Err(SyntaxError { message: TOO_LONG.into(), line: 1, column: 1, offset: 0 });
}
Ok(())
}
/// Where each line of a source starts, for turning offsets into lines and columns.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct LineTable {
starts: Vec<u32>,
/// The source ends with a line terminator.
ends_with_break: bool,
empty: bool,
}
impl LineTable {
pub(crate) fn new(src: &[u16]) -> Self {
let mut starts = vec![0];
let mut i = 0;
while let Some(&u) = src.get(i) {
i += 1;
let terminator = match u {
0x0D if src.get(i) == Some(&0x0A) => {
i += 1;
true
}
0x0A | 0x0D | 0x2028 | 0x2029 => true,
_ => false,
};
if terminator {
starts.push(u32::try_from(i).unwrap_or(u32::MAX));
}
}
let ends_with_break = src.last().is_some_and(|&u| matches!(u, 0x0A | 0x0D | 0x2028 | 0x2029));
Self { starts, ends_with_break, empty: src.is_empty() }
}
pub(crate) fn line_column(&self, offset: u32) -> (u32, u32) {
let line = self.starts.partition_point(|&s| s <= offset).max(1);
let start = self.starts.get(line - 1).copied().unwrap_or(0);
(u32::try_from(line).unwrap_or(u32::MAX), offset.saturating_sub(start) + 1)
}
/// The estimated bytes the table holds.
pub(crate) fn heap_bytes(&self) -> usize {
32 + 4 * self.starts.len()
}
pub(crate) fn line_count(&self) -> u32 {
if self.empty {
return 0;
}
let breaks = self.starts.len() - 1;
u32::try_from(breaks + usize::from(!self.ends_with_break)).unwrap_or(u32::MAX)
}
}
#[cfg(test)]
mod builtins_tests;
#[cfg(test)]
mod collections_tests;
#[cfg(test)]
mod es2015_object_tests;
#[cfg(test)]
mod es2015_tests;
#[cfg(test)]
mod es2020_tests;
#[cfg(test)]
mod extension_tests;
#[cfg(test)]
mod generator_tests;
#[cfg(test)]
mod host_tests;
#[cfg(test)]
mod interp_tests;
#[cfg(test)]
mod module_tests;
#[cfg(test)]
mod promise_tests;
#[cfg(test)]
mod reflect_tests;
#[cfg(test)]
mod scriptui_tests;
#[cfg(test)]
mod symbol_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod text_tests;
#[cfg(test)]
mod unit_value_tests;
#[cfg(test)]
mod xml_tests;
#[cfg(test)]
mod xmp_tests;