From 5c165ef7ff94adef46bfaaba21ef6954e8d0e469 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:33:26 -0800 Subject: [PATCH] Scripts: spread, global lets and rest parameters follow the limits and scopes - Spread keeps its list of elements counted against the heap limit until the elements are the array's properties, so a list and an array that only fit one at a time end the run with the heap limit. - A script stopped at the fuel or heap limit while its functions and variables are declared removes its `let` and `const` names from the global scope, so running it again in the same realm does not throw a redeclaration error. A script that throws once it runs keeps them. - A function whose only non-simple parameter is a rest parameter keeps its parameters and body in one environment (ECMA-262 2015 section 9.2.12), so `var r` in the body or in direct eval is the parameter. Its `arguments` object still does not follow the parameters. --- crates/js/src/bytecode.rs | 8 +++++- crates/js/src/compiler.rs | 5 +++- crates/js/src/es2015_tests.rs | 51 +++++++++++++++++++++++++++++++++++ crates/js/src/interp.rs | 38 +++++++++++++++++++------- 4 files changed, 90 insertions(+), 12 deletions(-) diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index b8d56bc2cd..3fa6087906 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -354,7 +354,7 @@ pub(crate) struct Code { pub(crate) arrow: bool, /// The code reads `this` or calls `eval`, itself or in an arrow function inside it. pub(crate) uses_this: bool, - /// The function has default or rest parameters: its parameters start uninitialized, its + /// The function has parameters with default values: its parameters start uninitialized, its /// code initializes them and then enters its body with [`Op::BodyEnv`]. pub(crate) param_init: bool, /// The code is a class constructor's: calling it without `new` is a `TypeError`. @@ -379,6 +379,12 @@ impl Code { let offset = self.positions.get(pc).copied().unwrap_or(self.span.0); self.source.lines.line_column(offset) } + + /// The parameters are plain names, without default values or a rest parameter, so outside + /// strict mode code the `arguments` object follows them (ECMA-262 2015 section 9.2.12). + pub(crate) fn simple_params(&self) -> bool { + !self.param_init && self.rest.is_none() + } } /// What an instruction does to the stack on each way out of it. diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 23f0f0e2fd..9fe6bc7096 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -2006,7 +2006,10 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, let all_params: Vec = params.iter().chain(&rest).cloned().collect(); let hoisted = c.hoist(&f.body, &all_params)?; let top_scope = c.list_scope(&f.body, false)?; - let param_init = !f.simple_params(); + // Only default values are expressions (ContainsExpression, ECMA-262 2015 section 14.1.5): a + // rest parameter alone leaves the parameters and the body in one environment (section 9.2.12, + // step 27). + let param_init = f.defaults.iter().any(Option::is_some); if param_init { // Each parameter is initialized in order, from its argument or, when that is // `undefined`, its default value; then the body's environment is entered. diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 17c89d86d8..c3e95a0525 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -160,6 +160,26 @@ fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() { assert!(restricted.is_err(), "{restricted:?}"); } +#[test] +fn a_script_stopped_at_a_limit_before_it_runs_leaves_no_global_lexical_bindings() { + // The 200 functions take a unit of fuel each after the `let` is declared, so each of these + // fuel limits stops the script before it runs. A second run with the default limits then + // declares `pending` again; a thrown error once the script runs keeps the binding. + let functions: String = (0..200).map(|k| format!("function f{k}() {{}} ")).collect(); + let src = format!("let pending = 1; {functions} pending"); + for fuel in (2..150).step_by(7) { + let mut realm = Realm::with_options(es_options(), Limits { fuel, ..Limits::default() }); + let e = realm.run(&src).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "fuel {fuel}: {e:?}"); + realm.set_limits(Limits::default()); + assert_eq!(realm.run(&src), Ok(JsValue::Number(1.0)), "fuel {fuel}"); + } + let mut realm = es(); + assert!(realm.run("let thrown = 1; throw 0;").is_err()); + let again = realm.run("let thrown = 2;"); + assert!(matches!(&again, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{again:?}"); +} + #[test] fn functions_from_earlier_runs_see_later_global_lexical_bindings() { let mut realm = Realm::new(); @@ -370,6 +390,14 @@ fn rest_parameters_collect_the_remaining_arguments() { truth("function f(a, ...r) { return Array.isArray(r) && r.length === 2 && r[0] === 2 && r[1] === 3; } f(1, 2, 3)"); truth("function f(...r) { return r.length; } f() === 0"); truth("function f(...r) { r.push(1); return r.length; } f(0) === 2"); + // Without default values the parameters and the body share one environment, so a `var` of a + // parameter's name, in the body or in direct eval, is the parameter. + truth("function f(...r) { return eval('var r; r[0]'); } f(3) === 3"); + truth("function f(a, ...r) { eval('var a = 5; var r = 6'); return a + r; } f(1, 2) === 11"); + truth("function f(...r) { var r; return r[0]; } f(4) === 4"); + // The arguments object still does not follow the parameters, and its callee throws. + truth("function f(a, ...r) { a = 9; return arguments[0]; } f(1) === 1"); + throws("function f(...r) { return arguments.callee; } f();", "TypeError"); syntax("function f(...r, a) {}"); syntax("function f(...r = []) {}"); syntax("function f(a, a = 1) {}"); @@ -546,6 +574,29 @@ fn spread_checks_the_heap_before_its_elements_are_added() { assert!(realm.interp().heap.bytes <= heap_bytes, "{} > {heap_bytes}", realm.interp().heap.bytes); } +#[test] +fn spread_counts_its_list_of_elements_while_the_array_grows() { + // The list of elements read (64 bytes each) fits in the room left over, and so do the array's + // new properties (116 bytes each), but the two together do not. The list is still held while + // the properties are added, so the spread ends with the heap limit. + let cases = [ + ("var big = { length: 25000 }; 0", "[...big].length", 3584 << 10), + ("var big = 'x'; for (var i = 0; i < 15; i++) big += big; big[0]; 0", "[...big].length", 4608 << 10), + ]; + for (setup, spread, room) in cases { + let mut measure = Realm::with_options(es_options(), Limits::default()); + assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0)), "{setup}"); + measure.interp().collect_garbage(); + let heap_bytes = measure.interp().heap.bytes + room; + let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() }); + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)), "{setup}"); + assert_eq!(realm.run("[...'abc', ...{ length: 10 }].length"), Ok(JsValue::Number(13.0)), "{setup}"); + let e = realm.run(spread).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{setup}: {e:?}"); + assert!(realm.interp().heap.bytes <= heap_bytes, "{setup}: {} > {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. diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24a1acaf90..c1c64b1d19 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2310,7 +2310,7 @@ impl Interp { self.push(v) } - /// Enters the body of a function with default or rest parameters: a variable environment + /// Enters the body of a function with default values for its parameters: a variable environment /// inside the parameters' one, whose variables start with the value of a parameter of the /// same name (ECMA-262 2015 section 9.2.12, step 28), and the body's function declarations /// and `let` and `const` names. @@ -2368,11 +2368,13 @@ impl Interp { fn op_array_spread(&mut self) -> JsResult<()> { let v = self.peek(0)?; let Value::Object(a) = self.peek(1)? else { return internal("spread into something that is not an array") }; + // The list of elements is counted against the heap limit as it grows, and stays counted + // until its elements have become the array's properties. + let mut held = HeldBytes::new(self); let items: Vec = match &v { Value::String(s) => { let units = crate::string_builtins::flat_charged(self, s)?; let mut out = Vec::new(); - let mut held = HeldBytes::new(self); let mut i = 0; while let Some(&u) = units.get(i) { self.use_fuel()?; @@ -2397,9 +2399,7 @@ impl Interp { return Err(self.throw(ErrorType::Range, "array literal too long")); }; // The elements read so far stay reachable while a getter runs. - // The list is counted against the heap limit as it grows. let mark = self.temp_roots.len(); - let mut held = HeldBytes::new(self); let mut read = || -> JsResult<()> { for i in 0..n { self.use_fuel()?; @@ -2410,7 +2410,6 @@ impl Interp { Ok(()) }; let r = read(); - drop(held); let out = self.temp_roots.split_off(mark.min(self.temp_roots.len())); r?; out @@ -2438,6 +2437,7 @@ impl Interp { for (i, item) in (start..end).zip(items) { self.define(a, index_key(i), Prop::Data { value: item, flags: OPEN })?; } + drop(held); self.pop().map(drop) } @@ -2846,7 +2846,7 @@ impl Interp { /// Declaration binding instantiation for function code (section 10.5). Each parameter and /// declaration takes a unit of fuel. /// Gives the environment the body runs in and its variable environment. A function with - /// default or rest parameters gets its parameters uninitialized, and its code enters the + /// default values for its parameters gets its parameters uninitialized, and its code enters the /// body's environments with [`Op::BodyEnv`] once they are initialized (ECMA-262 2015 section /// 9.2.12). fn instantiate_function(&mut self, code: &Rc, outer: EnvId, args: &[Value], callee: ObjId) -> JsResult<(EnvId, EnvId)> { @@ -2975,7 +2975,7 @@ impl Interp { /// strict mode code in a function with plain parameters (ECMA-262 2015 section 9.2.12). fn create_arguments(&mut self, code: &Code, env: EnvId, args: &[Value], callee: ObjId) -> JsResult { let mut names = vec![None; args.len()]; - if !code.strict && !code.param_init { + if !code.strict && code.simple_params() { let mut mapped = std::collections::HashSet::new(); for (i, p) in code.params.iter().enumerate().take(args.len()).rev() { if mapped.insert(p.clone()) @@ -2991,7 +2991,7 @@ impl Interp { self.define(a, index_key(u32::try_from(i).unwrap_or(u32::MAX)), Prop::Data { value: v.clone(), flags: OPEN })?; } self.define(a, key("length"), Prop::Data { value: Value::Number(args.len() as f64), flags: HIDDEN })?; - if code.strict || code.param_init { + if code.strict || !code.simple_params() { let thrower = Some(self.intrinsics.throw_type_error); for name in ["callee", "caller"] { self.define(a, key(name), Prop::Accessor { get: thrower, set: thrower, flags: 0 })?; @@ -3309,8 +3309,9 @@ impl Interp { self.check_global_declarations(code)?; } } + let global_lets = !is_eval && env == self.global_lex; let lex = match code.top_scope { - _ if !is_eval && env == self.global_lex => { + _ if global_lets => { self.declare_global_lexical(code, env)?; env } @@ -3318,6 +3319,23 @@ impl Interp { None => env, }; self.temp_envs.push(lex); + let r = self.declare_global_functions_and_vars(code, lex, var_env, configurable); + if r.is_err() && global_lets { + // A script that stops before it runs, at a limit, leaves none of its `let` and `const` + // names behind, so running it again in the same realm does not redeclare them. + let lets = code.top_scope.and_then(|i| code.scopes.get(i as usize)).map_or(&[][..], |s| &s.lets); + if let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(lex) { + for (name, _) in lets { + bindings.remove(name); + } + } + } + r.map(|()| lex) + } + + /// Declares the functions and variables of global or eval code for + /// [`Self::instantiate_global_in`], each taking a unit of fuel. + fn declare_global_functions_and_vars(&mut self, code: &Rc, lex: EnvId, var_env: EnvId, configurable: u8) -> JsResult<()> { // 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. @@ -3333,7 +3351,7 @@ impl Interp { self.use_fuel()?; self.declare(var_env, v, None, configurable)?; } - Ok(lex) + Ok(()) } /// A `var` or function that eval code outside strict mode code declares must not take the name