Merge branch feat/js-es2015-block-arrow-template into feat/js-es2015-for-of-destructuring

# Conflicts:
#	crates/js/src/interp.rs
This commit is contained in:
dotCooCoo committed 2026-11-22 06:17:48 -08:00
commit 3d75d9edcc
2 files changed
+109 -16

No files matched your search

+65
View File
@@ -172,6 +172,37 @@ 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_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
// a fixed property the global object inherits does not stop the declaration.
let mut realm = es();
let setup = "Object.defineProperty(Object.prototype, 'fixed', { value: 1 }); \
Object.defineProperty(Object.prototype, 'getter', { get: function () { return 1; } }); 0";
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)));
assert_eq!(realm.run("function fixed() { return 2; } function getter() { return 3; } fixed() + getter()"), Ok(JsValue::Number(5.0)));
let own = "var d = Object.getOwnPropertyDescriptor(this, 'fixed'); d.writable && d.enumerable && !d.configurable && ({}).fixed === 1";
assert_eq!(realm.run(own), Ok(JsValue::Bool(true)));
// A global object that is not extensible takes no new function, inherited name or not, and
// a function declared next to one it cannot take is not declared either.
let mut realm = es();
assert_eq!(realm.run(&format!("{setup}; var kept = 1; Object.preventExtensions(this); 0")), Ok(JsValue::Number(0.0)));
for decl in [
"function fixed() {}",
"function fresh() {}",
"(0, eval)('function fixed() {}')",
"(0, eval)('function fresh() {}')",
"(0, eval)('function kept() {} function fresh() {}')",
] {
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("this.hasOwnProperty('fixed') || this.hasOwnProperty('fresh') || kept !== 1"), Ok(JsValue::Bool(false)));
}
#[test]
fn eval_code_keeps_its_let_and_const_to_itself() {
truth("eval('let e = 1; e') === 1 && typeof e === 'undefined'");
@@ -376,6 +407,40 @@ fn spread_and_templates_stay_within_the_limits() {
throws("function f() {} var a = []; a.length = 100000; f(...a);", "RangeError");
}
#[test]
fn spreading_a_rope_counts_its_flattened_length_first() {
// `mk` returns a rope whose left half is a flat string of about half the heap, held by
// nothing else. Its flattened copy is the other half, so the two don't fit together. Making
// the left half takes about 16,400 fuel, and the elements read before the heap fills would
// take more than the rest, so only the check before the copy ends the run with the heap limit.
let build = "var s = 'x'; for (var i = 0; i < 18; i++) s = s + s; function f(c) { return s + c; } \
function mk() { var a = f('a'); a[0]; return a + 'b'; }";
let limits = Limits { heap_bytes: 4 * 262_146, fuel: 20_000, ..Limits::default() };
for spread in ["[...mk()]", "Math.max(...mk())"] {
let e = Realm::with_options(es_options(), limits.clone()).run(&format!("{build} {spread}; 0")).unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{spread}: {e:?}");
}
let made = Realm::with_options(es_options(), limits).run(&format!("{build} mk(); 0"));
assert_eq!(made, Ok(JsValue::Number(0.0)), "the rope is made within the fuel");
}
#[test]
fn a_rest_parameter_checks_the_heap_before_its_array_is_made() {
// The 20,000 arguments fit in the room left over, and the rest array of them does not, so
// the call ends with the heap limit before the heap estimate passes it.
let setup = "function f(...r) { return r.length; } var big = Array(20000); 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 + (512 << 10);
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("f.apply(null, Array(10))"), Ok(JsValue::Number(10.0)));
let e = realm.run("f.apply(null, big)").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 new_scopes_survive_collections_while_they_are_made() {
// Heaps just big enough make the collector run while function bodies and blocks set up their
+44 -16
View File
@@ -2728,7 +2728,15 @@ impl Interp {
let params = code.params.iter().chain(&code.pattern_names).fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len())));
let arguments =
if code.uses_arguments { OBJECT_BYTES.saturating_add(args.len().saturating_add(4).saturating_mul(binding_bytes(10))) } else { 0 };
let need = declaration_bytes(&code).saturating_add(ENV_BYTES).saturating_add(params).saturating_add(arguments);
// The array a rest parameter gets: its binding and one property for each extra argument.
let rest = match &code.rest {
Some(name) => {
let extra = args.len().saturating_sub(code.params.len());
OBJECT_BYTES.saturating_add(binding_bytes(name.len())).saturating_add(extra.saturating_mul(binding_bytes(10)))
}
None => 0,
};
let need = declaration_bytes(&code).saturating_add(ENV_BYTES).saturating_add(params).saturating_add(arguments).saturating_add(rest);
if self.heap.bytes.saturating_add(need) > self.limits.heap_bytes {
let mark = self.temp_roots.len();
self.temp_roots.push(Value::Object(callee));
@@ -3143,20 +3151,7 @@ impl Interp {
}
}
if self.options.es2015 {
// The test `declare` makes for a function in an object environment (section 15.1.8,
// step 8, CanDeclareGlobalFunction).
for (name, _) in &code.fun_decls {
let replaceable = match self.find_property(global, name)? {
None => true,
Some(p) if p.configurable() => true,
Some(Prop::Data { flags, .. }) => flags & (WRITABLE | ENUMERABLE) == WRITABLE | ENUMERABLE,
Some(_) => false,
};
if !replaceable {
let ident = String::from_utf16_lossy(name);
return Err(self.type_error(&format!("cannot declare function {ident}")));
}
}
self.check_global_functions(code)?;
}
for (name, constant) in lets {
let b = Binding::lexical(*constant);
@@ -3165,6 +3160,27 @@ impl Interp {
Ok(())
}
/// 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<()> {
let global = self.global;
for (name, _) in &code.fun_decls {
let replaceable = match self.get_own_property(global, name)? {
None => self.object(global)?.extensible,
Some(p) if p.configurable() => true,
Some(Prop::Data { flags, .. }) => flags & (WRITABLE | ENUMERABLE) == WRITABLE | ENUMERABLE,
Some(_) => false,
};
if !replaceable {
let ident = String::from_utf16_lossy(name);
return Err(self.type_error(&format!("cannot declare function {ident}")));
}
}
Ok(())
}
fn push_code_frame(&mut self, code: Rc<Code>, env: EnvId, var_env: EnvId, this: Value, boundary: bool) -> JsResult<()> {
if self.frames.len() >= self.limits.frames {
return Err(Abrupt::Limit(LimitKind::Frames));
@@ -3196,6 +3212,9 @@ impl Interp {
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)?;
}
}
let lex = match code.top_scope {
_ if !is_eval && env == self.global_lex => {
@@ -3271,7 +3290,16 @@ impl Interp {
None if declared => Ok(()),
None => self.define(object, name.clone(), Prop::Data { value: Value::Undefined, flags }),
Some(v) => {
let existing = self.find_property(object, name)?;
// ECMA-262 2015 section 8.1.1.4.18 reads the object's own property, and
// section 10.5 of the 5.1 edition the property it inherits as well.
let existing = if self.options.es2015 { self.get_own_property(object, name)? } else { self.find_property(object, name)? };
// A new own property needs an extensible object (ECMA-262 2015 section
// 8.1.1.4.16; section 8.12.9 of the 5.1 edition, step 3).
let defines = existing.as_ref().is_none_or(Prop::configurable);
if defines && !self.object(object)?.extensible && self.get_own_property(object, name)?.is_none() {
let ident = String::from_utf16_lossy(name);
return Err(self.type_error(&format!("cannot declare function {ident}")));
}
match existing {
None => self.define(object, name.clone(), Prop::Data { value: v, flags }),
Some(p) if p.configurable() => self.define(object, name.clone(), Prop::Data { value: v, flags }),