mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge pull request #9997 from dotCooCoo/fix/js-eval-new-target
Scripts: direct eval inside a function reads its new.target
This commit is contained in:
8 files changed
+72
-5
No files matched your search
@@ -67,6 +67,27 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `new.target` of the function the running code is in, for a direct `eval` it calls:
|
||||
/// `None` outside a function. A function that calls `eval` keeps its `new.target` in a hidden
|
||||
/// binding ([`Interp::function_bindings`]). Each scope looked at takes a unit of fuel.
|
||||
pub(crate) fn caller_new_target(&mut self) -> JsResult<Option<Value>> {
|
||||
let mut cur = Some(self.frame()?.env);
|
||||
while let Some(e) = cur {
|
||||
self.use_fuel()?;
|
||||
cur = match self.heap.env(e) {
|
||||
Some(Env::Decl { bindings, outer }) => {
|
||||
if bindings.contains(NEW_TARGET) {
|
||||
return self.binding_value(e, NEW_TARGET).map(Some);
|
||||
}
|
||||
*outer
|
||||
}
|
||||
Some(Env::Obj { outer, .. }) => *outer,
|
||||
None => None,
|
||||
};
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Adds the hidden bindings of a call to `code` to its function environment `env`: a derived
|
||||
/// class constructor's `this`, function object and `new.target`, and the `new.target` of a
|
||||
/// function whose arrow functions read it. Gives the environment of a derived constructor's
|
||||
|
||||
@@ -1950,6 +1950,9 @@ impl<'a> FnCompiler<'a> {
|
||||
if eval {
|
||||
self.uses_arguments = true;
|
||||
self.uses_this = true;
|
||||
// The eval code may read `new.target`, even when a later run reads
|
||||
// scripts as ECMAScript 2015 and this code was read as ES5.1.
|
||||
self.uses_new_target = true;
|
||||
}
|
||||
if self.has_spread(args) {
|
||||
self.spread_args(args)?;
|
||||
|
||||
@@ -1624,6 +1624,21 @@ fn new_target_names_the_constructor_new_was_applied_to() {
|
||||
truth("function F() { this.t = new.target; } var B = F.bind(null); new B().t === F");
|
||||
}
|
||||
|
||||
/// A direct `eval` inside a function reads the function's `new.target`, from an arrow function
|
||||
/// and a nested `eval` too; outside a function, and through an indirect `eval`, it is a
|
||||
/// `SyntaxError`.
|
||||
#[test]
|
||||
fn eval_inside_a_function_reads_its_new_target() {
|
||||
truth("function F() { return eval('new.target'); } new F() === F && F() === undefined");
|
||||
truth("function F() { 'use strict'; return eval('new.target'); } new F() === F");
|
||||
truth("function F() { return (() => eval('new.target'))(); } new F() === F");
|
||||
truth("function F() { return eval('eval(\"new.target\")'); } new F() === F");
|
||||
truth("class A { constructor() { this.t = eval('new.target'); } } class B extends A {} new B().t === B");
|
||||
throws("eval('new.target')", "SyntaxError");
|
||||
throws("(() => eval('new.target'))()", "SyntaxError");
|
||||
throws("function F() { return (0, eval)('new.target'); } new F()", "SyntaxError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_class_chains_stay_within_the_limits() {
|
||||
let src = "var C = class {}; for (var i = 0; i < 2000; i++) { C = class extends C {}; } new C();";
|
||||
|
||||
+15
-3
@@ -3539,10 +3539,17 @@ impl Interp {
|
||||
|
||||
/// [`Interp::compile_source`], with [`crate::bytecode::Source::strict_writes`] set to `writes`.
|
||||
pub(crate) fn compile_source_writes(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind) -> Result<Rc<Code>, CompileError> {
|
||||
self.compile_units(units, strict, writes, kind, false)
|
||||
}
|
||||
|
||||
/// [`Interp::compile_source_writes`]; `in_function` reads eval code run inside a function,
|
||||
/// where `new.target` is allowed.
|
||||
fn compile_units(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind, in_function: bool) -> Result<Rc<Code>, CompileError> {
|
||||
self.source_units = self.source_units.saturating_add(units.len());
|
||||
let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len()));
|
||||
let options = Options { strict, max_source_units: remaining, ..self.options.clone() };
|
||||
let program = crate::parse_utf16(units, &options).map_err(CompileError::Syntax)?;
|
||||
let parse = if in_function { crate::parse_utf16_in_function } else { crate::parse_utf16 };
|
||||
let program = parse(units, &options).map_err(CompileError::Syntax)?;
|
||||
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes });
|
||||
compile_program(&program, &source, kind).map_err(|e| match e {
|
||||
CompileFail::Syntax(s) => CompileError::Syntax(s),
|
||||
@@ -3569,7 +3576,10 @@ impl Interp {
|
||||
self.prepare_source(s.len())?;
|
||||
let units = self.flat_reserved(s)?;
|
||||
self.observe_code(&units);
|
||||
let code = self.compile_source(&units, strict, CodeKind::Eval).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
// Inside a function the eval code reads the function's `new.target` (section 18.2.1.1).
|
||||
let new_target = self.caller_new_target()?;
|
||||
let writes = self.writes_mode();
|
||||
let code = self.compile_units(&units, strict, writes, CodeKind::Eval, new_target.is_some()).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?;
|
||||
let frame = self.frame()?;
|
||||
let (caller_env, caller_var_env, this, this_in_env) = (frame.env, frame.var_env, frame.this.clone(), frame.this_in_env);
|
||||
@@ -3584,7 +3594,9 @@ impl Interp {
|
||||
let env = self.instantiate_pending(&code, env, var_env, true)?;
|
||||
self.push_code_frame(code, env, var_env, this, false)?;
|
||||
// The eval code reads `this` the way the code that called it does (section 18.2.1.1).
|
||||
self.frame_mut()?.this_in_env = this_in_env;
|
||||
let frame = self.frame_mut()?;
|
||||
frame.this_in_env = this_in_env;
|
||||
frame.new_target = new_target.and_then(|v| v.as_object());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -219,6 +219,13 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result<Program, SyntaxE
|
||||
parser::Parser::new(source, options, false)?.parse_program().map(|(program, _)| program)
|
||||
}
|
||||
|
||||
/// [`parse_utf16`] for code a direct `eval` runs inside a function, where `new.target` is allowed
|
||||
/// (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) fn parse_utf16_in_function(source: &[u16], options: &Options) -> Result<Program, SyntaxError> {
|
||||
check_length(source.len(), options)?;
|
||||
parser::Parser::new(source, options, false)?.with_new_target().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.
|
||||
|
||||
@@ -176,6 +176,12 @@ impl<'s> Parser<'s> {
|
||||
Ok(parser)
|
||||
}
|
||||
|
||||
/// Allows `new.target` at the top of the source: eval code run inside a function.
|
||||
pub(crate) fn with_new_target(mut self) -> Self {
|
||||
self.supers.new_target = self.es2015;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn parse_program(mut self) -> Result<(Program, Vec<Token>)> {
|
||||
let body = self.parse_body(false)?;
|
||||
if self.tok.kind != TokenKind::Eof {
|
||||
|
||||
+4
-1
@@ -2752,7 +2752,10 @@ declarations scoped to their block, arrow functions, template literals and tagge
|
||||
parameters, spread in array literals, calls and `new`, `for`-`of` loops, array and object destructuring in `var`,
|
||||
`let` and `const` declarations, assignments, parameters and `catch` clauses (with defaults, holes and rest elements),
|
||||
shorthand and computed property names in object literals, and classes with `extends`, `static` members, accessors and
|
||||
computed method names, `super` calls and properties and `new.target` (https://262.ecma-international.org/11.0/). A
|
||||
computed method names, `super` calls and properties and `new.target` (https://262.ecma-international.org/11.0/).
|
||||
`new.target` in a string given to direct `eval` inside a function, or inside an arrow function within one, reads that
|
||||
function's `new.target`; at the top of a script, in an arrow function at the top of a script and through an indirect
|
||||
`eval` it is a `SyntaxError`. A
|
||||
class can extend a class, a function, `null` or the built-in constructors `Object`, `Function`, `Array`, `String`,
|
||||
`Number`, `Boolean`, `RegExp`, `Date` and the error types. A class can name another built-in constructor in
|
||||
`extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is
|
||||
|
||||
@@ -1176,7 +1176,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`.
|
||||
- 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 uses the iterator protocol (see the `for`-`of` line below). 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. Modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
The collector retains tagged-template cache entries only while the site's code is reachable.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `super` and `new.target` in code given to direct `eval` are not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_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), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), 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: 7,000 of 7,070 runs pass (the 35 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,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 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`.
|
||||
|
||||
Reference in new issue
Block a user