From 8a269c4ce80af6957f053fae79a2ce1b793c45ba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 17:34:04 -0800 Subject: [PATCH] Scripts: direct eval inside a method or derived constructor reads super In a .js script, `class B extends A { m() { return eval("super.x"); } }` and `class B extends A { constructor() { eval("super()"); } }` threw a SyntaxError: eval code was parsed with only `new.target` allowed, never `super` (ECMA-262 2015 section 18.2.1.1). Each compiled code now records what `super` and `new.target` may do in eval code it runs: the rules of its function's body, the rules of the code around an arrow function, or the rules the eval code itself was read with. A direct eval parses its code with the caller's rules, so `super.name` and `super[key]` work inside a method, accessor or class constructor, and `super(...)` works inside a derived class's constructor, also from an arrow function or a nested eval there. A plain function inside a method, the top of a script, an indirect eval and a `Function` body still give a SyntaxError. `super(...)` in eval code binds `this` once; a second call is a ReferenceError. Two tests in es2015_tests.rs cover the allowed and SyntaxError cases and fail without the change; a third checks that a `Function` body reads its own `new.target`. docs/mcp.md describes the rule. Follows #9094. --- crates/js/src/ast.rs | 3 +++ crates/js/src/bytecode.rs | 4 +++ crates/js/src/compiler.rs | 24 ++++++++++++++--- crates/js/src/es2015_tests.rs | 50 +++++++++++++++++++++++++++++++++++ crates/js/src/interp.rs | 20 +++++++------- crates/js/src/interp_tests.rs | 1 + crates/js/src/lib.rs | 8 +++--- crates/js/src/parser.rs | 40 +++++++++++++++++++++------- docs/mcp.md | 5 +++- 9 files changed, 127 insertions(+), 28 deletions(-) diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index a0bf7f1f09..c23f8c6767 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -614,6 +614,9 @@ pub struct Program { pub(crate) lines: crate::LineTable, /// It was read with [`crate::Options::es2015`]. pub(crate) es2015: bool, + /// What `super` and `new.target` may do at its top: nothing in a script, and in eval code + /// what they may do in the code that calls a direct `eval` (ECMA-262 2015 section 18.2.1.1). + pub(crate) supers: crate::parser::SuperRules, } impl Program { diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 101e3e55b5..cda3d45ece 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -453,6 +453,10 @@ pub(crate) struct Code { /// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]), /// and it is not a constructor. pub(crate) generator: bool, + /// What `super` and `new.target` may do in eval code a direct `eval` in this code runs: the + /// rules of the function's body, of the code around an arrow function, or those eval code was + /// read with (ECMA-262 2015 section 18.2.1.1). + pub(crate) supers: crate::parser::SuperRules, } /// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors. diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index ee3151cd2d..1f6d12091d 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -25,6 +25,7 @@ use crate::ast::{ use crate::bytecode::{BlockScope, Code, CodeKind, Handler, NamePrefix, Op, Source, Template, fallthrough_effect, verify}; use crate::error::{SyntaxError, TOO_DEEP}; use crate::heap::Key; +use crate::parser::SuperRules; use crate::value::Str; use pattern::Mode; @@ -112,6 +113,8 @@ struct FnCompiler<'a> { optional: Vec<(Label, u32)>, /// The code is a generator function's. generator: bool, + /// [`Code::supers`]. + supers: SuperRules, } /// The `var` names and function declarations a body hoists. @@ -162,6 +165,7 @@ impl<'a> FnCompiler<'a> { annex: HashSet::new(), optional: Vec::new(), generator: false, + supers: SuperRules::default(), } } @@ -501,7 +505,7 @@ impl<'a> FnCompiler<'a> { /// Compiles a nested function and returns its index in the function table. fn function(&mut self, fid: FunctionId) -> CResult { - let code = compile_function(self.ast, fid, self.source, self.recursion, true, self.es2015)?; + let code = compile_function(self.ast, fid, self.source, self.recursion, true, self.es2015, self.supers)?; // An arrow function reads the `this`, `arguments` and `new.target` of the code around it. if code.arrow { self.uses_this |= code.uses_this; @@ -2389,6 +2393,7 @@ impl<'a> FnCompiler<'a> { own_name: meta.own_name, method: meta.method, generator: self.generator, + supers: self.supers, }; code.max_stack = verify(&code).map_err(CompileFail::Internal)?; Ok(Rc::new(code)) @@ -2419,12 +2424,22 @@ fn len_u32(n: usize) -> u32 { } /// Compiles function `fid` of `ast`. With `bind_name`, a function expression's name is bound -/// inside it. `es2015` is [`crate::Options::es2015`] of the script it is in. -pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, recursion: u32, bind_name: bool, es2015: bool) -> CResult> { +/// inside it. `es2015` is [`crate::Options::es2015`] of the script it is in, and `outer` the +/// [`Code::supers`] of the code around it, which an arrow function keeps. +pub(crate) fn compile_function( + ast: &Ast, + fid: FunctionId, + source: &Rc, + recursion: u32, + bind_name: bool, + es2015: bool, + outer: SuperRules, +) -> CResult> { let Some(f) = ast.function(fid) else { return internal("function out of range") }; let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion); c.es2015 = es2015; c.generator = f.generator; + c.supers = if f.kind == FunctionKind::Arrow { outer } else { SuperRules::function(f.home, f.kind == FunctionKind::DerivedConstructor) }; c.at(f.span.start); c.enter()?; // A destructured parameter has a binding of its own under a name no script can write, which @@ -2515,6 +2530,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, pub(crate) fn compile_program(program: &crate::Program, source: &Rc, kind: CodeKind) -> CResult> { let mut c = FnCompiler::new(&program.ast, source, kind, program.strict, 0); c.es2015 = program.es2015; + c.supers = program.supers; let hoisted = c.hoist(&program.body, &[])?; let top_scope = c.list_scope(&program.body, false)?; c.stmts(&program.body)?; @@ -2531,5 +2547,5 @@ pub(crate) fn compile_constructed_function(program: &crate::Program, source: &Rc let Some(Stmt::Expr(e)) = program.ast.stmt(*stmt) else { return Ok(None) }; let Some(Expr::Paren(inner)) = program.ast.expr(*e) else { return Ok(None) }; let Some(Expr::Function(fid)) = program.ast.expr(*inner) else { return Ok(None) }; - compile_function(&program.ast, *fid, source, 0, false, program.es2015).map(Some) + compile_function(&program.ast, *fid, source, 0, false, program.es2015, program.supers).map(Some) } diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index cc8e246d2d..00d0874111 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -1639,6 +1639,56 @@ fn eval_inside_a_function_reads_its_new_target() { throws("function F() { return (0, eval)('new.target'); } new F()", "SyntaxError"); } +/// A direct `eval` inside a method reads `super` properties of the method's home object, from an +/// arrow function and a nested `eval` too; in a function that is not a method, at the top of a +/// script, through an indirect `eval` and in a `Function` body it is a `SyntaxError`. +#[test] +fn eval_inside_a_method_reads_super_properties() { + truth("class A { get x() { return 'a' + this.n; } } class B extends A { m() { this.n = 1; return eval('super.x'); } } new B().m() === 'a1'"); + truth("class A { f() { return 3; } } class B extends A { m() { return (() => eval('super.f()'))(); } } new B().m() === 3"); + truth("class A { f() { return 3; } } class B extends A { m() { return eval('eval(\"super[\\'f\\']()\")'); } } new B().m() === 3"); + truth("class A { f() { return 3; } } class B extends A { m() { return eval('() => super.f()')(); } } new B().m() === 3"); + truth("class A {} class B extends A { m() { eval('super.y = 5'); return this.y; } } new B().m() === 5"); + truth("class A { static s() { return 4; } } class B extends A { static s() { return eval('super.s()'); } } B.s() === 4"); + truth("class A { constructor() { this.t = eval('super.constructor'); } } new A().t === Object"); + truth("var o = { __proto__: { x: 2 }, m() { 'use strict'; return eval('super.x'); } }; o.m() === 2"); + throws("function F() { return eval('super.x'); } F()", "SyntaxError"); + throws("eval('super.x')", "SyntaxError"); + throws("class A { m() { return (function () { return eval('super.x'); })(); } } new A().m()", "SyntaxError"); + throws("class A { m() { return (0, eval)('super.x'); } } new A().m()", "SyntaxError"); + throws("class A { m() { return Function('return super.x'); } } new A().m()", "SyntaxError"); +} + +/// A direct `eval` inside a derived class's constructor calls the superclass's constructor with +/// `super(…)` and binds `this` once; elsewhere `super(…)` in eval code is a `SyntaxError`. +#[test] +fn eval_inside_a_derived_constructor_calls_super() { + let a = "class A { constructor(v) { this.a = v; this.t = new.target; } } "; + truth(&format!( + "{a}class B extends A {{ constructor() {{ eval('super(1)'); this.b = 2; }} }} var b = new B(); b.a === 1 && b.b === 2 && b.t === B && b instanceof B" + )); + truth(&format!("{a}class B extends A {{ constructor() {{ var r = eval('super(1)'); this.r = r === this; }} }} new B().r")); + truth(&format!("{a}class B extends A {{ constructor() {{ (() => eval('super(1)'))(); }} }} new B().a === 1")); + truth(&format!("{a}class B extends A {{ constructor() {{ 'use strict'; eval('super(1)'); }} }} new B().a === 1")); + throws(&format!("{a}class B extends A {{ constructor() {{ super(1); eval('super(2)'); }} }} new B()"), "ReferenceError"); + throws(&format!("{a}class B extends A {{ constructor() {{ eval('super(1); super(2)'); }} }} new B()"), "ReferenceError"); + throws(&format!("{a}class B extends A {{ constructor() {{ eval('this'); super(1); }} }} new B()"), "ReferenceError"); + throws("class A { constructor() { eval('super()'); } } new A()", "SyntaxError"); + throws(&format!("{a}class B extends A {{ m() {{ eval('super()'); }} }} new B(1).m()"), "SyntaxError"); + throws(&format!("{a}class B extends A {{ constructor() {{ (function () {{ eval('super(1)'); }})(); }} }} new B()"), "SyntaxError"); + throws(&format!("{a}class B extends A {{ constructor() {{ (0, eval)('super(1)'); }} }} new B()"), "SyntaxError"); + throws(&format!("{a}class B extends A {{ constructor() {{ Function('super(1)'); }} }} new B()"), "SyntaxError"); + throws("function F() { eval('super()'); } F()", "SyntaxError"); + throws("eval('super()')", "SyntaxError"); +} + +/// A `Function` body reads its own `new.target`, wherever the `Function` constructor is called. +#[test] +fn a_function_body_reads_its_own_new_target() { + truth("var G = Function('return new.target'); new G() === G && G() === undefined"); + truth("class A { m() { return Function('return new.target')(); } } new A().m() === undefined"); +} + #[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();"; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index ffc58e64da..66b73a83b2 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -29,6 +29,7 @@ use crate::heap::{ ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes, }; +use crate::parser::SuperRules; use crate::string_builtins::flat_charged; use crate::symbol::PropKey; use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32}; @@ -3545,17 +3546,16 @@ 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, CompileError> { - self.compile_units(units, strict, writes, kind, false) + self.compile_units(units, strict, writes, kind, SuperRules::default()) } - /// [`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, CompileError> { + /// [`Interp::compile_source_writes`]; `supers` says what `super` and `new.target` may do at + /// the top of the code: what they may do where a direct `eval` is called. + fn compile_units(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind, supers: SuperRules) -> Result, 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 parse = if in_function { crate::parse_utf16_in_function } else { crate::parse_utf16 }; - let program = parse(units, &options).map_err(CompileError::Syntax)?; + let program = crate::parse_utf16_with_supers(units, &options, supers).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), @@ -3582,10 +3582,12 @@ impl Interp { self.prepare_source(s.len())?; let units = self.flat_reserved(s)?; self.observe_code(&units); - // Inside a function the eval code reads the function's `new.target` (section 18.2.1.1). - let new_target = self.caller_new_target()?; + // The eval code may use `super` and `new.target` as the code that calls it may, and reads + // the `new.target` of the function it is in (section 18.2.1.1). + let supers = self.frame()?.code.supers; + let new_target = if supers.new_target { self.caller_new_target()? } else { None }; 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))?; + let code = self.compile_units(&units, strict, writes, CodeKind::Eval, supers).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); diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 2dc3008630..cf47fa9848 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -1048,6 +1048,7 @@ fn code(ops: Vec) -> Code { own_name: None, method: false, generator: false, + supers: crate::parser::SuperRules::default(), } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 346f21eb58..c3ae4acfcd 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -219,11 +219,11 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result Result { +/// [`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 { check_length(source.len(), options)?; - parser::Parser::new(source, options, false)?.with_new_target().parse_program().map(|(program, _)| program) + 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 diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index a7852f2d14..bb35c08212 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -68,14 +68,23 @@ struct Scope { /// What `super` and `new.target` may do where the parser is (ECMA-262 2015 sections 12.3.5.1, /// 12.3.8.1, 14.1.2, 14.5.1 and 15.1.1): set for each function body and kept by arrow functions. -#[derive(Clone, Copy, Debug, Default)] -struct SuperRules { +/// Eval code run by a direct `eval` has the rules of the code that calls it (section 18.2.1.1). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct SuperRules { /// `super.property` and `super[index]`: in a class's methods, accessors and constructor. - property: bool, + pub(crate) property: bool, /// `super(arguments)`: in a derived class's constructor. - call: bool, + pub(crate) call: bool, /// `new.target`: in any function other than an arrow function at the top of a script. - new_target: bool, + pub(crate) new_target: bool, +} + +impl SuperRules { + /// The rules in the body of a function that is not an arrow function: `home` for one with a + /// home object, `derived` for a derived class's constructor. + pub(crate) fn function(home: bool, derived: bool) -> Self { + Self { property: home, call: derived, new_target: true } + } } /// The parameters of a function as they are read: names or patterns, each one's default value, @@ -176,9 +185,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; + /// Reads the top of the source with `rules`: eval code run by a direct `eval` inside a + /// function. Without [`crate::Options::es2015`] the rules stay the default. + pub(crate) fn with_supers(mut self, rules: SuperRules) -> Self { + if self.es2015 { + self.supers = rules; + } self } @@ -190,7 +202,15 @@ impl<'s> Parser<'s> { if let Some(tokens) = &mut self.tokens { tokens.push(self.tok.clone()); } - let program = Program { ast: self.ast, body, strict: self.ctx.strict, directives: self.directives, lines: self.lines, es2015: self.es2015 }; + let program = Program { + ast: self.ast, + body, + strict: self.ctx.strict, + directives: self.directives, + lines: self.lines, + es2015: self.es2015, + supers: self.supers, + }; Ok((program, self.tokens.unwrap_or_default())) } @@ -1149,7 +1169,7 @@ impl<'s> Parser<'s> { generator: bool, ) -> Result { self.enter()?; - let rules = SuperRules { property: home, call: kind == FunctionKind::DerivedConstructor, new_target: true }; + let rules = SuperRules::function(home, kind == FunctionKind::DerivedConstructor); let outer = std::mem::replace(&mut self.supers, rules); // The parameters are read with the function's own `yield` rule, not the enclosing code's. let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); diff --git a/docs/mcp.md b/docs/mcp.md index 9fc37a4e00..55bfb519b8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2764,7 +2764,10 @@ shorthand and computed property names in object literals, and classes with `exte 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 +`eval` it is a `SyntaxError`. In the same way, a string given to direct `eval` may use `super.name` and `super[key]` +inside a method, accessor or class constructor, and `super(…)` inside a derived class's constructor, also from an +arrow function within one; elsewhere, through an indirect `eval` and in a `Function` body they are a `SyntaxError` +(https://262.ecma-international.org/6.0/#sec-performeval). 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