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.
This commit is contained in:
dotCooCoo committed 2026-11-28 17:34:04 -08:00
1 parent 31a5e30057
commit 8a269c4ce8
9 files changed
+127 -28

No files matched your search

+3
View File
@@ -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 {
+4
View File
@@ -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.
+20 -4
View File
@@ -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<u32> {
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<Source>, recursion: u32, bind_name: bool, es2015: bool) -> CResult<Rc<Code>> {
/// 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<Source>,
recursion: u32,
bind_name: bool,
es2015: bool,
outer: SuperRules,
) -> CResult<Rc<Code>> {
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<Source>,
pub(crate) fn compile_program(program: &crate::Program, source: &Rc<Source>, kind: CodeKind) -> CResult<Rc<Code>> {
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)
}
+50
View File
@@ -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();";
+11 -9
View File
@@ -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<Rc<Code>, 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<Rc<Code>, 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<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 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);
+1
View File
@@ -1048,6 +1048,7 @@ fn code(ops: Vec<Op>) -> Code {
own_name: None,
method: false,
generator: false,
supers: crate::parser::SuperRules::default(),
}
}
+4 -4
View File
@@ -219,11 +219,11 @@ 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> {
/// [`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_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
+30 -10
View File
@@ -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<crate::ast::FunctionId> {
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);
+4 -1
View File
@@ -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