mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Scripts: class code, eval and block functions follow the ES2015 rules
- Direct eval in a derived constructor, or in an arrow function inside
one, reads the constructor's this binding when it runs, so
eval('this') before super() throws a ReferenceError, and an arrow
function made by the eval code sees this once super() returns.
- A class's heritage and computed keys run as strict mode code inside
sloppy code; the code after the class, and a handler of what they
throw, stay sloppy.
- A super property write that cannot be made throws with
Realm::set_strict_writes, as other property writes do.
- A labeled function in a block is made when the block is entered and
declares its name in the block, so { let f; L: function f() {} } is
a SyntaxError. A block function whose name a function of an
enclosing block also declares no longer assigns the outer variable.
- Methods reject duplicate parameter names outside strict mode code.
- With a global object that is not extensible, a var that would add a
property throws a TypeError before the script or the eval code
declares anything.
- The receiver, arguments and new.target of a call, a strict eval's
own environment and spread's elements stay reachable while their
scopes and properties are made, and spread counts the array's new
properties against the heap limit before it adds them.
- Tagged template strings objects are dropped once nothing but the
cache holds their code, also for code with several sites.
- A //@ or # directive after a template with a substitution that
spans lines is read only at the start of a line.
- The code size estimate counts a block scope's entries by their size.
This commit is contained in:
1 parent
2d19ae8e3c
commit
029482d0d7
10 files changed
+363
-100
No files matched your search
@@ -429,7 +429,7 @@ pub enum FunctionKind {
|
||||
Setter,
|
||||
/// An arrow function; one with an expression body has a body of one `return` statement.
|
||||
Arrow,
|
||||
/// A method in a class body.
|
||||
/// A method in a class body or an object literal.
|
||||
Method,
|
||||
/// The constructor of a class without `extends`.
|
||||
ClassConstructor,
|
||||
|
||||
@@ -207,6 +207,9 @@ pub(crate) enum Op {
|
||||
ToStr,
|
||||
/// Pushes the template object of `templates[i]`, the same object for each evaluation.
|
||||
TemplateObject(u32),
|
||||
/// Starts (`true`) or ends (`false`) a class's heritage and computed keys in code that is not
|
||||
/// strict mode code: the code between runs as strict mode code (ECMA-262 2015 section 10.2.1).
|
||||
StrictClass(bool),
|
||||
/// `[superclass]` → `constructor prototype`: makes a class's prototype object and its
|
||||
/// constructor from `functions[ctor]`, the superclass on the stack when `heritage` is true
|
||||
/// (ECMA-262 2015 section 14.5.14).
|
||||
@@ -443,7 +446,7 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
|
||||
Op::XmlScopeRef => e(1, 2),
|
||||
Op::ForEachValue(n) => e(n + 2, n + 3),
|
||||
Op::SetDefaultNamespace => e(1, 0),
|
||||
Op::PushBlock(_) | Op::CopyEnv | Op::BodyEnv => e(0, 0),
|
||||
Op::PushBlock(_) | Op::CopyEnv | Op::BodyEnv | Op::StrictClass(_) => e(0, 0),
|
||||
Op::InitVar(_) | Op::AnnexB(_) => e(1, 0),
|
||||
Op::LoadParam(_) | Op::TemplateObject(_) => e(0, 1),
|
||||
Op::ArraySpread | Op::NewSpread => e(2, 1),
|
||||
|
||||
@@ -98,11 +98,11 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// The value of `this` in the running code (ResolveThisBinding, section 8.3.2). In a derived
|
||||
/// class constructor and the arrow functions inside it, reading it before `super(…)` returns
|
||||
/// is a `ReferenceError`.
|
||||
/// class constructor and the arrow functions and direct eval code inside it, reading it before
|
||||
/// `super(…)` returns is a `ReferenceError`.
|
||||
pub(crate) fn this_value(&mut self) -> JsResult<Value> {
|
||||
let frame = self.frame()?;
|
||||
if (frame.code.arrow || frame.code.derived)
|
||||
if frame.this_in_env
|
||||
&& let Some(e) = self.hidden_env(frame.env, ARROW_THIS)
|
||||
{
|
||||
if self.uninitialized(e, ARROW_THIS) {
|
||||
@@ -399,10 +399,11 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// [[Set]] of `k` on `proto` with `receiver` as `this` (OrdinarySet, section 9.1.9). A write
|
||||
/// that cannot be made throws a `TypeError` in strict mode code and does nothing otherwise
|
||||
/// (PutValue, section 6.2.3.2).
|
||||
/// that cannot be made throws a `TypeError` in strict mode code and in code from a source with
|
||||
/// [`crate::bytecode::Source::strict_writes`], and does nothing otherwise (PutValue, section
|
||||
/// 6.2.3.2).
|
||||
fn super_put(&mut self, proto: ObjId, k: Key, v: Value, receiver: &Value) -> JsResult<()> {
|
||||
let throw = self.frame()?.code.strict;
|
||||
let throw = self.strict_writes();
|
||||
let why = match self.find_property(proto, &k)? {
|
||||
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), receiver, &[v]).map(drop),
|
||||
Some(Prop::Accessor { set: None, .. }) => Some("it has only a getter"),
|
||||
|
||||
+75
-28
@@ -244,14 +244,15 @@ impl<'a> FnCompiler<'a> {
|
||||
/// in source order, and compiles the functions.
|
||||
/// With [`crate::Options::es2015`], only the function declarations at the top of the body are
|
||||
/// hoisted; one in a block is instantiated when the block is entered, and outside strict mode
|
||||
/// code its name is also a variable (Annex B.3.3) unless that clashes with a parameter or with
|
||||
/// a `let` or a `const` of the body or of a block or loop around the declaration.
|
||||
/// code its name is also a variable (Annex B.3.3) unless that clashes with a parameter, with
|
||||
/// a `let` or a `const` of the body or of a block or loop around the declaration, or with a
|
||||
/// function declared in a block around the one that holds the declaration.
|
||||
fn hoist(&mut self, body: &[StmtId], params: &[Key]) -> CResult<Hoisted> {
|
||||
let mut out = Hoisted::default();
|
||||
let mut seen = HashSet::new();
|
||||
// The `let` and `const` names of each statement list and loop the walk enters, with the
|
||||
// index of the one around it; the body's are first.
|
||||
let mut scopes: Vec<(Option<usize>, HashSet<Key>)> = vec![(None, self.lexical_names(body))];
|
||||
// The `let` and `const` names and the block's function names of each statement list and
|
||||
// loop the walk enters, with the index of the one around it; the body's are first.
|
||||
let mut scopes: Vec<(Option<usize>, HashSet<Key>, HashSet<Key>)> = vec![(None, self.lexical_names(body), HashSet::new())];
|
||||
let mut work: Vec<(StmtId, bool, usize)> = body.iter().rev().map(|&s| (s, false, 0)).collect();
|
||||
let mut add_var = |out: &mut Hoisted, k: Key| {
|
||||
if seen.insert(k.clone()) {
|
||||
@@ -262,8 +263,8 @@ impl<'a> FnCompiler<'a> {
|
||||
while let Some((id, nested, scope)) = work.pop() {
|
||||
let Some(stmt) = self.ast.stmt(id) else { return internal("statement out of range") };
|
||||
let inner = self.es2015;
|
||||
let mut enter = |names: HashSet<Key>| {
|
||||
scopes.push((Some(scope), names));
|
||||
let mut enter = |names: HashSet<Key>, funcs: HashSet<Key>| {
|
||||
scopes.push((Some(scope), names, funcs));
|
||||
scopes.len() - 1
|
||||
};
|
||||
match stmt {
|
||||
@@ -285,7 +286,7 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
}
|
||||
Stmt::Block(list) => {
|
||||
let s = enter(self.lexical_names(list));
|
||||
let s = enter(self.lexical_names(list), self.block_function_names(list));
|
||||
work.extend(list.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
Stmt::If { consequent, alternate, .. } => {
|
||||
@@ -300,7 +301,7 @@ impl<'a> FnCompiler<'a> {
|
||||
decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name)));
|
||||
scope
|
||||
}
|
||||
Some(ForInit::Lexical(_, decls)) => enter(decls.iter().map(|d| key_of(&d.name.name)).collect()),
|
||||
Some(ForInit::Lexical(_, decls)) => enter(decls.iter().map(|d| key_of(&d.name.name)).collect(), HashSet::new()),
|
||||
_ => scope,
|
||||
};
|
||||
work.push((*body, nested || inner, s));
|
||||
@@ -311,28 +312,29 @@ impl<'a> FnCompiler<'a> {
|
||||
add_var(&mut out, key_of(&d.name.name));
|
||||
scope
|
||||
}
|
||||
ForInTarget::Lexical(_, name) => enter(HashSet::from([key_of(&name.name)])),
|
||||
ForInTarget::Lexical(_, name) => enter(HashSet::from([key_of(&name.name)]), HashSet::new()),
|
||||
ForInTarget::Expr(_) => scope,
|
||||
};
|
||||
work.push((*body, nested || inner, s));
|
||||
}
|
||||
Stmt::Switch { cases, .. } => {
|
||||
let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect();
|
||||
let s = enter(names);
|
||||
let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect();
|
||||
let s = enter(names, funcs);
|
||||
for case in cases.iter().rev() {
|
||||
work.extend(case.body.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
}
|
||||
Stmt::Try { block, handler, finalizer } => {
|
||||
if let Some(f) = finalizer {
|
||||
let s = enter(self.lexical_names(f));
|
||||
let s = enter(self.lexical_names(f), self.block_function_names(f));
|
||||
work.extend(f.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
if let Some(h) = handler {
|
||||
let s = enter(self.lexical_names(&h.body));
|
||||
let s = enter(self.lexical_names(&h.body), self.block_function_names(&h.body));
|
||||
work.extend(h.body.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
let s = enter(self.lexical_names(block));
|
||||
let s = enter(self.lexical_names(block), self.block_function_names(block));
|
||||
work.extend(block.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
Stmt::Expr(_)
|
||||
@@ -348,8 +350,11 @@ impl<'a> FnCompiler<'a> {
|
||||
for (k, scope, id) in annex {
|
||||
let mut cur = Some(scope);
|
||||
let mut clash = params.contains(&k) || *k == *key_of("arguments");
|
||||
while let Some((outer, names)) = cur.and_then(|i| scopes.get(i)).filter(|_| !clash) {
|
||||
clash = names.contains(&k);
|
||||
// The functions of the declaration's own block do not count: it is the one replaced.
|
||||
let mut own = true;
|
||||
while let Some((outer, names, funcs)) = cur.and_then(|i| scopes.get(i)).filter(|_| !clash) {
|
||||
clash = names.contains(&k) || (!own && funcs.contains(&k));
|
||||
own = false;
|
||||
cur = *outer;
|
||||
}
|
||||
if !clash {
|
||||
@@ -372,8 +377,31 @@ impl<'a> FnCompiler<'a> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The names of the function declarations a block's statement list declares, labeled ones
|
||||
/// included.
|
||||
fn block_function_names(&self, list: &[StmtId]) -> HashSet<Key> {
|
||||
list.iter()
|
||||
.filter_map(|&s| self.labeled_function(s))
|
||||
.filter_map(|(_, fid)| self.ast.function(fid).and_then(|f| f.name.as_ref()))
|
||||
.map(|n| key_of(&n.name))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The function declaration the statement `s` is, alone or inside labels, and its statement.
|
||||
fn labeled_function(&self, s: StmtId) -> Option<(StmtId, FunctionId)> {
|
||||
let mut cur = s;
|
||||
loop {
|
||||
match self.ast.stmt(cur)? {
|
||||
Stmt::FunctionDecl(fid) => return Some((cur, *fid)),
|
||||
Stmt::Labeled { body, .. } => cur = *body,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The scope a statement list declares with [`crate::Options::es2015`]: its `let`, `const`
|
||||
/// and class names, and (`functions`) its function declarations. `None` when it declares none.
|
||||
/// and class names, and (`functions`) its function declarations, labeled ones included.
|
||||
/// `None` when it declares none.
|
||||
fn list_scope(&mut self, list: &[StmtId], functions: bool) -> CResult<Option<u32>> {
|
||||
if !self.es2015 {
|
||||
return Ok(None);
|
||||
@@ -383,12 +411,13 @@ impl<'a> FnCompiler<'a> {
|
||||
match self.ast.stmt(s) {
|
||||
Some(Stmt::Lexical(kind, decls)) => scope.lets.extend(decls.iter().map(|d| (key_of(&d.name.name), *kind == LexKind::Const))),
|
||||
Some(Stmt::Class(class)) => scope.lets.extend(class.name.iter().map(|n| (key_of(&n.name), false))),
|
||||
Some(Stmt::FunctionDecl(fid)) if functions && !self.top_funcs.contains(&s) => {
|
||||
let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else {
|
||||
_ if functions => {
|
||||
let Some((s, fid)) = self.labeled_function(s).filter(|(s, _)| !self.top_funcs.contains(s)) else { continue };
|
||||
let Some(name) = self.ast.function(fid).and_then(|f| f.name.as_ref()) else {
|
||||
return internal("function declaration without a name");
|
||||
};
|
||||
let k = key_of(&name.name);
|
||||
let i = self.function(*fid)?;
|
||||
let i = self.function(fid)?;
|
||||
scope.funcs.push((k, i));
|
||||
self.block_funcs.insert(s);
|
||||
}
|
||||
@@ -1385,7 +1414,8 @@ impl<'a> FnCompiler<'a> {
|
||||
/// A class definition (ECMA-262 2015 section 14.5.14), leaving its constructor on the stack. A
|
||||
/// named class binds its name, uninitialized and constant, in a scope of its own around the
|
||||
/// heritage and the methods, and initializes it only after every method is defined (steps 21
|
||||
/// and 23), so a computed key that reads the name throws a `ReferenceError`.
|
||||
/// and 23), so a computed key that reads the name throws a `ReferenceError`. The heritage and
|
||||
/// the computed keys run as strict mode code (section 10.2.1).
|
||||
fn class(&mut self, class: &ClassDef) -> CResult<()> {
|
||||
self.at(class.span.start);
|
||||
let scope = class.name.as_ref().map(|n| self.push_scope(BlockScope { lets: vec![(key_of(&n.name), true)], funcs: Vec::new() }));
|
||||
@@ -1393,6 +1423,30 @@ impl<'a> FnCompiler<'a> {
|
||||
self.emit(Op::PushBlock(s));
|
||||
self.env_depth += 1;
|
||||
}
|
||||
// A class inside this one's heritage or keys is already in strict mode code.
|
||||
let sloppy = !self.strict;
|
||||
if sloppy {
|
||||
self.emit(Op::StrictClass(true));
|
||||
self.strict = true;
|
||||
}
|
||||
let r = self.class_body(class);
|
||||
if sloppy {
|
||||
self.strict = false;
|
||||
self.emit(Op::StrictClass(false));
|
||||
}
|
||||
r?;
|
||||
if let (Some(name), Some(_)) = (&class.name, scope) {
|
||||
self.emit(Op::Dup);
|
||||
let n = self.var_name(&name.name);
|
||||
self.emit(Op::InitVar(n));
|
||||
self.emit(Op::PopEnv);
|
||||
self.env_depth -= 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A class's heritage, constructor and methods, leaving its constructor on the stack.
|
||||
fn class_body(&mut self, class: &ClassDef) -> CResult<()> {
|
||||
if let Some(h) = class.heritage {
|
||||
self.expr(h)?;
|
||||
}
|
||||
@@ -1417,13 +1471,6 @@ impl<'a> FnCompiler<'a> {
|
||||
self.emit(Op::ClassMethod { func, kind, is_static: element.is_static });
|
||||
}
|
||||
self.emit(Op::Pop);
|
||||
if let (Some(name), Some(_)) = (&class.name, scope) {
|
||||
self.emit(Op::Dup);
|
||||
let n = self.var_name(&name.name);
|
||||
self.emit(Op::InitVar(n));
|
||||
self.emit(Op::PopEnv);
|
||||
self.env_depth -= 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -100,6 +100,12 @@ fn redeclarations_and_bad_declarations_are_syntax_errors() {
|
||||
// Outside strict mode code `let` is still a name where no declaration can start.
|
||||
truth("var let = 3; let === 3");
|
||||
truth("{ function f() { return 1; } function f() { return 2; } } f() === 2");
|
||||
// A labeled function in a block declares its name in the block.
|
||||
syntax("{ let f; label: function f() {} }");
|
||||
truth("function g() { var f; L: function f() {} return typeof f; } g() === 'function'");
|
||||
// A method's parameter names are unique outside strict mode code too.
|
||||
syntax("({ m(x, x) {} })");
|
||||
truth("function f(x, x) { return x; } f(1, 2) === 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -121,7 +127,11 @@ fn functions_declared_in_blocks_are_scoped_to_the_block() {
|
||||
truth("var before = typeof f; { function f() { return 1; } } before === 'undefined' && f() === 1");
|
||||
truth("{ let x = 2; function g() { return x; } } g() === 2");
|
||||
truth("function h() { if (true) { function inner() { return 'i'; } } return inner(); } h() === 'i'");
|
||||
// Only a `let` or `const` around the declaration, or a parameter, keeps the name from being a variable.
|
||||
// Only a `let` or `const` around the declaration, a function declared in a block around it, or
|
||||
// a parameter keeps the name from being a variable.
|
||||
truth("var f; { function f() { return 1; } { function f() { return 2; } } } f() === 1");
|
||||
// A labeled function in a block is made when the block is entered.
|
||||
truth("{ var result = typeof lf; L: function lf() {} } result === 'function'");
|
||||
truth("function f() { { let g; } { function g() {} } return typeof g; } f() === 'function'");
|
||||
truth("function f() { let g = 1; { function g() {} } return g; } f() === 1");
|
||||
truth("function f() { { let g = 1; { function g() {} } } return typeof g; } f() === 'undefined'");
|
||||
@@ -169,6 +179,23 @@ fn a_global_function_that_cannot_be_declared_declares_nothing() {
|
||||
assert_eq!(realm.run("let retained = 2; retained"), Ok(JsValue::Number(2.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_variable_that_cannot_be_declared_declares_nothing() {
|
||||
// A global object that is not extensible takes no new variable (ECMA-262 2015 sections 15.1.8
|
||||
// and 18.2.1.2, CanDeclareGlobalVar), and nothing else the code declares is declared.
|
||||
let mut realm = es();
|
||||
assert_eq!(realm.run("var kept = 1; Object.preventExtensions(this); 0"), Ok(JsValue::Number(0.0)));
|
||||
for decl in ["let pending = 1; var missing;", "eval('var missing;')", "(0, eval)('var missing;')"] {
|
||||
let failed = realm.run(decl);
|
||||
assert!(
|
||||
matches!(&failed, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("TypeError")),
|
||||
"{decl}: {failed:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(realm.run("typeof pending === 'undefined' && !this.hasOwnProperty('missing')"), Ok(JsValue::Bool(true)));
|
||||
assert_eq!(realm.run("var kept = 2; kept"), Ok(JsValue::Number(2.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_function_is_judged_by_the_global_objects_own_property() {
|
||||
// ECMA-262 2015 sections 8.1.1.4.16 and 8.1.1.4.18 read the global object's own property, so
|
||||
@@ -451,6 +478,91 @@ fn new_scopes_survive_collections_while_they_are_made() {
|
||||
assert!(completed > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calls_and_strict_eval_survive_collections_while_their_scopes_are_made() {
|
||||
// Heaps just big enough make the collector run while a call's or a strict eval's scopes are
|
||||
// made; the receiver, the arguments and eval's own environment stay reachable.
|
||||
let src = "var total = 0; \
|
||||
for (var i = 0; i < 300; i++) { \
|
||||
total += (function () { 'use strict'; let x = i; return this.marker + x - i; }).call({ marker: 1 }); \
|
||||
total += (function (a) { let y = a; return arguments.length + y.v; })({ v: 1 }, {}, {}); \
|
||||
total += eval(\"'use strict'; var x = 7; let y = 1; function g() { return x; } x + y + g() + i - i\"); \
|
||||
total += (0, eval)(\"'use strict'; var x = 2; let y = 1; function g() { return x; } x + y + g() + i - i\"); } total";
|
||||
let mut completed = 0;
|
||||
for kib in 16..400 {
|
||||
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes: kib << 10, ..Limits::default() });
|
||||
match realm.run(src) {
|
||||
Ok(v) => {
|
||||
assert_eq!(v, JsValue::Number(7500.0), "{kib} KiB");
|
||||
completed += 1;
|
||||
}
|
||||
Err(e) => assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{kib} KiB: {e:?}"),
|
||||
}
|
||||
}
|
||||
assert!(completed > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_eval_keeps_its_environment_through_a_collection_while_its_scope_is_made() {
|
||||
// The scope of 500 names is the biggest piece eval code makes, so the collector runs while it
|
||||
// is made at many heap sizes; eval's own environment, with `x` in it, stays.
|
||||
let lets: Vec<String> = (0..500).map(|k| format!("l{k}")).collect();
|
||||
let src = format!(
|
||||
"var total = 0; var src = \"'use strict'; var x = 7; let {}; function g() {{ return x; }} x + g() + i - i\"; \
|
||||
for (var i = 0; i < 10; i++) {{ total += eval(src) + (0, eval)(src); }} total",
|
||||
lets.join(", ")
|
||||
);
|
||||
let mut completed = 0;
|
||||
for kib in (64..1024).step_by(2) {
|
||||
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes: kib << 10, ..Limits::default() });
|
||||
match realm.run(&src) {
|
||||
Ok(v) => {
|
||||
assert_eq!(v, JsValue::Number(280.0), "{kib} KiB");
|
||||
completed += 1;
|
||||
}
|
||||
Err(e) => assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{kib} KiB: {e:?}"),
|
||||
}
|
||||
}
|
||||
assert!(completed > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spread_checks_the_heap_before_its_elements_are_added() {
|
||||
// The list of 25,000 elements read fits in the room left over, and the array's 25,000 new
|
||||
// properties do not, so the spread ends with the heap limit before the estimate passes it.
|
||||
let setup = "var big = { length: 25000 }; 0";
|
||||
let mut measure = Realm::with_options(es_options(), Limits::default());
|
||||
assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0)));
|
||||
measure.interp().collect_garbage();
|
||||
let heap_bytes = measure.interp().heap.bytes + (2 << 20);
|
||||
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() });
|
||||
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)));
|
||||
assert_eq!(realm.run("[...{ length: 10 }].length"), Ok(JsValue::Number(10.0)));
|
||||
let e = realm.run("[...big].length").unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}");
|
||||
assert!(realm.interp().heap.bytes <= heap_bytes, "{} > {heap_bytes}", realm.interp().heap.bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_objects_go_when_their_code_does() {
|
||||
// Two sites in one function share its code; both strings objects go once the function does.
|
||||
let mut realm = es();
|
||||
let src = "function tag(s) { return s; } (function () { tag`a`; tag`b`; })(); (function () { tag`c`; })(); 0";
|
||||
assert_eq!(realm.run(src), Ok(JsValue::Number(0.0)));
|
||||
realm.interp().collect_garbage();
|
||||
realm.interp().collect_garbage();
|
||||
assert_eq!(realm.interp().template_objects.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directive_after_a_template_over_lines_must_start_its_line() {
|
||||
let options = Options { preprocessor_lines: true, ..es_options() };
|
||||
let p = crate::parse("var s = `${1}\nx` //@include \"missing.jsx\"\nvar t = `a\nb` //@include \"other.jsx\"", &options).unwrap();
|
||||
assert!(p.directives.is_empty(), "{:?}", p.directives);
|
||||
assert!(crate::parse("var s = `${1}\nx` #include x", &options).is_err());
|
||||
assert_eq!(crate::parse("var s = `${1}\nx`\n//@include \"a.jsx\"", &options).unwrap().directives.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_arrows_and_templates_stay_within_the_depth_limit() {
|
||||
let deep = format!("{}0", "x => ".repeat(400));
|
||||
@@ -558,6 +670,11 @@ fn object_literal_methods_are_enumerable_and_reach_super() {
|
||||
// A `super` write that cannot be made does nothing outside strict mode code.
|
||||
truth("var o = { m() { super.x = 1; Object.freeze(o); super.y = 2; return 1; } }; o.m() === 1 && o.x === 1 && !('y' in o)");
|
||||
throws("var o = { m() { 'use strict'; Object.freeze(o); super.y = 2; } }; o.m();", "TypeError");
|
||||
// So does a realm's strict writes setting.
|
||||
let mut realm = es();
|
||||
realm.set_strict_writes(true);
|
||||
let failed = realm.run("var o = { m() { Object.freeze(o); super.y = 2; } }; o.m();");
|
||||
assert!(matches!(&failed, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("TypeError")), "{failed:?}");
|
||||
syntax("var o = { m() { super(); } };");
|
||||
syntax("var o = { f: function () { return super.x; } };");
|
||||
let r = Realm::new().run("var o = { m() {} };");
|
||||
@@ -575,6 +692,13 @@ fn this_before_super_is_a_reference_error() {
|
||||
truth("class A {} class B extends A { constructor() { var f = () => this; super(); this.f = f; } } var b = new B(); b.f() === b");
|
||||
// A handler in the constructor does not catch what its return throws.
|
||||
throws("class A {} class B extends A { constructor() { try { return; } catch (e) {} } } new B();", "ReferenceError");
|
||||
// Direct eval reads the constructor's `this` binding when it runs.
|
||||
throws("class A {} class B extends A { constructor() { eval('this'); super(); } } new B();", "ReferenceError");
|
||||
truth("class A {} class B extends A { constructor() { eval('1'); super(); this.ok = eval('this') === this; } } new B().ok");
|
||||
truth("class A {} class B extends A { constructor() { var f = eval('() => this'); super(); this.f = f; } } var b = new B(); b.f() === b");
|
||||
truth(
|
||||
"var seen; class A {} class B extends A { constructor() { var o = { g() { return eval('this'); } }; seen = o.g() === o; super(); } } new B(); seen",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -589,6 +713,17 @@ fn extends_null_and_bad_heritage() {
|
||||
throws("class A { m() {} } class B extends A.prototype.m {}", "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn class_heritage_and_computed_keys_run_as_strict_mode_code() {
|
||||
throws("var o = {}; Object.defineProperty(o, 'x', { value: 1 }); class C { [(o.x = 2)]() {} }", "TypeError");
|
||||
throws("class C extends (undeclared = Object) {}", "ReferenceError");
|
||||
throws("var C = class { static [(undeclared = 'k')]() {} };", "ReferenceError");
|
||||
// The code around the class stays sloppy, after the class and in a handler of what it throws.
|
||||
truth("class C extends Object {} after = 1; after === 1");
|
||||
truth("try { class C extends (function () { throw 1; })() {} } catch (e) { caught = e; } caught === 1");
|
||||
truth("try { class C { [(function () { throw 2; })()]() {} } } catch (e) { caught = e; } caught === 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_extends_other_built_ins_but_new_on_it_throws() {
|
||||
let e4x = || Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default());
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::bytecode::{Code, Handler, Op};
|
||||
use crate::bytecode::{BlockScope, Code, Handler, Op};
|
||||
use crate::value::{Str, Value};
|
||||
|
||||
/// A property name: its UTF-16 code units.
|
||||
@@ -617,10 +617,15 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
|
||||
+ code.params.len()
|
||||
+ code.vars.len()
|
||||
+ 2 * code.fun_decls.len()
|
||||
+ code.scopes.iter().map(|s| 2 + s.lets.len() + 2 * s.funcs.len()).sum::<usize>()
|
||||
+ code.templates.iter().map(|t| 2 + t.cooked.len() + t.raw.len()).sum::<usize>();
|
||||
let tables = code.finally_tables.iter().map(|t| 24 + 4 * t.len()).sum::<usize>();
|
||||
let scopes = code
|
||||
.scopes
|
||||
.iter()
|
||||
.map(|s| size_of::<BlockScope>() + size_of::<(Key, bool)>() * s.lets.len() + size_of::<(Key, u32)>() * s.funcs.len())
|
||||
.sum::<usize>();
|
||||
strings.bytes += CODE_BYTES
|
||||
+ scopes
|
||||
+ size_of::<Op>() * code.ops.len()
|
||||
+ 4 * code.positions.len()
|
||||
+ 8 * code.numbers.len()
|
||||
|
||||
+116
-53
@@ -179,6 +179,12 @@ pub(crate) struct Frame {
|
||||
/// `with` and catch environments entered and not yet left.
|
||||
env_depth: u32,
|
||||
pub(crate) this: Value,
|
||||
/// `this` is the binding of the environment chain that an arrow function or a derived class
|
||||
/// constructor reads, not [`Self::this`]: in such code and in the direct eval code it runs.
|
||||
pub(crate) this_in_env: bool,
|
||||
/// The frame is running a class's heritage or computed keys, which are strict mode code
|
||||
/// (ECMA-262 2015 section 10.2.1) inside code that is not.
|
||||
strict_class: bool,
|
||||
callee: Option<ObjId>,
|
||||
/// The object `new` made, returned unless the function returns an object.
|
||||
construct: Option<ObjId>,
|
||||
@@ -803,8 +809,13 @@ impl Interp {
|
||||
roots.envs.push(self.global_env);
|
||||
roots.envs.push(self.global_lex);
|
||||
roots.envs.extend(self.temp_envs.iter().copied());
|
||||
// A template object stays while its code can still run.
|
||||
self.template_objects.retain(|_, (code, _)| Rc::strong_count(code) > 1);
|
||||
// A template object stays while its code can still run: while something other than the
|
||||
// entries for its code's sites holds the code.
|
||||
let mut sites: std::collections::HashMap<*const Code, usize> = std::collections::HashMap::new();
|
||||
for (code, _) in self.template_objects.values() {
|
||||
*sites.entry(Rc::as_ptr(code)).or_default() += 1;
|
||||
}
|
||||
self.template_objects.retain(|_, (code, _)| Rc::strong_count(code) > sites.get(&Rc::as_ptr(code)).copied().unwrap_or(0));
|
||||
roots.objects.extend(self.template_objects.values().map(|&(_, id)| id));
|
||||
self.heap.collect(&roots);
|
||||
// The collection counts the live total again, so bytes already released are not in it.
|
||||
@@ -909,6 +920,9 @@ impl Interp {
|
||||
frame.env_depth -= 1;
|
||||
}
|
||||
frame.pc = h.target as usize;
|
||||
// A handler of this frame is never inside a class's heritage or keys: they are
|
||||
// expressions, and a function in them runs in a frame of its own.
|
||||
frame.strict_class = false;
|
||||
if self.stack.len() < target_len {
|
||||
return internal("handler stack deeper than the stack");
|
||||
}
|
||||
@@ -989,13 +1003,13 @@ impl Interp {
|
||||
}
|
||||
|
||||
fn strict(&self) -> bool {
|
||||
self.frames.last().is_some_and(|f| f.code.strict)
|
||||
self.frames.last().is_some_and(|f| f.code.strict || f.strict_class)
|
||||
}
|
||||
|
||||
/// Does a property write the running code makes throw when it cannot be made? It does in
|
||||
/// strict mode code and in code from a source with [`crate::bytecode::Source::strict_writes`].
|
||||
fn strict_writes(&self) -> bool {
|
||||
self.frames.last().is_some_and(|f| f.code.strict || f.code.source.strict_writes)
|
||||
pub(crate) fn strict_writes(&self) -> bool {
|
||||
self.frames.last().is_some_and(|f| f.code.strict || f.strict_class || f.code.source.strict_writes)
|
||||
}
|
||||
|
||||
/// [`crate::bytecode::Source::strict_writes`] for source compiled now: the running code's,
|
||||
@@ -1122,6 +1136,10 @@ impl Interp {
|
||||
self.push(v)
|
||||
}
|
||||
Op::ClassStart { ctor, heritage } => self.op_class_start(ctor, heritage),
|
||||
Op::StrictClass(on) => {
|
||||
self.frame_mut()?.strict_class = on;
|
||||
Ok(())
|
||||
}
|
||||
Op::ClassMethod { func, kind, is_static } => self.op_class_method(func, kind, is_static),
|
||||
Op::InitMethod { func, kind, name } => self.op_init_method(func, kind, name),
|
||||
Op::SuperRef => self.op_super_ref(),
|
||||
@@ -2111,9 +2129,10 @@ impl Interp {
|
||||
fn op_closure(&mut self, i: u32) -> JsResult<()> {
|
||||
let frame = self.frame()?;
|
||||
let (env, this) = (frame.env, frame.this.clone());
|
||||
// In an arrow function or a derived class constructor, `this` is already a binding of the
|
||||
// environment chain, which the new function reads as it is when it runs.
|
||||
let this_bound = frame.code.arrow || frame.code.derived;
|
||||
// In an arrow function or a derived class constructor, and in the direct eval code they
|
||||
// run, `this` is already a binding of the environment chain, which the new function reads
|
||||
// as it is when it runs.
|
||||
let this_bound = frame.this_in_env;
|
||||
let Some(code) = frame.code.functions.get(i as usize).cloned() else { return internal("function out of range") };
|
||||
// An arrow function keeps the `this` of the code it is made in (ECMA-262 2015 section
|
||||
// 14.2.16), in an environment of its own that only the call reads.
|
||||
@@ -2397,6 +2416,14 @@ impl Interp {
|
||||
return Err(self.type_error(&format!("{what} cannot be spread")));
|
||||
}
|
||||
};
|
||||
// Each element becomes a property of the array, counted against the heap limit before it
|
||||
// is made, with the elements reachable while the collector runs.
|
||||
let mark = self.temp_roots.len();
|
||||
let count = items.len();
|
||||
self.temp_roots.extend(items);
|
||||
let reserved = self.reserve_heap(count.saturating_mul(PROP_BYTES.saturating_add(string_bytes(10))));
|
||||
let items = self.temp_roots.split_off(mark.min(self.temp_roots.len()));
|
||||
reserved?;
|
||||
let o = self.object_mut(a)?;
|
||||
let Class::Array { length, .. } = &mut o.class else { return internal("spread into something that is not an array") };
|
||||
let start = *length;
|
||||
@@ -2762,46 +2789,54 @@ impl Interp {
|
||||
.saturating_add(arguments)
|
||||
.saturating_add(rest)
|
||||
.saturating_add(crate::class_ops::hidden_bytes(&code));
|
||||
if self.heap.bytes.saturating_add(need) > self.limits.heap_bytes {
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.push(Value::Object(callee));
|
||||
// The operands are off the stack and in no frame yet, so they stay reachable while the
|
||||
// function's environments are made.
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.push(Value::Object(callee));
|
||||
self.temp_roots.push(this.clone());
|
||||
self.temp_roots.extend(construct.map(Value::Object));
|
||||
self.temp_roots.extend(new_target.map(Value::Object));
|
||||
self.temp_roots.extend(args.iter().cloned());
|
||||
let enter = || -> JsResult<()> {
|
||||
self.reserve_heap(need)?;
|
||||
let this = if code.arrow {
|
||||
if code.uses_this { self.arrow_this(env) } else { Value::Undefined }
|
||||
} else if code.strict {
|
||||
this
|
||||
} else {
|
||||
match this {
|
||||
Value::Undefined | Value::Null => Value::Object(self.global),
|
||||
Value::Object(_) => this,
|
||||
prim => Value::Object(self.to_object(&prim)?),
|
||||
}
|
||||
};
|
||||
self.temp_roots.push(this.clone());
|
||||
self.temp_roots.extend(construct.map(Value::Object));
|
||||
self.temp_roots.extend(args.iter().cloned());
|
||||
let reserved = self.reserve_heap(need);
|
||||
self.temp_roots.truncate(mark);
|
||||
reserved?;
|
||||
}
|
||||
let this = if code.arrow {
|
||||
if code.uses_this { self.arrow_this(env) } else { Value::Undefined }
|
||||
} else if code.strict {
|
||||
this
|
||||
} else {
|
||||
match this {
|
||||
Value::Undefined | Value::Null => Value::Object(self.global),
|
||||
Value::Object(_) => this,
|
||||
prim => Value::Object(self.to_object(&prim)?),
|
||||
}
|
||||
let (fenv, var_env) = self.instantiate_function(&code, env, &args, callee)?;
|
||||
let this_env = self.function_bindings(&code, var_env, callee, new_target)?;
|
||||
let base = self.stack.len();
|
||||
let this_in_env = code.arrow || code.derived;
|
||||
self.frames.push(Frame {
|
||||
code,
|
||||
pc: 0,
|
||||
base,
|
||||
env: fenv,
|
||||
var_env,
|
||||
env_depth: 0,
|
||||
this,
|
||||
this_in_env,
|
||||
strict_class: false,
|
||||
callee: Some(callee),
|
||||
construct,
|
||||
new_target,
|
||||
this_env,
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
});
|
||||
Ok(())
|
||||
};
|
||||
let (fenv, var_env) = self.instantiate_function(&code, env, &args, callee)?;
|
||||
let this_env = self.function_bindings(&code, var_env, callee, new_target)?;
|
||||
let base = self.stack.len();
|
||||
self.frames.push(Frame {
|
||||
code,
|
||||
pc: 0,
|
||||
base,
|
||||
env: fenv,
|
||||
var_env,
|
||||
env_depth: 0,
|
||||
this,
|
||||
callee: Some(callee),
|
||||
construct,
|
||||
new_target,
|
||||
this_env,
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
});
|
||||
Ok(())
|
||||
let r = enter();
|
||||
self.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
/// Declaration binding instantiation for function code (section 10.5). Each parameter and
|
||||
@@ -3095,7 +3130,7 @@ impl Interp {
|
||||
let code = self.compile_source(&units, strict, CodeKind::Eval).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) = (frame.env, frame.var_env, frame.this.clone());
|
||||
let (caller_env, caller_var_env, this, this_in_env) = (frame.env, frame.var_env, frame.this.clone(), frame.this_in_env);
|
||||
let (env, var_env) = if code.strict {
|
||||
let e = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(caller_env) });
|
||||
(e, e)
|
||||
@@ -3104,7 +3139,10 @@ impl Interp {
|
||||
};
|
||||
self.stack.truncate(start);
|
||||
let env = self.instantiate_global(&code, env, var_env, true)?;
|
||||
self.push_code_frame(code, env, var_env, this, false)
|
||||
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;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Indirect eval and scripts: runs `code` in the global environment and returns its
|
||||
@@ -3154,7 +3192,8 @@ impl Interp {
|
||||
/// declared, or a built-in such as `undefined`) or a `var` or function of this script that
|
||||
/// another script declared with `let` or `const` is a `SyntaxError`, and nothing is declared.
|
||||
/// With [`Options::es2015`], a function of this script that cannot replace a property of the
|
||||
/// global object is a `TypeError`, also before anything is declared.
|
||||
/// global object, or a `var` that cannot be added to it, is a `TypeError`, also before
|
||||
/// anything is declared.
|
||||
fn declare_global_lexical(&mut self, code: &Code, lex: EnvId) -> JsResult<()> {
|
||||
let lets: &[(Key, bool)] = code.top_scope.and_then(|i| code.scopes.get(i as usize)).map_or(&[], |s| &s.lets);
|
||||
let in_lex = |interp: &Self, name: &[u16]| matches!(interp.heap.env(lex), Some(Env::Decl { bindings, .. }) if bindings.contains(name));
|
||||
@@ -3174,7 +3213,7 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
if self.options.es2015 {
|
||||
self.check_global_functions(code)?;
|
||||
self.check_global_declarations(code)?;
|
||||
}
|
||||
for (name, constant) in lets {
|
||||
let b = Binding::lexical(*constant);
|
||||
@@ -3186,9 +3225,19 @@ impl Interp {
|
||||
/// The test `declare` makes for a function in an object environment, on the global object's
|
||||
/// own property, for every function `code` declares before any is (ECMA-262 2015 sections
|
||||
/// 15.1.8, step 8, and 18.2.1.2, step 8, CanDeclareGlobalFunction): a function that cannot
|
||||
/// replace its property is a `TypeError`.
|
||||
fn check_global_functions(&mut self, code: &Code) -> JsResult<()> {
|
||||
/// replace its property is a `TypeError`. So is a variable without an own property of a global
|
||||
/// object that is not extensible (the same sections, step 10, CanDeclareGlobalVar).
|
||||
fn check_global_declarations(&mut self, code: &Code) -> JsResult<()> {
|
||||
let global = self.global;
|
||||
if !self.object(global)?.extensible {
|
||||
for name in &code.vars {
|
||||
self.use_fuel()?;
|
||||
if self.get_own_property(global, name)?.is_none() {
|
||||
let ident = String::from_utf16_lossy(name);
|
||||
return Err(self.type_error(&format!("cannot declare variable {ident}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name, _) in &code.fun_decls {
|
||||
let replaceable = match self.get_own_property(global, name)? {
|
||||
None => self.object(global)?.extensible,
|
||||
@@ -3217,6 +3266,8 @@ impl Interp {
|
||||
var_env,
|
||||
env_depth: 0,
|
||||
this,
|
||||
this_in_env: false,
|
||||
strict_class: false,
|
||||
callee: None,
|
||||
construct: None,
|
||||
new_target: None,
|
||||
@@ -3234,11 +3285,22 @@ impl Interp {
|
||||
/// environment of its `let` and `const` names. A script's `let` and `const` names go in the
|
||||
/// global scope ([`Self::declare_global_lexical`]).
|
||||
fn instantiate_global(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<EnvId> {
|
||||
// A strict eval's own environment is in no frame yet, so the environments stay reachable
|
||||
// until the code's frame holds them.
|
||||
let mark = self.temp_envs.len();
|
||||
self.temp_envs.extend([env, var_env]);
|
||||
let r = self.instantiate_global_in(code, env, var_env, is_eval);
|
||||
self.temp_envs.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
/// [`Self::instantiate_global`], its environments already reachable from the roots.
|
||||
fn instantiate_global_in(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<EnvId> {
|
||||
let configurable = if is_eval { CONFIGURABLE } else { 0 };
|
||||
if is_eval && !code.strict && self.options.es2015 {
|
||||
self.check_eval_vars(code, env, var_env)?;
|
||||
if var_env == self.global_env {
|
||||
self.check_global_functions(code)?;
|
||||
self.check_global_declarations(code)?;
|
||||
}
|
||||
}
|
||||
let lex = match code.top_scope {
|
||||
@@ -3249,6 +3311,7 @@ impl Interp {
|
||||
Some(i) => self.block_env(code, i, env)?,
|
||||
None => env,
|
||||
};
|
||||
self.temp_envs.push(lex);
|
||||
// Functions close over the code's own environment with ES2015's scoping, and over its
|
||||
// variable environment otherwise (ECMA-262 5.1 section 13). Global code's functions close
|
||||
// over the global scope in either language, which sees the global object's names too.
|
||||
|
||||
@@ -194,6 +194,8 @@ impl<'s> Lexer<'s> {
|
||||
self.line_start = start.saturating_sub(usize::try_from(token.column.saturating_sub(1)).unwrap_or(0));
|
||||
self.blank_line = false;
|
||||
let mut piece = self.template(start, token.line, token.column)?;
|
||||
// A template continued over a line ends on a new line, but not at its start.
|
||||
self.blank_line = false;
|
||||
piece.newline_before = token.newline_before;
|
||||
Ok(piece)
|
||||
}
|
||||
|
||||
@@ -53,9 +53,10 @@
|
||||
//! 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). Spread reads arrays, strings (by code point) and objects
|
||||
//! with a `length`, by index; other values are a `TypeError`. Destructuring, `for … of`, classes,
|
||||
//! generators and modules stay syntax errors.
|
||||
//! `new` (sections 12.2.5 and 12.3.6.1), classes with `extends`, `super` and `new.target`
|
||||
//! (sections 14.5, 12.3.5 and 12.3.8), and methods in object literals (section 14.3). Spread reads
|
||||
//! arrays, strings (by code point) and objects with a `length`, by index; other values are a
|
||||
//! `TypeError`. Destructuring, `for … of`, generators and modules stay syntax errors.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod ast;
|
||||
|
||||
+11
-5
@@ -978,6 +978,11 @@ impl<'s> Parser<'s> {
|
||||
self.ctx.labels.remove(&label.name);
|
||||
}
|
||||
let mut body = body?;
|
||||
// A labeled function declares its name in the statement list it stands in.
|
||||
if let Some(Stmt::FunctionDecl(fid)) = self.ast.stmt(body) {
|
||||
let fid = *fid;
|
||||
self.declare_function(fid)?;
|
||||
}
|
||||
for (label, label_start) in labels.into_iter().rev() {
|
||||
let span = Span::new(label_start.start, self.ast.stmt_span(body).end);
|
||||
body = self.ast.push_stmt(Stmt::Labeled { label, body }, span);
|
||||
@@ -1155,13 +1160,14 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
|
||||
/// The rules for a function's name and parameters. Strict mode code (Annex C): neither `eval`,
|
||||
/// `arguments` nor a strict-mode reserved word, and no parameter name twice. An arrow function
|
||||
/// or a function with a default or rest parameter has no parameter name twice either (ECMA-262
|
||||
/// 2015 sections 14.1.2 and 14.2.1), and its body cannot start with `"use strict"`
|
||||
/// (`body_strict`; ECMA-262 2016 section 14.1.2).
|
||||
/// `arguments` nor a strict-mode reserved word, and no parameter name twice. An arrow function,
|
||||
/// a method or a function with a default or rest parameter has no parameter name twice either
|
||||
/// (ECMA-262 2015 sections 14.1.2, 14.2.1 and 14.3.1), and a function with a default or rest
|
||||
/// parameter cannot start its body with `"use strict"` (`body_strict`; ECMA-262 2016 section
|
||||
/// 14.1.2).
|
||||
fn check_params(&self, function: &Function, body_strict: bool) -> Result<()> {
|
||||
let params = || function.params.iter().chain(&function.rest);
|
||||
let simple = function.simple_params() && function.kind != FunctionKind::Arrow;
|
||||
let simple = function.simple_params() && !matches!(function.kind, FunctionKind::Arrow | FunctionKind::Method);
|
||||
if body_strict && !function.simple_params() {
|
||||
let at = function.body.first().map_or(function.span.start, |&s| self.ast.stmt_span(s).start);
|
||||
return Err(self.error_at_offset(at, "\"use strict\" is not allowed in a function with default or rest parameters"));
|
||||
|
||||
Reference in new issue
Block a user