Skip to content

Truly independent web browser

LibJS: Only bind this in function environments that need it

Andreas Kling068edab0d9e3
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
index 428cf491fef..1aa2a0062e2 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
@@ -930,7 +930,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
if template.allocator == 0
|| template_bytes > u64::from(template.cell_size)
|| u64::from(template.binding_values_offset) + 8 > template_bytes
- || u64::from(template.this_value_offset) + 8 > template_bytes
+ || (template.binds_this && u64::from(template.this_value_offset) + 8 > template_bytes)
{
return Err(CompileFailure::CodeGeneration);
}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs
index 3b8429820b1..319aa5e9999 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs
@@ -213,7 +213,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.emit_pop_free_list_of(scratch, cell, heap, from_runtime);
// The environment, from the template's words and the call.
- for index in 0..layout.function_environment_words {
+ for index in 0..layout.declarative_environment_words {
self.masm.load64(
scratch,
&at(template, layout.call_environment_template_words + 8 * index),
@@ -238,6 +238,21 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
&at(function, self.runtime.offsets.ecmascript_function_environment),
);
self.masm.store32(&at(cell, layout.function_environment_outer), scratch);
+ // The rest of a function environment, which only some callees need.
+ let no_function_fields = self.masm.new_label();
+ self.masm.load64(
+ scratch,
+ &at(template, layout.call_environment_template_has_function_fields),
+ );
+ self.masm
+ .branch_test64(Condition::Zero, scratch, u64::MAX, no_function_fields);
+ for index in layout.declarative_environment_words..layout.function_environment_words {
+ self.masm.load64(
+ scratch,
+ &at(template, layout.call_environment_template_words + 8 * index),
+ );
+ self.masm.store64(&at(cell, 8 * index), scratch);
+ }
self.masm.shr64_imm(scratch, function, COMPRESSED_POINTER_SHIFT);
self.masm
.store32(&at(cell, layout.function_environment_function_object), scratch);
@@ -249,6 +264,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm
.store64(&at(cell, layout.function_environment_this_value), scratch);
self.masm.bind(no_this);
+ self.masm.bind(no_function_fields);
self.masm.store64(&environment_local, cell);
// Count the cell like the heap does.
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
index 0b25f40b29a..dc17d6b9695 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
@@ -4046,7 +4046,8 @@ mod direct_calls {
#[test]
fn callees_with_a_call_environment_template_get_it_inline() {
// A fake template (size class, cell size, binding values offset,
- // whether calls bind `this`, then six words) and heap, and the
+ // whether calls bind `this`, whether the environment has the
+ // fields of a function environment, then six words) and heap, and the
// environment's fields: binding values at 16, outer environment at
// 24, function object at 32 and this value at 40.
struct Case {
@@ -4056,6 +4057,7 @@ mod direct_calls {
template: bool,
free_cell: bool,
inline: bool,
+ function_fields: bool,
}
let run = |case: Case| {
let flags = CAN_INLINE_CALL | NEEDS_ENVIRONMENT | USES_THIS | if case.strict { STRICT } else { 0 };
@@ -4076,7 +4078,13 @@ mod direct_calls {
// The free lists of size classes 0 to 3: the template's size
// class 6 masks to 2.
let free_lists = vec![0, 0, free_list.as_mut_ptr() as u64, 0];
- let mut template = vec![6, 64, if case.inline { 48 } else { 0 }, u64::from(case.binds_this)];
+ let mut template = vec![
+ 6,
+ 64,
+ if case.inline { 48 } else { 0 },
+ u64::from(case.binds_this),
+ u64::from(case.function_fields),
+ ];
template.extend([0x1000, 0x1001, 0, 0, 0, 0]);
let template = fake_heap::cell(&template);
// NB: Bits in the other half of the word, which the stub ignores.
@@ -4098,8 +4106,10 @@ mod direct_calls {
layout.call_environment_template_cell_size = 8;
layout.call_environment_template_binding_values_offset = 16;
layout.call_environment_template_binds_this = 24;
- layout.call_environment_template_words = 32;
+ layout.call_environment_template_has_function_fields = 32;
+ layout.call_environment_template_words = 40;
layout.function_environment_words = 6;
+ layout.declarative_environment_words = 4;
layout.function_environment_binding_values = 16;
layout.function_environment_outer = 24;
layout.function_environment_function_object = 32;
@@ -4146,6 +4156,7 @@ mod direct_calls {
template: true,
free_cell: true,
inline,
+ function_fields: true,
};
for (case, this) in [
(inline(true, true, value::int32(3), true), value::int32(3)),
@@ -4171,6 +4182,21 @@ mod direct_calls {
assert_eq!(heap, [164, 10_000, 1064]);
}
+ // Without the fields of a function environment, `this` only goes in
+ // the frame, and the cell's words after the declarative ones stay.
+ let (_, frame, from_runtime, _, block) = run(Case {
+ function_fields: false,
+ ..inline(true, true, value::int32(3), true)
+ });
+ assert!(!from_runtime);
+ let cell = block.cell();
+ let address = cell.as_ptr() as u64;
+ assert_eq!((frame[1], frame[12]), (address, address), "environments");
+ assert_eq!(frame[120 / 8], value::int32(3), "this");
+ assert_eq!(&cell[..2], &[0x1000, 0x1001]);
+ assert_eq!(cell[3] as u32, FUNCTION_WORDS[0] as u32, "compressed outer environment");
+ assert_eq!(&cell[4..6], &[0x5a5a, 0x5a5a]);
+
// Sloppy callees binding primitives, callees without a template and
// empty free lists get their environment from the runtime.
for case in [
diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
index 9c9ac406b9d..f7dd8c29043 100644
--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs
+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
@@ -547,7 +547,7 @@ pub struct LexicalEnvironmentTemplateSnapshot {
pub shape: Option<CellId>,
}
-/// A `FunctionEnvironment` like the ones calls of a function get (see
+/// A `FunctionEnvironment` or `DeclarativeEnvironment` like the ones calls of a function get (see
/// `ECMAScriptFunctionObject::inline_call_environment()`), with its final
/// shape and room for its binding values in the cell, as JIT code allocates
/// it: from the local free list at `allocator` (like
@@ -1228,6 +1228,7 @@ pub struct DynamicCallLayout {
pub call_environment_template_cell_size: u32,
pub call_environment_template_binding_values_offset: u32,
pub call_environment_template_binds_this: u32,
+ pub call_environment_template_has_function_fields: u32,
pub call_environment_template_words: u32,
/// The address of a table of the addresses of the local free lists of
/// the function environment size classes, which the stub pops the cell
@@ -1237,6 +1238,8 @@ pub struct DynamicCallLayout {
pub function_environment_size_class_mask: u32,
/// The number of words of a `FunctionEnvironment`.
pub function_environment_words: u32,
+ /// The number of words of a `DeclarativeEnvironment`, which the first words of a `FunctionEnvironment` are.
+ pub declarative_environment_words: u32,
/// `FunctionEnvironment` fields: the pointer to its binding values, its
/// outer environment, its function object and its this value.
pub function_environment_binding_values: u32,
diff --git a/Libraries/LibJS/Rust/src/jit/allocation.rs b/Libraries/LibJS/Rust/src/jit/allocation.rs
index 8e883c2accb..d160a6e511f 100644
--- a/Libraries/LibJS/Rust/src/jit/allocation.rs
+++ b/Libraries/LibJS/Rust/src/jit/allocation.rs
@@ -201,14 +201,23 @@ fn rope_template(vm: &Vm) -> Vec<u64> {
words
}
-/// The size class of function environments with room for `binding_count` binding values in their cells, as
-/// `FunctionEnvironmentFreeLists` numbers them: 0 for none, and the inline binding size class plus one otherwise.
-fn function_environment_size_class(binding_count: usize) -> Option<usize> {
- match inline_binding_size_class(binding_count) {
- Some(size_class) => Some(size_class + 1),
- None if binding_count == 0 => Some(0),
- None => None,
- }
+/// The size class of the environments of calls with room for `binding_count` binding values in their cells, as
+/// `FunctionEnvironmentFreeLists` numbers them: 0 for none, and the inline binding size class plus one otherwise, past
+/// DECLARATIVE_CALL_ENVIRONMENT_SIZE_CLASSES for declarative environments.
+fn function_environment_size_class(has_function_fields: bool, binding_count: usize) -> Option<usize> {
+ let size_class = match inline_binding_size_class(binding_count) {
+ Some(size_class) => size_class + 1,
+ None if binding_count == 0 => 0,
+ None => return None,
+ };
+ Some(
+ size_class
+ + if has_function_fields {
+ 0
+ } else {
+ DECLARATIVE_CALL_ENVIRONMENT_SIZE_CLASSES
+ },
+ )
}
/// The local free list function environments of a size class (see `function_environment_size_class()`) come from,
@@ -218,6 +227,18 @@ fn function_environment_size_class_allocator(
size_class: usize,
) -> Option<(NonNull<*mut core::ffi::c_void>, u32)> {
let heap = vm.heap();
+ if size_class >= DECLARATIVE_CALL_ENVIRONMENT_SIZE_CLASSES {
+ let size_class = size_class - DECLARATIVE_CALL_ENVIRONMENT_SIZE_CLASSES;
+ if size_class == 0 {
+ return Some((
+ heap.local_free_list_of(DeclarativeEnvironment::CLASS)?,
+ size(size_of::<DeclarativeEnvironment>()),
+ ));
+ }
+ let size_class =
+ heap.size_classes(DeclarativeEnvironment::CLASS, &DECLARATIVE_ENVIRONMENT_CELL_SIZES)[size_class - 1];
+ return Some((size_class.local_free_list()?, size_class.cell_size()));
+ }
if size_class == 0 {
return Some((
heap.local_free_list_of(FunctionEnvironment::CLASS)?,
@@ -230,13 +251,21 @@ fn function_environment_size_class_allocator(
/// The local free list function environments with room for `binding_count` binding values in their cells come from,
/// and the size of their cells, if they have room for that many and the heap gives the address of the list.
-fn function_environment_allocator(vm: &Vm, binding_count: usize) -> Option<(NonNull<*mut core::ffi::c_void>, u32)> {
- function_environment_size_class_allocator(vm, function_environment_size_class(binding_count)?)
+fn function_environment_allocator(
+ vm: &Vm,
+ has_function_fields: bool,
+ binding_count: usize,
+) -> Option<(NonNull<*mut core::ffi::c_void>, u32)> {
+ function_environment_size_class_allocator(vm, function_environment_size_class(has_function_fields, binding_count)?)
}
/// The number of entries of `FunctionEnvironmentFreeLists`, a power of two above the number of size classes.
-pub const FUNCTION_ENVIRONMENT_FREE_LIST_COUNT: usize = 16;
-const _: () = assert!(FUNCTION_ENVIRONMENT_CELL_SIZES.len() < FUNCTION_ENVIRONMENT_FREE_LIST_COUNT);
+pub const FUNCTION_ENVIRONMENT_FREE_LIST_COUNT: usize = 32;
+
+/// Where the size classes of declarative environments start in `FunctionEnvironmentFreeLists`.
+const DECLARATIVE_CALL_ENVIRONMENT_SIZE_CLASSES: usize = FUNCTION_ENVIRONMENT_FREE_LIST_COUNT / 2;
+const _: () = assert!(FUNCTION_ENVIRONMENT_CELL_SIZES.len() < DECLARATIVE_CALL_ENVIRONMENT_SIZE_CLASSES);
+const _: () = assert!(DECLARATIVE_ENVIRONMENT_CELL_SIZES.len() < DECLARATIVE_CALL_ENVIRONMENT_SIZE_CLASSES);
/// A list that is always empty, for the size classes whose free lists JIT code does not pop. It is never written: JIT
/// code only pops lists that are not empty.
@@ -258,7 +287,11 @@ impl Default for FunctionEnvironmentFreeLists {
impl FunctionEnvironmentFreeLists {
/// The address of the table, after filling it in from the VM's heap.
pub fn address(&self, vm: &Vm) -> u64 {
- for size_class in 0..=FUNCTION_ENVIRONMENT_CELL_SIZES.len() {
+ let size_classes = (0..=FUNCTION_ENVIRONMENT_CELL_SIZES.len()).chain(
+ DECLARATIVE_CALL_ENVIRONMENT_SIZE_CLASSES
+ ..=DECLARATIVE_CALL_ENVIRONMENT_SIZE_CLASSES + DECLARATIVE_ENVIRONMENT_CELL_SIZES.len(),
+ );
+ for size_class in size_classes {
if let Some((allocator, _)) = function_environment_size_class_allocator(vm, size_class) {
self.0[size_class].set(allocator.as_ptr() as u64);
}
@@ -275,11 +308,12 @@ pub fn make_call_environment_template(vm: &Vm, function: Gc<EcmascriptFunctionOb
if !shared_data.call_environment_template.is_null() {
return;
}
- let Some(environment) = environment.downcast::<FunctionEnvironment>() else {
+ let Some(environment) = environment.downcast::<DeclarativeEnvironment>() else {
return;
};
+ let has_function_fields = environment.downcast::<FunctionEnvironment>().is_some();
let binding_count = shared_data.function_environment_bindings_count();
- let Some(size_class) = function_environment_size_class(binding_count) else {
+ let Some(size_class) = function_environment_size_class(has_function_fields, binding_count) else {
return;
};
let Some((_, cell_size)) = function_environment_size_class_allocator(vm, size_class) else {
@@ -293,31 +327,39 @@ pub fn make_call_environment_template(vm: &Vm, function: Gc<EcmascriptFunctionOb
{
return;
}
- let words = cell_words(environment, size_of::<FunctionEnvironment>());
+ let cell_bytes = if has_function_fields {
+ size_of::<FunctionEnvironment>()
+ } else {
+ size_of::<DeclarativeEnvironment>()
+ };
+ let words = cell_words(environment, cell_bytes);
let mut template = CallEnvironmentTemplate {
header: CellHeader::for_class(CallEnvironmentTemplate::CLASS),
size_class: size_class as u64,
cell_size: u64::from(cell_size),
binding_values_offset: if has_inline_binding_values {
- size_of::<FunctionEnvironment>() as u64
+ cell_bytes as u64
} else {
0
},
binds_this: u64::from(function.uses_this() && function.this_mode() != ThisMode::Lexical),
+ has_function_fields: u64::from(has_function_fields),
words: [0; FUNCTION_ENVIRONMENT_WORDS],
};
- template.words.copy_from_slice(&words);
+ template.words[..words.len()].copy_from_slice(&words);
for (offset, size) in [
(core::mem::offset_of!(DeclarativeEnvironment, binding_values), 8),
(
core::mem::offset_of!(Environment, outer),
size_of::<NullableMember<Environment>>(),
),
- (FUNCTION_ENVIRONMENT_FUNCTION_OBJECT_OFFSET, 4),
- (FUNCTION_ENVIRONMENT_THIS_VALUE_OFFSET, 8),
] {
clear_bytes(&mut template.words, offset, size);
}
+ if has_function_fields {
+ clear_bytes(&mut template.words, FUNCTION_ENVIRONMENT_FUNCTION_OBJECT_OFFSET, 4);
+ clear_bytes(&mut template.words, FUNCTION_ENVIRONMENT_THIS_VALUE_OFFSET, 8);
+ }
shared_data
.call_environment_template
.set(Some(vm.heap().allocate(|_| template)));
@@ -338,14 +380,18 @@ pub fn function_environment_template(
}
let shared_data = function.shared_data();
let binding_count = shared_data.function_environment_bindings_count();
- let (allocator, cell_size) = function_environment_allocator(vm, binding_count)?;
+ let has_function_fields = shared_data.function_environment_has_this_binding();
+ let (allocator, cell_size) = function_environment_allocator(vm, has_function_fields, binding_count)?;
let sample = function
.inline_call_environment(vm, None)?
- .downcast::<FunctionEnvironment>()?;
+ .downcast::<DeclarativeEnvironment>()?;
// NB: Calls that bind `this` store it in the environment, as resolve_and_bind_this() does.
- let binds_this = function.uses_this() && function.this_mode() != ThisMode::Lexical;
+ let binds_this = has_function_fields && function.uses_this() && function.this_mode() != ThisMode::Lexical;
if binds_this {
- sample.bind_this_value(vm, Value::UNDEFINED).must();
+ sample
+ .downcast::<FunctionEnvironment>()?
+ .bind_this_value(vm, Value::UNDEFINED)
+ .must();
}
if !sample.rare_data.is_null() || sample.binding_values_are_inline() != (binding_count != 0) {
return None;
@@ -363,7 +409,14 @@ pub fn function_environment_template(
Some(EnvironmentTemplateSnapshot {
allocator: allocator.as_ptr() as u64,
cell_size,
- words: cell_words(sample, size_of::<FunctionEnvironment>()),
+ words: cell_words(
+ sample,
+ if has_function_fields {
+ size_of::<FunctionEnvironment>()
+ } else {
+ size_of::<DeclarativeEnvironment>()
+ },
+ ),
inline_binding_values: binding_count != 0,
binding_values_offset: offset(core::mem::offset_of!(DeclarativeEnvironment, binding_values)),
binds_this,
diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
index 93fd24d3046..90e1ead7c64 100644
--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs
+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
@@ -610,8 +610,10 @@ fn dynamic_call_layout(vm: &Vm) -> DynamicCallLayout {
binding_values_offset
)),
call_environment_template_binds_this: offset(offset_of!(CallEnvironmentTemplate, binds_this)),
+ call_environment_template_has_function_fields: offset(offset_of!(CallEnvironmentTemplate, has_function_fields)),
call_environment_template_words: offset(offset_of!(CallEnvironmentTemplate, words)),
function_environment_words: offset(FUNCTION_ENVIRONMENT_WORDS),
+ declarative_environment_words: offset(size_of::<DeclarativeEnvironment>() / 8),
function_environment_binding_values: offset(offset_of!(DeclarativeEnvironment, binding_values)),
function_environment_outer: offset(offset_of!(Environment, outer)),
function_environment_function_object: offset(FUNCTION_ENVIRONMENT_FUNCTION_OBJECT_OFFSET),
diff --git a/Libraries/LibJS/Rust/src/layout/function_object.rs b/Libraries/LibJS/Rust/src/layout/function_object.rs
index 5d55fca7601..b56cf135429 100644
--- a/Libraries/LibJS/Rust/src/layout/function_object.rs
+++ b/Libraries/LibJS/Rust/src/layout/function_object.rs
@@ -183,7 +183,8 @@ pub struct SharedFunctionInstanceData {
/// The number of words of a FunctionEnvironment: a DeclarativeEnvironment and two more words of fields.
pub const FUNCTION_ENVIRONMENT_WORDS: usize = size_of::<DeclarativeEnvironment>() / 8 + 2;
-/// A function environment like the ones the calls of a function get, with its final shape and room for its binding
+/// The environment of a call of a function (a function environment if `has_function_fields` is not 0, and a declarative
+/// environment otherwise) like the ones the calls of a function get, with its final shape and room for its binding
/// values in its cell, for JIT code to allocate from the local free list of its `size_class` (cells of `cell_size`
/// bytes, see `jit::allocation::FunctionEnvironmentFreeLists`) and fill with `words`. The words have no binding values pointer, outer environment, function object or this
/// value, which differ between calls: the binding values start `binding_values_offset` bytes into the cell (0 if they
@@ -196,5 +197,6 @@ pub struct CallEnvironmentTemplate {
pub cell_size: u64,
pub binding_values_offset: u64,
pub binds_this: u64,
+ pub has_function_fields: u64,
pub words: [u64; FUNCTION_ENVIRONMENT_WORDS],
}
diff --git a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
index c7ed0bbd9f1..7906717f7d0 100644
--- a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
+++ b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
@@ -824,6 +824,24 @@ pub fn new_object_environment(
)
}
+/// The environment of a call of `function`, which needs one: a function environment if the function's code reads
+/// anything of one through its environment, and otherwise the same without the fields it would never read.
+pub fn new_call_environment(
+ vm: &Vm,
+ function: Gc<EcmascriptFunctionObject>,
+ new_target: Option<Gc<Object>>,
+) -> Gc<DeclarativeEnvironment> {
+ let shared_data = function.shared_data();
+ if shared_data.function_environment_has_this_binding() {
+ return new_function_environment(vm, function, new_target).upcast();
+ }
+ DeclarativeEnvironment::create_with_binding_capacity(
+ vm,
+ function.environment(),
+ shared_data.function_environment_bindings_count(),
+ )
+}
+
// 9.1.2.4 NewFunctionEnvironment ( F, newTarget ), https://tc39.es/ecma262/#sec-newfunctionenvironment
// 4.1.2.2 NewFunctionEnvironment ( F, newTarget ), https://tc39.es/proposal-explicit-resource-management/#sec-newfunctionenvironment
pub fn new_function_environment(
diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
index 0cf772526fb..fc4d1c4b7ba 100644
--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
@@ -29,7 +29,7 @@ use crate::layout::member::NullableMember;
use crate::layout::object::{IndexedStorageKind, Object};
use crate::layout::value::Value;
use crate::runtime::abstract_operations::{
- create_unmapped_arguments_object, get_prototype_from_constructor, new_function_environment,
+ create_unmapped_arguments_object, get_prototype_from_constructor, new_call_environment,
};
use crate::runtime::async_function_driver_wrapper::AsyncFunctionDriverWrapper;
use crate::runtime::async_generator::AsyncGenerator;
@@ -658,7 +658,8 @@ impl EcmascriptFunctionObject {
if self.function_environment_needed() {
// 7. Let localEnv be NewFunctionEnvironment(F, newTarget).
- let local_environment = new_function_environment(vm, self.as_ecmascript_function_gc(), new_target);
+ // NB: Or what the function's code needs of one.
+ let local_environment = new_call_environment(vm, self.as_ecmascript_function_gc(), new_target);
let shared_data = self.shared_data();
let function_environment_bindings_count = shared_data.function_environment_bindings_count();
local_environment.set_environment_shape_cache(
@@ -751,7 +752,7 @@ impl EcmascriptFunctionObject {
// 7. Assert: localEnv is a function Environment Record.
// 8. Assert: The next step never returns an abrupt completion because localEnv.[[ThisBindingStatus]] is not initialized.
// 9. Perform ! localEnv.BindThisValue(thisValue).
- if self.function_environment_needed() {
+ if self.shared_data().function_environment_has_this_binding() {
local_env
.and_then(|environment| environment.downcast::<FunctionEnvironment>())
.expect("the lexical environment of the call is a function environment")
@@ -770,7 +771,7 @@ impl EcmascriptFunctionObject {
if !self.function_environment_needed() {
return self.environment();
}
- let local_environment = new_function_environment(vm, self.as_ecmascript_function_gc(), new_target);
+ let local_environment = new_call_environment(vm, self.as_ecmascript_function_gc(), new_target);
let shared_data = self.shared_data();
let function_environment_bindings_count = shared_data.function_environment_bindings_count();
local_environment.set_environment_shape_cache(
diff --git a/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs b/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
index 14479061bbd..42a2845c9ba 100644
--- a/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
+++ b/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
@@ -918,6 +918,15 @@ impl SharedFunctionInstanceData {
u32::from(self.construct_reserve.get())
}
+ /// Whether the environment of a call has to answer for `this`, `new.target` or `super`, because something reads
+ /// them through the environment. Otherwise a declarative environment does for the function's bindings, just as no
+ /// environment at all does for a function without any.
+ pub fn function_environment_has_this_binding(&self) -> bool {
+ self.contains_direct_call_to_eval()
+ || self.is_module_wrapper()
+ || (!self.is_arrow_function() && self.this_value_needs_environment_resolution())
+ }
+
pub fn function_environment_needed(&self) -> bool {
self.metadata_bit(asm_call_metadata::FUNCTION_ENVIRONMENT_NEEDED)
}
diff --git a/Tests/LibJS/Runtime/functions/function-environment-this-binding.js b/Tests/LibJS/Runtime/functions/function-environment-this-binding.js
new file mode 100644
index 00000000000..c676ca15d30
--- /dev/null
+++ b/Tests/LibJS/Runtime/functions/function-environment-this-binding.js
@@ -0,0 +1,212 @@
+// Functions whose code never reads `this`, `new.target` or `super` through their environment get a lighter environment
+// for their captured bindings. Everything that does read them has to keep working.
+
+const ITERATIONS = 5000;
+
+function repeated(callback) {
+ let result;
+ for (let i = 0; i < ITERATIONS; ++i) result = callback(i);
+ return result;
+}
+
+test("closures that do not read this through their environment", () => {
+ function counter(start) {
+ let count = start;
+ return () => ++count;
+ }
+ const next = repeated(i => counter(i));
+ expect(next()).toBe(ITERATIONS);
+ expect(next()).toBe(ITERATIONS + 1);
+});
+
+test("this read directly next to captured bindings", () => {
+ function method(value) {
+ const captured = () => value;
+ return [this.name, captured()];
+ }
+ const object = { name: "object", method };
+ expect(repeated(i => object.method(i))).toEqual(["object", ITERATIONS - 1]);
+
+ function sloppy() {
+ const value = 1;
+ const captured = () => value;
+ captured();
+ return typeof this;
+ }
+ expect(repeated(() => sloppy.call(1))).toBe("object");
+ expect(repeated(() => sloppy())).toBe("object");
+});
+
+test("this read through arrow functions", () => {
+ function method(value) {
+ return () => () => [this.name, value];
+ }
+ const object = { name: "object", method };
+ expect(repeated(i => object.method(i)()())).toEqual(["object", ITERATIONS - 1]);
+ expect(object.method(1)()()).toEqual(["object", 1]);
+});
+
+test("arrow functions with captured bindings of their own", () => {
+ function method() {
+ return value => {
+ const captured = () => value;
+ return [this.name, captured()];
+ };
+ }
+ const object = { name: "object", method };
+ expect(repeated(i => object.method()(i))).toEqual(["object", ITERATIONS - 1]);
+
+ const lexical = value => {
+ const captured = () => value;
+ return captured();
+ };
+ expect(repeated(i => lexical(i))).toBe(ITERATIONS - 1);
+});
+
+test("new.target next to captured bindings", () => {
+ function Direct(value) {
+ const captured = () => value;
+ this.value = captured();
+ this.target = new.target;
+ }
+ expect(repeated(i => new Direct(i)).target).toBe(Direct);
+ expect(Direct.call({}, 1)).toBeUndefined();
+
+ function ThroughArrow(value) {
+ const captured = () => [new.target, value];
+ this.result = captured();
+ }
+ expect(repeated(i => new ThroughArrow(i)).result).toEqual([ThroughArrow, ITERATIONS - 1]);
+});
+
+test("super next to captured bindings", () => {
+ class Base {
+ constructor(value) {
+ this.base = value;
+ }
+ method() {
+ return "base";
+ }
+ }
+ class Derived extends Base {
+ constructor(value) {
+ const captured = () => value;
+ super(captured());
+ this.derived = captured();
+ }
+ method(value) {
+ const captured = () => value;
+ return [super.method(), captured()];
+ }
+ arrow(value) {
+ return (() => [super.method(), value])();
+ }
+ }
+ class ThroughArrow extends Base {
+ constructor(value) {
+ const call = () => super(value);
+ call();
+ this.after = value;
+ }
+ }
+ const object = repeated(i => new Derived(i));
+ expect(object.base).toBe(ITERATIONS - 1);
+ expect(object.derived).toBe(ITERATIONS - 1);
+ expect(repeated(i => object.method(i))).toEqual(["base", ITERATIONS - 1]);
+ expect(repeated(i => object.arrow(i))).toEqual(["base", ITERATIONS - 1]);
+ expect(repeated(i => new ThroughArrow(i)).base).toBe(ITERATIONS - 1);
+
+ class Uninitialized extends Base {
+ constructor() {
+ const read = () => this;
+ expect(read).toThrow(ReferenceError);
+ super(1);
+ expect(read().base).toBe(1);
+ }
+ }
+ new Uninitialized();
+});
+
+test("direct eval reads everything", () => {
+ function evaluates(value) {
+ const captured = () => value;
+ captured();
+ return [eval("this.name"), eval("new.target"), eval("value")];
+ }
+ expect(evaluates.call({ name: "object" }, 1)).toEqual(["object", undefined, 1]);
+
+ function evaluatesInArrow(value) {
+ return (() => [eval("this.name"), eval("new.target"), eval("value")])();
+ }
+ expect(evaluatesInArrow.call({ name: "object" }, 1)).toEqual(["object", undefined, 1]);
+
+ function nested(value) {
+ const inner = () => eval("var added = value + 1; added");
+ return inner();
+ }
+ expect(nested(1)).toBe(2);
+
+ class Base {
+ method() {
+ return "base";
+ }
+ }
+ class Derived extends Base {
+ method() {
+ const value = 1;
+ return () => eval("super.method()") + value;
+ }
+ }
+ expect(new Derived().method()()).toBe("base1");
+});
+
+test("generators and async functions with captured bindings", () => {
+ function* generator(value) {
+ const captured = () => value;
+ yield this.name;
+ yield captured();
+ yield (() => this.name)();
+ }
+ expect([...generator.call({ name: "object" }, 1)]).toEqual(["object", 1, "object"]);
+
+ let result;
+ async function asynchronous(value) {
+ const captured = () => value;
+ await null;
+ result = [this.name, captured(), (() => this.name)()];
+ }
+ asynchronous.call({ name: "object" }, 1);
+ runQueuedPromiseJobs();
+ expect(result).toEqual(["object", 1, "object"]);
+});
+
+test("arguments objects and parameter scopes", () => {
+ function mapped(a) {
+ const captured = () => a;
+ arguments[0] = 2;
+ return [captured(), arguments.length, this.name];
+ }
+ expect(repeated(() => mapped.call({ name: "object" }, 1))).toEqual([2, 1, "object"]);
+
+ function defaults(a, b = () => a) {
+ var a;
+ return b();
+ }
+ expect(repeated(() => defaults(1))).toBe(1);
+});
+
+test("class fields and static blocks", () => {
+ class Fields {
+ value = 1;
+ arrow = () => this.value;
+ static captured = (() => this.name)();
+ static {
+ const value = 2;
+ const read = () => [this.name, value];
+ this.read = read();
+ }
+ }
+ expect(repeated(() => new Fields().arrow())).toBe(1);
+ expect(Fields.captured).toBe("Fields");
+ expect(Fields.read).toEqual(["Fields", 2]);
+});