Skip to content

Truly independent web browser

LibJS: Switch to the new frontend

Andreas Klinge2a1e2239da3
diff --git a/Libraries/LibJS/CMakeLists.txt b/Libraries/LibJS/CMakeLists.txt
index b9493c9faf6..721c67c7330 100644
--- a/Libraries/LibJS/CMakeLists.txt
+++ b/Libraries/LibJS/CMakeLists.txt
@@ -29,7 +29,6 @@ set(SOURCES
Console.cpp
CyclicModule.cpp
Debugger.cpp
- DecodedBytecodeCache.cpp
Heap/Cell.cpp
Module.cpp
ParserError.cpp
diff --git a/Libraries/LibJS/Flap/src/rust_bytecode.rs b/Libraries/LibJS/Flap/src/rust_bytecode.rs
index 12b129f5b49..c744b9709c6 100644
--- a/Libraries/LibJS/Flap/src/rust_bytecode.rs
+++ b/Libraries/LibJS/Flap/src/rust_bytecode.rs
@@ -82,7 +82,7 @@ pub fn count_field_name<'a>(op: &'a InstructionDefinition, array_field: &Field)
/// A Rust expression reading a field of type `ty` from `bytes` at the byte
/// offset `offset` (itself a Rust expression). `reader` is the path prefix of
-/// the `read_u32` / `read_u64` helpers, for example `"super::validator::"`.
+/// the `read_u32` / `read_u64` helpers, for example `"super::operand::"`.
pub fn read_expr_for_type(ty: &str, offset: &str, reader: &str) -> String {
match ty {
"bool" => format!("bytes[{offset}] != 0"),
@@ -375,13 +375,20 @@ pub fn generate_encoded_size_method(mut w: impl Write, ops: &[InstructionDefinit
/// Emit `Instruction::encode()`, which serializes an instruction into bytes
/// in the struct layout of its fields. Must be called inside an `impl Instruction`.
-pub fn generate_encode_method(mut w: impl Write, ops: &[InstructionDefinition]) -> GeneratorResult {
+pub fn generate_encode_method(
+ mut w: impl Write,
+ ops: &[InstructionDefinition],
+ method_name: &str,
+ encoder_type: &str,
+) -> GeneratorResult {
writeln!(
w,
" /// Encode this instruction into bytes in the struct layout of its fields."
)?;
- writeln!(w, " pub fn encode(&self, strict: bool, buf: &mut Vec<u8>) {{")?;
- writeln!(w, " let start = buf.len();")?;
+ writeln!(
+ w,
+ " pub fn {method_name}(&self, strict: bool, encoder: &mut {encoder_type}) {{"
+ )?;
writeln!(w, " match self {{")?;
for op in ops {
@@ -400,174 +407,255 @@ pub fn generate_encode_method(mut w: impl Write, ops: &[InstructionDefinition])
)?;
}
- // Write header: opcode (u8) + strict (u8) = 2 bytes
- writeln!(w, " buf.push(OpCode::{} as u8);", op.name)?;
- writeln!(w, " buf.push(strict as u8);")?;
+ generate_encode_body(&mut w, op)?;
- // Track offset for the struct layout.
- // We iterate ALL fields (including m_type, m_strict, m_length) for
- // accurate alignment but only emit writes for user fields.
- let mut offset: usize = 2;
+ writeln!(w, " }}")?;
+ }
- // Iterate all non-array fields in declaration order
- for f in &op.fields {
- if f.is_array {
- continue;
- }
- // m_type and m_strict are already written as the header
- if f.name == "m_type" || f.name == "m_strict" {
- continue;
- }
+ writeln!(w, " }}")?;
+ writeln!(w, " }}")?;
+ writeln!(w)?;
+ Ok(())
+}
- let info = field_type_info(&f.ty);
- let field_offset = op.layout.field_offsets[&f.name];
- assert!(
- field_offset >= offset,
- "{}: tracked offset {offset} passed layout offset {field_offset} for {}",
- op.name,
- f.name
- );
- let pad = field_offset - offset;
- if pad > 0 {
- writeln!(w, " buf.extend_from_slice(&[0u8; {pad}]);")?;
- }
- offset = field_offset;
-
- if f.name == "m_length" {
- // Write placeholder (patched at end for variable-length instructions)
- writeln!(
- w,
- " buf.extend_from_slice(&[0u8; 4]); // m_length placeholder"
- )?;
- } else {
- let rname = rust_field_name(&f.name);
- emit_field_write(&mut w, &rname, info.kind, false)?;
- }
- offset += info.size;
+/// Emit the statements that encode `op`, whose fields are bound by reference.
+fn generate_encode_body(mut w: impl Write, op: &InstructionDefinition) -> GeneratorResult {
+ // The fixed part of the instruction goes through one buffer of its exact size.
+ let fixed_size = match &op.array {
+ Some(array) => array.offset,
+ None => op.layout.size.expect("fixed op missing encoded size"),
+ };
+ writeln!(w, " let mut out = [0u8; {fixed_size}];")?;
+ writeln!(w, " out[0] = OpCode::{} as u8;", op.name)?;
+ writeln!(w, " out[1] = strict as u8;")?;
+
+ // We iterate ALL fields (including m_type, m_strict, m_length) for
+ // accurate alignment but only emit writes for user fields.
+ for f in &op.fields {
+ if f.is_array || f.name == "m_type" || f.name == "m_strict" || f.name == "m_length" {
+ continue;
}
+ let info = field_type_info(&f.ty);
+ let field_offset = op.layout.field_offsets[&f.name];
+ assert!(
+ field_offset + info.size <= fixed_size,
+ "{}: field {} does not fit the fixed part",
+ op.name,
+ f.name
+ );
+ emit_field_store(&mut w, &rust_field_name(&f.name), info.kind, field_offset)?;
+ }
+ writeln!(w, " let start = encoder.bytes.len();")?;
+ writeln!(w, " encoder.bytes.extend_from_slice(&out);")?;
+
+ // Write trailing array elements
+ if let Some(array) = &op.array {
+ let field = &op.fields[array.field_index];
+ let info = field_type_info(&field.ty);
+ let rname = rust_field_name(&field.name);
+
+ writeln!(w, " for item in {rname} {{")?;
+ emit_field_write(&mut w, "item", info.kind)?;
+ writeln!(w, " }}")?;
+ writeln!(
+ w,
+ " let target = ({} + {}.len() * {} + 7) & !7;",
+ op.layout.minimum_size, rname, array.element_size
+ )?;
+ writeln!(w, " encoder.bytes.resize(start + target, 0);")?;
+
+ let m_length_offset = op
+ .layout
+ .m_length_offset
+ .expect("the parser requires m_length for array ops");
+ writeln!(w, " let total_len = target as u32;")?;
+ writeln!(
+ w,
+ " encoder.bytes[start + {}..start + {}].copy_from_slice(&total_len.to_ne_bytes());",
+ m_length_offset,
+ m_length_offset + 4
+ )?;
+ } else {
+ writeln!(w, " let _ = start;")?;
+ }
- // Write trailing array elements
- if let Some(array) = &op.array {
- let field = &op.fields[array.field_index];
- let info = field_type_info(&field.ty);
- let rname = rust_field_name(&field.name);
- assert!(
- array.offset >= offset,
- "{}: tracked offset {offset} passed array offset {} for {}",
- op.name,
- array.offset,
- field.name
- );
- let pad = array.offset - offset;
- if pad > 0 {
- writeln!(w, " buf.extend_from_slice(&[0u8; {pad}]);")?;
- }
-
- writeln!(w, " for item in {rname} {{")?;
- emit_field_write(&mut w, "item", info.kind, true)?;
- writeln!(w, " }}")?;
- writeln!(
- w,
- " let target = ({} + {}.len() * {} + 7) & !7;",
- op.layout.minimum_size, rname, array.element_size
- )?;
- writeln!(
- w,
- " while (buf.len() - start) < target {{ buf.push(0); }}"
- )?;
+ Ok(())
+}
- let m_length_offset = op
- .layout
- .m_length_offset
- .expect("the parser requires m_length for array ops");
- writeln!(w, " let total_len = (buf.len() - start) as u32;")?;
- writeln!(
- w,
- " buf[start + {}..start + {}].copy_from_slice(&total_len.to_ne_bytes());",
- m_length_offset,
- m_length_offset + 4
- )?;
+/// Emit a module with a plain struct for every instruction, for code that knows which instruction it writes: the fields
+/// are those of `Instruction`, with a slice for a trailing array, so writing one takes no allocation and no enum.
+/// `specializable_operands` names the operands of an instruction whose value may select a specialized form.
+pub fn generate_typed_instructions(
+ mut w: impl Write,
+ ops: &[InstructionDefinition],
+ module_name: &str,
+ encoder_type: &str,
+ specializable_operands: &dyn Fn(&str) -> Vec<String>,
+) -> GeneratorResult {
+ writeln!(w, "pub mod {module_name} {{")?;
+ writeln!(w, "use super::*;")?;
+ writeln!(w)?;
+ writeln!(w, "pub trait TypedInstruction {{")?;
+ writeln!(w, " const OPCODE: OpCode;")?;
+ writeln!(w, " const IS_TERMINATOR: bool;")?;
+ writeln!(
+ w,
+ " /// Whether an operand that is a constant may select a specialized form."
+ )?;
+ writeln!(w, " fn may_specialize(&self) -> bool;")?;
+ writeln!(w, " fn encode(&self, strict: bool, encoder: &mut {encoder_type});")?;
+ writeln!(w, " fn to_instruction(&self) -> Instruction;")?;
+ writeln!(w, "}}")?;
+ writeln!(w)?;
+ for op in ops {
+ let fields = user_fields(op);
+ let has_array = fields.iter().any(|f| f.is_array);
+ let lifetime = if has_array { "<'a>" } else { "" };
+ let anonymous_lifetime = if has_array { "<'_>" } else { "" };
+ writeln!(w, "#[derive(Clone, Copy)]")?;
+ if fields.is_empty() {
+ writeln!(w, "pub struct {} {{}}", op.name)?;
} else {
- let final_size = op.layout.size.expect("fixed op missing encoded size");
- assert!(
- final_size >= offset,
- "{}: tracked offset {offset} passed final size {final_size}",
- op.name
- );
- let tail_pad = final_size - offset;
- if tail_pad > 0 {
- writeln!(w, " buf.extend_from_slice(&[0u8; {tail_pad}]);")?;
+ writeln!(w, "pub struct {}{lifetime} {{", op.name)?;
+ for f in &fields {
+ let info = field_type_info(&f.ty);
+ let r_name = rust_field_name(&f.name);
+ if f.is_array {
+ writeln!(w, " pub {}: &'a [{}],", r_name, info.rust_type)?;
+ } else {
+ writeln!(w, " pub {}: {},", r_name, info.rust_type)?;
+ }
}
+ writeln!(w, "}}")?;
}
-
- writeln!(w, " }}")?;
+ writeln!(w, "impl TypedInstruction for {}{anonymous_lifetime} {{", op.name)?;
+ writeln!(w, " const OPCODE: OpCode = OpCode::{};", op.name)?;
+ writeln!(w, " const IS_TERMINATOR: bool = {};", op.is_terminator)?;
+ let operands = specializable_operands(&op.name);
+ writeln!(w, " #[inline(always)]")?;
+ if operands.is_empty() {
+ writeln!(w, " fn may_specialize(&self) -> bool {{ false }}")?;
+ } else {
+ let tests = operands
+ .iter()
+ .map(|operand| format!("self.{operand}.is_constant()"))
+ .collect::<Vec<_>>();
+ writeln!(w, " fn may_specialize(&self) -> bool {{ {} }}", tests.join(" || "))?;
+ }
+ writeln!(w, " #[inline(always)]")?;
+ writeln!(w, " fn encode(&self, strict: bool, encoder: &mut {encoder_type}) {{")?;
+ if !fields.is_empty() {
+ let bindings: Vec<String> = fields.iter().map(|f| rust_field_name(&f.name)).collect();
+ writeln!(w, " let Self {{ {} }} = self;", bindings.join(", "))?;
+ for f in fields.iter().filter(|f| f.is_array) {
+ let name = rust_field_name(&f.name);
+ writeln!(w, " let {name} = *{name};")?;
+ }
+ }
+ generate_encode_body(&mut w, op)?;
+ writeln!(w, " }}")?;
+ writeln!(w, " #[inline(always)]")?;
+ writeln!(w, " fn to_instruction(&self) -> Instruction {{")?;
+ if fields.is_empty() {
+ writeln!(w, " Instruction::{}", op.name)?;
+ } else {
+ let values: Vec<String> = fields
+ .iter()
+ .map(|f| {
+ let name = rust_field_name(&f.name);
+ if f.is_array {
+ format!("{name}: self.{name}.to_vec()")
+ } else {
+ format!("{name}: self.{name}")
+ }
+ })
+ .collect();
+ writeln!(w, " Instruction::{} {{ {} }}", op.name, values.join(", "))?;
+ }
+ writeln!(w, " }}")?;
+ writeln!(w, "}}")?;
}
-
- writeln!(w, " }}")?;
- writeln!(w, " }}")?;
+ writeln!(w, "}}")?;
writeln!(w)?;
Ok(())
}
-/// Emit code to write a field value into `w`.
+/// Emit code to store a field of the fixed part of an instruction into `out` at `offset`.
///
-/// All bindings from pattern matching and loop iteration are references (`&T`).
-/// Rust auto-derefs for method calls, but explicit `*` is needed for casts
-/// and direct pushes of Copy types.
-fn emit_field_write(mut w: impl Write, name: &str, kind: &str, is_loop_item: bool) -> GeneratorResult {
- let prefix = " ".repeat(if is_loop_item { 20 } else { 16 });
+/// All bindings from pattern matching are references (`&T`). Rust auto-derefs for method calls, but explicit `*` is
+/// needed for casts and direct stores of Copy types.
+fn emit_field_store(mut w: impl Write, name: &str, kind: &str, offset: usize) -> GeneratorResult {
+ let prefix = " ".repeat(16);
+ let store = |value: &str, size: usize| format!("out[{offset}..{}].copy_from_slice(&{value});", offset + size);
match kind {
- "bool" => writeln!(w, "{prefix}buf.push(*{name} as u8);")?,
- "u8" => writeln!(w, "{prefix}buf.push(*{name});")?,
- "i32" => writeln!(w, "{prefix}buf.extend_from_slice(&{name}.to_ne_bytes());")?,
- "u16" => writeln!(w, "{prefix}buf.extend_from_slice(&{name}.to_ne_bytes());")?,
- "u32" => writeln!(w, "{prefix}buf.extend_from_slice(&{name}.to_ne_bytes());")?,
- "u64" => writeln!(w, "{prefix}buf.extend_from_slice(&{name}.to_ne_bytes());")?,
- "operand" => writeln!(w, "{prefix}buf.extend_from_slice(&{name}.raw().to_ne_bytes());")?,
+ "bool" => writeln!(w, "{prefix}out[{offset}] = *{name} as u8;")?,
+ "u8" => writeln!(w, "{prefix}out[{offset}] = *{name};")?,
+ "i32" | "u32" => writeln!(w, "{prefix}{}", store(&format!("{name}.to_ne_bytes()"), 4))?,
+ "u16" => writeln!(w, "{prefix}{}", store(&format!("{name}.to_ne_bytes()"), 2))?,
+ "u64" => writeln!(w, "{prefix}{}", store(&format!("{name}.to_ne_bytes()"), 8))?,
+ "operand" => writeln!(
+ w,
+ "{prefix}{}",
+ store(&format!("encoder.operand(*{name}, {offset}).to_ne_bytes()"), 4)
+ )?,
"optional_operand" => {
- writeln!(w, "{prefix}match {name} {{")?;
- writeln!(
- w,
- "{prefix} Some(op) => buf.extend_from_slice(&op.raw().to_ne_bytes()),"
- )?;
- writeln!(
- w,
- "{prefix} None => buf.extend_from_slice(&Operand::INVALID.to_ne_bytes()),"
- )?;
- writeln!(w, "{prefix}}}")?;
+ let value = format!("{name}.map_or(Operand::INVALID, |op| encoder.operand(op, {offset})).to_ne_bytes()");
+ writeln!(w, "{prefix}{}", store(&value, 4))?;
+ }
+ "label" => {
+ writeln!(w, "{prefix}encoder.note_label({offset});")?;
+ writeln!(w, "{prefix}{}", store(&format!("{name}.0.to_ne_bytes()"), 4))?;
}
- "label" => writeln!(w, "{prefix}buf.extend_from_slice(&{name}.0.to_ne_bytes());")?,
"optional_label" => {
// Optional<Label> layout: u32 value, bool has_value, 3 bytes padding = 8 bytes total
- writeln!(w, "{prefix}match {name} {{")?;
- writeln!(w, "{prefix} Some(lbl) => {{")?;
- writeln!(w, "{prefix} buf.extend_from_slice(&lbl.0.to_ne_bytes());")?;
- writeln!(w, "{prefix} buf.push(1); buf.push(0); buf.push(0); buf.push(0);")?;
- writeln!(w, "{prefix} }}")?;
- writeln!(w, "{prefix} None => {{")?;
- writeln!(w, "{prefix} buf.extend_from_slice(&0u32.to_ne_bytes());")?;
- writeln!(w, "{prefix} buf.push(0); buf.push(0); buf.push(0); buf.push(0);")?;
- writeln!(w, "{prefix} }}")?;
+ writeln!(w, "{prefix}if let Some(lbl) = {name} {{")?;
+ writeln!(w, "{prefix} encoder.note_label({offset});")?;
+ writeln!(w, "{prefix} {}", store("lbl.0.to_ne_bytes()", 4))?;
+ writeln!(w, "{prefix} out[{}] = 1;", offset + 4)?;
writeln!(w, "{prefix}}}")?;
}
- "u32_newtype" => writeln!(w, "{prefix}buf.extend_from_slice(&{name}.0.to_ne_bytes());")?,
+ "u32_newtype" => writeln!(w, "{prefix}{}", store(&format!("{name}.0.to_ne_bytes()"), 4))?,
"optional_u32_newtype" => {
- writeln!(w, "{prefix}match {name} {{")?;
+ let value = format!("{name}.map_or(0xFFFF_FFFFu32, |idx| idx.0).to_ne_bytes()");
+ writeln!(w, "{prefix}{}", store(&value, 4))?;
+ }
+ "env_coord" => {
+ writeln!(w, "{prefix}{}", store(&format!("{name}.hops.to_ne_bytes()"), 4))?;
writeln!(
w,
- "{prefix} Some(idx) => buf.extend_from_slice(&idx.0.to_ne_bytes()),"
+ "{prefix}out[{}..{}].copy_from_slice(&{name}.index.to_ne_bytes());",
+ offset + 4,
+ offset + 8
)?;
+ }
+ other => panic!("Unknown encoding kind: {other}"),
+ }
+
+ Ok(())
+}
+
+/// Emit code to append an element of the trailing array of an instruction, a reference, to the encoder.
+fn emit_field_write(mut w: impl Write, name: &str, kind: &str) -> GeneratorResult {
+ let prefix = " ".repeat(20);
+ match kind {
+ "bool" => writeln!(w, "{prefix}encoder.bytes.push(*{name} as u8);")?,
+ "u8" => writeln!(w, "{prefix}encoder.bytes.push(*{name});")?,
+ "i32" | "u16" | "u32" | "u64" => {
+ writeln!(w, "{prefix}encoder.bytes.extend_from_slice(&{name}.to_ne_bytes());")?
+ }
+ "operand" => {
+ writeln!(w, "{prefix}let raw = encoder.operand(*{name}, 0);")?;
+ writeln!(w, "{prefix}encoder.bytes.extend_from_slice(&raw.to_ne_bytes());")?;
+ }
+ "optional_operand" => {
writeln!(
w,
- "{prefix} None => buf.extend_from_slice(&0xFFFF_FFFFu32.to_ne_bytes()),"
+ "{prefix}let raw = {name}.map_or(Operand::INVALID, |op| encoder.operand(op, 0));"
)?;
- writeln!(w, "{prefix}}}")?;
+ writeln!(w, "{prefix}encoder.bytes.extend_from_slice(&raw.to_ne_bytes());")?;
}
- "env_coord" => {
- writeln!(w, "{prefix}buf.extend_from_slice(&{name}.hops.to_ne_bytes());")?;
- writeln!(w, "{prefix}buf.extend_from_slice(&{name}.index.to_ne_bytes());")?;
- }
- other => panic!("Unknown encoding kind: {other}"),
+ "u32_newtype" => writeln!(w, "{prefix}encoder.bytes.extend_from_slice(&{name}.0.to_ne_bytes());")?,
+ other => panic!("Unknown array element encoding kind: {other}"),
}
Ok(())
diff --git a/Libraries/LibJS/JIT/Rust/build.rs b/Libraries/LibJS/JIT/Rust/build.rs
index 60a6d6d6e6d..ea42e097242 100644
--- a/Libraries/LibJS/JIT/Rust/build.rs
+++ b/Libraries/LibJS/JIT/Rust/build.rs
@@ -415,8 +415,24 @@ fn generate_rust_code(mut w: impl Write, ops: &[InstructionDefinition], record_f
writeln!(w, "#[cfg(test)]")?;
writeln!(w, "#[allow(dead_code)]")?;
writeln!(w, "impl Instruction {{")?;
- generate_encode_method(&mut w, ops)?;
+ generate_encode_method(&mut w, ops, "encode_with", "TestEncoder<'_>")?;
generate_encoded_size_method(&mut w, ops)?;
+ writeln!(
+ w,
+ " pub fn encode(&self, strict: bool, bytes: &mut Vec<u8>) {{ self.encode_with(strict, &mut TestEncoder {{ bytes }}); }}"
+ )?;
+ writeln!(w, "}}")?;
+ writeln!(w)?;
+ writeln!(w, "#[cfg(test)]")?;
+ writeln!(w, "pub struct TestEncoder<'a> {{ bytes: &'a mut Vec<u8> }}")?;
+ writeln!(w)?;
+ writeln!(w, "#[cfg(test)]")?;
+ writeln!(w, "impl TestEncoder<'_> {{")?;
+ writeln!(
+ w,
+ " fn operand(&mut self, operand: Operand, _: usize) -> u32 {{ operand.raw() }}"
+ )?;
+ writeln!(w, " fn note_label(&mut self, _: usize) {{}}")?;
writeln!(w, "}}")?;
Ok(())
}
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs b/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
index 70be92e08b9..d75cfee4beb 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
@@ -15,10 +15,11 @@
//! Each back edge gets an entry block without predecessors that loads the
//! slots live into the back edge instruction from the frame and then runs the
//! instruction itself, or jumps to its block where the instruction starts it
-//! (as the tests at the bottom of loops do). Where the instruction jumps to the
-//! update step of a for loop, which leads to the loop's header, the entry runs
-//! that step itself instead. Its edges are forward edges into the loop and the
-//! loop exit, so the values it loaded meet the other paths in phis.
+//! (as the tests at the bottom of loops do). Where the instruction jumps to a
+//! block that leads to the loop's header and nowhere else, like the body of a
+//! for loop whose test is a constant, the entry runs that block itself instead.
+//! Its edges are forward edges into the loop and the loop exit, so the values
+//! it loaded meet the other paths in phis.
//!
//! Generators and async functions resume the same way: a suspended frame holds
//! every value live at the continuation it resumes at (see `build_suspend()`),
@@ -119,9 +120,10 @@ impl GraphBuilder<'_> {
// Unconditional back edges jump to their loop's header
// directly instead, since entering a block of the loop
// other than its header would make the loop irreducible.
- // Those of loops whose update step has a block of its own
- // (like for loops with a continue) jump to that step, which
- // the entry runs itself before it continues at the header.
+ // Those that jump to a block leading to the header (like the
+ // body of a for loop whose test is a constant, where the test
+ // is the header) have the entry run that block itself before
+ // it continues at the header.
let opcode = self.function.instructions[index].instruction.opcode();
let own_block = self
.function
@@ -132,9 +134,9 @@ impl GraphBuilder<'_> {
if let Some(own_block) = own_block {
self.end_with_jump(own_block)?;
targets.push(own_block);
- } else if let Some(update_block) = self.update_block_of_back_edge(index) {
- self.build_bytecode_block(update_block)?;
- targets.extend(self.function.cfg.blocks[update_block].successors.iter().copied());
+ } else if let Some(block_before_header) = self.block_before_header_of_back_edge(index) {
+ self.build_bytecode_block(block_before_header)?;
+ targets.extend(self.function.cfg.blocks[block_before_header].successors.iter().copied());
} else {
match self.build_instruction()? {
Flow::Ended => {}
@@ -274,7 +276,7 @@ impl GraphBuilder<'_> {
/// The block that the unconditional back edge at instruction `index` jumps
/// to, if it is no loop header and leads to one and nowhere else.
- fn update_block_of_back_edge(&self, index: usize) -> Option<BlockIndex> {
+ fn block_before_header_of_back_edge(&self, index: usize) -> Option<BlockIndex> {
let instruction = &self.function.instructions[index].instruction;
if instruction.opcode() != OpCode::JumpLoop {
return None;
diff --git a/Libraries/LibJS/Rust/build.rs b/Libraries/LibJS/Rust/build.rs
index a594d911a0b..e9cd2b73fa8 100644
--- a/Libraries/LibJS/Rust/build.rs
+++ b/Libraries/LibJS/Rust/build.rs
@@ -101,13 +101,6 @@ fn target() -> Target {
/// Mirrors GC::HEAP_REGION_SIZE in Libraries/LibGC/HeapRegion.h.
const HEAP_REGION_SIZE: u64 = 32 * GIB;
-/// The 64-bit FNV-1a hash of `bytes`, which stays the same from build to build, unlike std's hashers.
-fn fnv1a_64(bytes: &[u8]) -> u64 {
- bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, &byte| {
- (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
- })
-}
-
fn main() {
let manifest_directory = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
let output_directory = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));
@@ -125,19 +118,6 @@ fn main() {
instructions::generate(&interpreter_source, &output_directory).expect("generate the frontend's instruction types");
- // NB: Bytecode cache blobs hold encoded instructions, so a blob is only good for the instruction set it was encoded
- // with. The generated instruction types spell out every opcode, in the order that numbers them, and every
- // operand, so their fingerprint changes with any change to the instructions in interpreter.flap.
- let instruction_types =
- fs::read(output_directory.join("instruction_generated.rs")).expect("read instruction_generated.rs");
- write_if_changed(
- &output_directory.join("instruction_set_fingerprint.rs"),
- &format!(
- "pub(crate) const INSTRUCTION_SET_FINGERPRINT: u64 = {:#018x};\n",
- fnv1a_64(&instruction_types)
- ),
- );
-
let target = target();
let address_sanitizer = env::var_os("CARGO_FEATURE_ADDRESS_SANITIZER").is_some();
let configuration = layout_table::LayoutConfiguration {
diff --git a/Libraries/LibJS/Rust/generate/instructions.rs b/Libraries/LibJS/Rust/generate/instructions.rs
index 2574d23b2da..58b4a775118 100644
--- a/Libraries/LibJS/Rust/generate/instructions.rs
+++ b/Libraries/LibJS/Rust/generate/instructions.rs
@@ -21,23 +21,21 @@ use flapc::metadata::user_fields;
use flapc::rust_bytecode::InstructionSet;
use flapc::rust_bytecode::count_field_name;
use flapc::rust_bytecode::generate_encode_method;
-use flapc::rust_bytecode::generate_encoded_size_method;
use flapc::rust_bytecode::generate_field_reads;
use flapc::rust_bytecode::generate_instruction_enum;
use flapc::rust_bytecode::generate_instruction_is_terminator_from_opcode;
use flapc::rust_bytecode::generate_instruction_length_from_bytes;
use flapc::rust_bytecode::generate_instruction_name_from_opcode;
-use flapc::rust_bytecode::generate_is_terminator_method;
use flapc::rust_bytecode::generate_num_opcodes_const;
use flapc::rust_bytecode::generate_opcode_enum;
-use flapc::rust_bytecode::generate_opcode_method;
+use flapc::rust_bytecode::generate_typed_instructions;
use flapc::rust_bytecode::rust_field_name;
use std::fs;
use std::io::Write;
use std::path::Path;
/// Path prefix of the `read_u32` / `read_u64` helpers used by generated field reads.
-const READER: &str = "super::validator::";
+const READER: &str = "super::operand::";
fn generate_rust_code(
mut w: impl Write,
@@ -55,18 +53,49 @@ fn generate_rust_code(
generate_num_opcodes_const(&mut w, ops)?;
generate_instruction_enum(&mut w, ops, "Debug, Clone")?;
generate_instruction_impl(&mut w, ops)?;
- generate_instruction_length_from_bytes(&mut w, ops, "super::validator::ValidationErrorKind")?;
+ generate_instruction_length_from_bytes(&mut w, ops, "super::operand::InstructionLengthError")?;
generate_instruction_name_from_opcode(&mut w, ops)?;
generate_instruction_feedback_slots_from_bytes(&mut w, ops)?;
generate_instruction_dump_from_bytes(&mut w, ops)?;
generate_visit_labels_from_bytes(&mut w, ops)?;
generate_instruction_is_terminator_from_opcode(&mut w, ops)?;
- generate_validate_instruction(&mut w, ops)?;
generate_specialization_selector(&mut w, ops, specializations, specialized_ops)?;
+ generate_typed_instructions(
+ &mut w,
+ ops,
+ "typed",
+ "crate::bytecode::codegen::emitter::BlockEncoder<'_>",
+ &|name| specializable_operands(name, specializations),
+ )?;
Ok(())
}
+/// The operands of the instruction called `name` that a specialization looks at. The emitter only
+/// holds back `Mov` for specializations of several instructions, which this makes sure stays all it has to do.
+fn specializable_operands(name: &str, specializations: &[Specialization]) -> Vec<String> {
+ let mut operands = Vec::new();
+ for specialization in specializations {
+ assert!(
+ specialization.components.len() == 1
+ || specialization
+ .components
+ .iter()
+ .all(|component| component.bytecode == "Mov"),
+ "only Mov may specialize as part of a sequence"
+ );
+ if name != "Mov" && specialization.components[0].bytecode == name {
+ for parameter in &specialization.components[0].parameters {
+ let operand = rust_field_name(&parameter.name);
+ if !operands.contains(&operand) {
+ operands.push(operand);
+ }
+ }
+ }
+ }
+ operands
+}
+
/// Emits `instruction_feedback_slots_from_bytes()`, which reads the feedback slot indices of the instruction at
/// `bytes[at..]`, one per feedback kind it records.
fn generate_instruction_feedback_slots_from_bytes(
@@ -137,7 +166,19 @@ fn generate_specialization_selector(
writeln!(w, "#[allow(clippy::unnecessary_unwrap)]")?;
writeln!(
w,
- "pub fn specialize_instruction_sequence<'a>(instructions: impl Iterator<Item = &'a Instruction> + Clone, constants: &[super::generator::ConstantValue]) -> Option<(Instruction, usize)> {{"
+ "pub fn specialize_instruction_sequence<'a>(instructions: impl Iterator<Item = &'a Instruction> + Clone, constants: &[super::executable_data::ConstantValue]) -> Option<(Instruction, usize)> {{"
+ )?;
+ // Most instructions start no sequence at all, which one look at the first of them tells.
+ let mut first_ops = specializations
+ .iter()
+ .map(|specialization| format!("Instruction::{} {{ .. }}", specialization.components[0].bytecode))
+ .collect::<Vec<_>>();
+ first_ops.sort();
+ first_ops.dedup();
+ writeln!(
+ w,
+ " if !matches!(instructions.clone().next(), Some({})) {{ return None; }}",
+ first_ops.join(" | ")
)?;
for index in order {
let specialization = &specializations[index];
@@ -178,7 +219,7 @@ fn generate_specialization_selector(
)?;
writeln!(
w,
- " super::generator::ConstantValue::Number(number) if number.fract() == 0.0 && *number >= i32::MIN as f64 && *number <= i32::MAX as f64 && number.to_bits() != (-0.0_f64).to_bits() => Some(*number as i32),"
+ " super::executable_data::ConstantValue::Number(number) if number.fract() == 0.0 && *number >= i32::MIN as f64 && *number <= i32::MAX as f64 && number.to_bits() != (-0.0_f64).to_bits() => Some(*number as i32),"
)?;
writeln!(w, " _ => None,")?;
writeln!(w, " }});")?;
@@ -187,7 +228,7 @@ fn generate_specialization_selector(
}
SpecializationConstraint::Undefined => {
conditions.push(format!(
- "{operand}.is_constant() && matches!(constants.get({operand}.index() as usize), Some(super::generator::ConstantValue::Undefined))"
+ "{operand}.is_constant() && matches!(constants.get({operand}.index() as usize), Some(super::executable_data::ConstantValue::Undefined))"
));
}
}
@@ -533,350 +574,19 @@ fn generate_visit_labels_from_bytes(
Ok(())
}
-fn emit_scalar_field_check(
- mut w: impl Write,
- field_name: &str,
- ty: &str,
- offset: usize,
-) -> Result<(), Box<dyn std::error::Error>> {
- match ty {
- "Operand" => writeln!(w, " validate_operand(read_u32(bytes, at + {offset}), ctx)?;")?,
- "Optional<Operand>" => writeln!(
- w,
- " validate_optional_operand(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "Label" => writeln!(w, " validate_label(read_u32(bytes, at + {offset}), ctx)?;")?,
- "Optional<Label>" => {
- // Encoded as 8 bytes: u32 value + u8 has_value + 3 bytes pad.
- writeln!(w, " if bytes[at + {offset} + 4] != 0 {{")?;
- writeln!(
- w,
- " validate_label(read_u32(bytes, at + {offset}), ctx)?;"
- )?;
- writeln!(w, " }}")?;
- }
- "IdentifierTableIndex" => writeln!(
- w,
- " validate_identifier_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "Optional<IdentifierTableIndex>" => writeln!(
- w,
- " validate_optional_identifier_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "StringTableIndex" => writeln!(
- w,
- " validate_string_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "Optional<StringTableIndex>" => writeln!(
- w,
- " validate_optional_string_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "PropertyKeyTableIndex" => writeln!(
- w,
- " validate_property_key_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "PropertyLookupCacheIndex" => writeln!(
- w,
- " validate_property_lookup_cache_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "GlobalVariableCacheIndex" => writeln!(
- w,
- " validate_global_variable_cache_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "EnvironmentCoordinateCacheIndex" => writeln!(
- w,
- " validate_environment_coordinate_cache_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "TemplateObjectCacheIndex" => writeln!(
- w,
- " validate_template_object_cache_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "ObjectShapeCacheIndex" => writeln!(
- w,
- " validate_object_shape_cache_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "ObjectPropertyIteratorCacheIndex" => writeln!(
- w,
- " validate_object_property_iterator_cache_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "EnvironmentShapeCacheIndex" => writeln!(
- w,
- " validate_environment_shape_cache_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "ArithFeedbackIndex" => writeln!(
- w,
- " validate_arith_feedback_index(read_u16(bytes, at + {offset}), ctx)?;"
- )?,
- "ValueFeedbackIndex" => writeln!(
- w,
- " validate_value_feedback_index(read_u16(bytes, at + {offset}), ctx)?;"
- )?,
- "CallFeedbackIndex" => writeln!(
- w,
- " validate_call_feedback_index(read_u16(bytes, at + {offset}), ctx)?;"
- )?,
- "KeyedFeedbackIndex" => writeln!(
- w,
- " validate_keyed_feedback_index(read_u16(bytes, at + {offset}), ctx)?;"
- )?,
- "u32" => {
- // The handler signature gives us no first-class types for SFD,
- // class-blueprint, or object-shape cache references stored as u32.
- // Recognize the canonical field names so these still get
- // range-checked.
- if field_name == "m_shared_function_data_index" {
- writeln!(
- w,
- " validate_shared_function_data_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?;
- } else if field_name == "m_class_blueprint_index" {
- writeln!(
- w,
- " validate_class_blueprint_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?;
- } else if field_name == "m_shape_cache_index" {
- writeln!(
- w,
- " validate_object_shape_cache_index(read_u32(bytes, at + {offset}), ctx)?;"
- )?;
- }
- }
- "Completion::Type" => writeln!(
- w,
- " validate_completion_type(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "IteratorHint" => writeln!(
- w,
- " validate_iterator_hint(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "EnvironmentMode" => writeln!(
- w,
- " validate_environment_mode(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "PutKind" => writeln!(
- w,
- " validate_put_kind(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "ArgumentsKind" => writeln!(
- w,
- " validate_arguments_kind(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- "FunctionNamePrefix" => writeln!(
- w,
- " validate_function_name_prefix(read_u32(bytes, at + {offset}), ctx)?;"
- )?,
- // bool, i32, u64, Value, EnvironmentCoordinate, Builtin: no per-field
- // bound applied here.
- _ => {}
- }
- Ok(())
-}
-
-fn emit_array_elem_check(mut w: impl Write, ty: &str) -> Result<(), Box<dyn std::error::Error>> {
- match ty {
- "Operand" => writeln!(w, " validate_operand(read_u32(bytes, __off), ctx)?;")?,
- "Optional<Operand>" => writeln!(
- w,
- " validate_optional_operand(read_u32(bytes, __off), ctx)?;"
- )?,
- "Value" => {
- // Trailing Value array (NewPrimitiveArray): no per-element check;
- // the count was already bounded against the instruction length.
- }
- other => panic!("Array element type not supported: {other}"),
- }
- Ok(())
-}
-
-fn generate_validate_instruction(
- mut w: impl Write,
- ops: &[InstructionDefinition],
-) -> Result<(), Box<dyn std::error::Error>> {
- let layouts = compute_layouts(ops);
-
- writeln!(
- w,
- "/// Per-opcode field validation, dispatched by Pass 2 of the validator."
- )?;
- writeln!(
- w,
- "pub fn validate_instruction(opcode: u8, ctx: &super::validator::ValidationContext, at: usize) -> Result<(), super::validator::ValidationErrorKind> {{"
- )?;
- writeln!(w, " use super::validator::*;")?;
- writeln!(w, " let bytes = ctx.bytes;")?;
- writeln!(w, " match opcode {{")?;
-
- for (i, op) in ops.iter().enumerate() {
- let layout = layouts.get(&op.name).expect("layout missing for op");
- let arrays: Vec<&Field> = op.fields.iter().filter(|f| f.is_array).collect();
- let has_array = !arrays.is_empty();
-
- // Map each count field's name to the array it sizes, so we can skip
- // the count field when emitting scalar checks (it gets read alongside
- // the array bound below) and avoid duplicate work.
- let mut count_field_names: std::collections::HashSet<String> = std::collections::HashSet::new();
- for af in &arrays {
- count_field_names.insert(count_field_name(op, af).to_string());
- }
-
- let op_name = &op.name;
- writeln!(w, " {i} => {{ // {op_name}")?;
-
- for f in &op.fields {
- if f.is_array {
- continue;
- }
- if f.name == "m_type" || f.name == "m_strict" || f.name == "m_length" {
- continue;
- }
- if count_field_names.contains(&f.name) {
- continue;
- }
- let offset = *layout.field_offsets.get(&f.name).expect("missing field offset");
- emit_scalar_field_check(&mut w, &f.name, &f.ty, offset)?;
- }
-
- if has_array {
- let m_length_offset = *layout
- .field_offsets
- .get("m_length")
- .expect("variable-length op missing m_length");
- // All variable-length bytecodes carry exactly one trailing
- // array; if that ever changes, this loop validates each independently.
- for af in &arrays {
- let array_offset = *layout.field_offsets.get(&af.name).expect("missing array offset");
- let count_field = count_field_name(op, af);
- let count_offset = *layout
- .field_offsets
- .get(count_field)
- .expect("missing count field offset");
- let elem_size = field_type_info(&af.ty).size;
-
- writeln!(
- w,
- " let __m_length = read_u32(bytes, at + {m_length_offset}) as usize;"
- )?;
- writeln!(
- w,
- " let __count = read_u32(bytes, at + {count_offset}) as usize;"
- )?;
- writeln!(
- w,
- " let __array_bytes = __count.saturating_mul({elem_size});"
- )?;
- writeln!(
- w,
- " if {array_offset}usize.saturating_add(__array_bytes) > __m_length {{"
- )?;
- writeln!(w, " return Err(ValidationErrorKind::InvalidLength);")?;
- writeln!(w, " }}")?;
- writeln!(w, " let __array_off = at + {array_offset};")?;
- writeln!(w, " for __i in 0..__count {{")?;
- writeln!(w, " let __off = __array_off + __i * {elem_size};")?;
- emit_array_elem_check(&mut w, &af.ty)?;
- writeln!(w, " }}")?;
- }
- }
-
- writeln!(w, " }}")?;
- }
-
- writeln!(w, " _ => {{}}")?;
- writeln!(w, " }}")?;
- writeln!(w, " Ok(())")?;
- writeln!(w, "}}")?;
- writeln!(w)?;
-
- Ok(())
-}
-
fn generate_instruction_impl(
mut w: impl Write,
ops: &[InstructionDefinition],
) -> Result<(), Box<dyn std::error::Error>> {
writeln!(w, "impl Instruction {{").unwrap();
- generate_opcode_method(&mut w, ops)?;
- generate_is_terminator_method(&mut w, ops)?;
- generate_encode_method(&mut w, ops)?;
- generate_encoded_size_method(&mut w, ops)?;
- generate_visit_operands_method(&mut w, ops)?;
- generate_visit_labels_method(&mut w, ops)?;
- writeln!(w, " }}")?;
- Ok(())
-}
-
-fn generate_visit_operands_method(
- mut w: impl Write,
- ops: &[InstructionDefinition],
-) -> Result<(), Box<dyn std::error::Error>> {
- writeln!(w, " /// Visit all `Operand` fields (for operand rewriting).")?;
- writeln!(
- w,
- " pub fn visit_operands(&mut self, visitor: &mut dyn FnMut(&mut Operand)) {{"
+ generate_encode_method(
+ &mut w,
+ ops,
+ "encode_into_block",
+ "crate::bytecode::codegen::emitter::BlockEncoder<'_>",
)?;
- writeln!(w, " match self {{")?;
-
- for op in ops {
- let fields = user_fields(op);
- let operand_fields: Vec<&&Field> = fields
- .iter()
- .filter(|f| f.ty == "Operand" || f.ty == "Optional<Operand>")
- .collect();
-
- if operand_fields.is_empty() {
- let pat = if fields.is_empty() {
- format!("Instruction::{}", op.name)
- } else {
- format!("Instruction::{} {{ .. }}", op.name)
- };
- writeln!(w, " {pat} => {{}}")?;
- continue;
- }
-
- // Bind the operand fields
- let bindings: Vec<String> = fields
- .iter()
- .map(|f| {
- let rname = rust_field_name(&f.name);
- if f.ty == "Operand" || f.ty == "Optional<Operand>" {
- rname
- } else {
- format!("{rname}: _")
- }
- })
- .collect();
- writeln!(
- w,
- " Instruction::{} {{ {} }} => {{",
- op.name,
- bindings.join(", ")
- )?;
-
- for f in &operand_fields {
- let rname = rust_field_name(&f.name);
- if f.is_array {
- if f.ty == "Optional<Operand>" {
- writeln!(
- w,
- " for op in {rname}.iter_mut().flatten() {{ visitor(op); }}"
- )?;
- } else {
- writeln!(w, " for item in {rname}.iter_mut() {{ visitor(item); }}")?;
- }
- } else if f.ty == "Optional<Operand>" {
- writeln!(w, " if let Some(op) = {rname} {{ visitor(op); }}")?;
- } else {
- writeln!(w, " visitor({rname});")?;
- }
- }
-
- writeln!(w, " }}")?;
- }
-
- writeln!(w, " }}")?;
+ generate_visit_labels_method(&mut w, ops)?;
writeln!(w, " }}")?;
- writeln!(w)?;
-
Ok(())
}
diff --git a/Libraries/LibJS/Rust/src/ast.rs b/Libraries/LibJS/Rust/src/ast.rs
index 482d846ec60..9d7b94a1eee 100644
--- a/Libraries/LibJS/Rust/src/ast.rs
+++ b/Libraries/LibJS/Rust/src/ast.rs
@@ -4,941 +4,1182 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! AST types for JavaScript.
-//!
-//! This module defines the Abstract Syntax Tree using idiomatic Rust enums.
-//! Every node carries a `SourceRange` for error messages and source maps.
-//!
-//! ## Design
-//!
-//! - `ExpressionKind` and `StatementKind` are flat enums — pattern matching
-//! replaces virtual dispatch.
-//! - `Node<T>` wraps every AST node with source location info.
-//! - `Identifier` carries scope analysis results as plain fields, written
-//! by the scope collector through `&mut arena.identifiers[id]` after
-//! parsing.
-//! - Operator enums use `#[repr(u8)]` with ABI-compatible values for
-//! trivial FFI conversion.
-//! - `ScopeData` is carried by block-like constructs (Program,
-//! BlockStatement, FunctionBody, etc.) and holds scope analysis results.
-
-use std::ops::Index;
-use std::ops::IndexMut;
-use std::sync::Arc;
+//! The syntax tree of a program, which the parser writes as flat columns and everything after it reads through typed
+//! views. A view is a small `Copy` handle of a tree and a node: `expression.kind()` and `statement.kind()` return a
+//! borrowing enum to match on, whose data structs hold further views. Nothing is copied out of the tree, and a literal
+//! is only read from the source once something asks for its value.
-use crate::fast_hash::HashMap;
+use std::marker::PhantomData;
+use std::sync::Arc;
+use ak::Utf16String;
+
+use crate::parser::FunctionRow;
+use crate::parser::OuterResolutions;
+use crate::parser::ScriptData;
+use crate::parser::columns::Ast;
+use crate::parser::columns::NONE;
+use crate::parser::columns::function_flag;
+use crate::parser::columns::tag;
+use crate::parser::literals;
+use crate::parser::literals::EscapeMode;
+use crate::parser::token::N_PROTO;
+use crate::parser::token::T;
use crate::u32_from_usize;
+use crate::utf16::Utf16StringBuilder;
+use crate::utf16::Utf16View;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Position {
+ pub line: u32,
+ pub column: u32,
+ pub offset: u32,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct SourceRange {
+ pub start: Position,
+ pub end: Position,
+}
// =============================================================================
-// AST arena (contiguous storage for identifiers, scopes, and interned strings)
+// Operator enums — values are ABI-compatible for FFI
// =============================================================================
-//
-// Bulk allocation replaces per-node `Rc::new` calls. AST nodes hold opaque
-// `Copy` indexes into the arena's `Vec`s; the actual data lives contiguously
-// for cache-friendly traversal during scope analysis and codegen. After parse
-// the arena is logically frozen and can be shared across threads via
-// `Arc<AstArena>` without atomic refcount churn on individual nodes.
-
-/// Opaque handle into `IdentifierArena`. `Copy` so AST nodes can hold one
-/// without cloning anything.
-#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
-pub struct IdentifierId(u32);
-/// Opaque handle into `ScopeArena`.
-#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
-pub struct ScopeId(u32);
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum BinaryOp {
+ Addition = 0,
+ Subtraction = 1,
+ Multiplication = 2,
+ Division = 3,
+ Modulo = 4,
+ Exponentiation = 5,
+ StrictlyEquals = 6,
+ StrictlyInequals = 7,
+ LooselyEquals = 8,
+ LooselyInequals = 9,
+ GreaterThan = 10,
+ GreaterThanEquals = 11,
+ LessThan = 12,
+ LessThanEquals = 13,
+ BitwiseAnd = 14,
+ BitwiseOr = 15,
+ BitwiseXor = 16,
+ LeftShift = 17,
+ RightShift = 18,
+ UnsignedRightShift = 19,
+ In = 20,
+ InstanceOf = 21,
+}
-/// Opaque handle into `StringInterner`. Equal `StringId`s mean equal strings,
-/// so name comparisons are a single `u32` compare instead of slice equality.
-#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
-pub struct StringId(u32);
+#[derive(Clone, Copy, Debug)]
+#[repr(u8)]
+pub enum LogicalOp {
+ And = 0,
+ Or = 1,
+ NullishCoalescing = 2,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum UnaryOp {
+ BitwiseNot = 0,
+ Not = 1,
+ Plus = 2,
+ Minus = 3,
+ Typeof = 4,
+ Void = 5,
+ Delete = 6,
+}
+
+#[derive(Clone, Copy, Debug)]
+#[repr(u8)]
+pub enum UpdateOp {
+ Increment = 0,
+ Decrement = 1,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum AssignmentOp {
+ Assignment = 0,
+ AdditionAssignment = 1,
+ SubtractionAssignment = 2,
+ MultiplicationAssignment = 3,
+ DivisionAssignment = 4,
+ ModuloAssignment = 5,
+ ExponentiationAssignment = 6,
+ BitwiseAndAssignment = 7,
+ BitwiseOrAssignment = 8,
+ BitwiseXorAssignment = 9,
+ LeftShiftAssignment = 10,
+ RightShiftAssignment = 11,
+ UnsignedRightShiftAssignment = 12,
+ AndAssignment = 13,
+ OrAssignment = 14,
+ NullishAssignment = 15,
+}
+
+// =============================================================================
+// Kind enums
+// =============================================================================
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum DeclarationKind {
+ Var = 1,
+ Let = 2,
+ Const = 3,
+}
-/// Contiguous backing store for `Identifier` nodes.
-#[derive(Debug, Default)]
-pub struct IdentifierArena {
- storage: Vec<Identifier>,
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum FunctionKind {
+ Normal = 0,
+ Generator = 1,
+ Async = 2,
+ AsyncGenerator = 3,
}
-impl IdentifierArena {
- pub fn new() -> Self {
- Self { storage: Vec::new() }
+impl FunctionKind {
+ pub fn from_async_generator(is_async: bool, is_generator: bool) -> Self {
+ match (is_async, is_generator) {
+ (true, true) => Self::AsyncGenerator,
+ (true, false) => Self::Async,
+ (false, true) => Self::Generator,
+ (false, false) => Self::Normal,
+ }
}
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum ProgramType {
+ Script = 0,
+ Module = 1,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub enum MetaPropertyType {
+ NewTarget,
+ ImportMeta,
+}
+
+/// Scope analysis result: how this identifier is resolved.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum LocalType {
+ Argument,
+ Variable,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum ClassMethodKind {
+ Method = 0,
+ Getter = 1,
+ Setter = 2,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum BindingPatternKind {
+ Array,
+ Object,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum ObjectPropertyType {
+ KeyValue = 0,
+ Getter = 1,
+ Setter = 2,
+ Spread = 3,
+ ProtoSetter = 4,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum OptionalChainMode {
+ Optional,
+ NotOptional,
+}
+
+#[derive(Clone, Debug)]
+pub struct ModuleRequest {
+ pub module_specifier: Utf16String,
+ pub attributes: Vec<ImportAttribute>,
+}
+
+#[derive(Clone, Debug)]
+pub struct ImportAttribute {
+ pub key: Utf16String,
+ pub value: Utf16String,
+}
+
+#[derive(Clone, Debug)]
+pub struct ImportEntry {
+ /// `None` means namespace import (`import * as x`).
+ pub import_name: Option<Utf16String>,
+ pub local_name: Utf16String,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum ExportEntryKind {
+ NamedExport = 0,
+ ModuleRequestAll = 1,
+ ModuleRequestAllButDefault = 2,
+ EmptyNamedExport = 3,
+}
- pub fn insert(&mut self, identifier: Identifier) -> IdentifierId {
- let id = IdentifierId(u32_from_usize(self.storage.len()));
- self.storage.push(identifier);
- id
+#[derive(Clone, Debug)]
+pub struct ExportEntry {
+ pub kind: ExportEntryKind,
+ pub export_name: Option<Utf16String>,
+ pub local_or_import_name: Option<Utf16String>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ForInOfKind {
+ ForIn,
+ ForOf,
+ ForAwaitOf,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum LocalVarKind {
+ Var = 0,
+ LetOrConst = 1,
+ Function = 2,
+ ArgumentsObject = 3,
+ CatchClauseParameter = 4,
+ /// A parameter that a binding pattern binds.
+ PatternParameter = 5,
+}
+
+// =============================================================================
+// Names
+// =============================================================================
+
+/// An interned name of a [`SyntaxTree`]. Equal names of a tree have equal ids.
+#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
+pub struct Name(pub(crate) u32);
+
+#[derive(Clone, Copy)]
+struct NameSpan {
+ start: u32,
+ length: u32,
+ is_ascii: bool,
+}
+
+/// The text of every name of a source: one byte per code unit for ASCII names, which is nearly all of them, and UTF-16
+/// for the others, along with the UTF-8 that a parser knows them by.
+#[derive(Default)]
+pub(crate) struct NameTable {
+ spans: Vec<NameSpan>,
+ ascii_text: Vec<u8>,
+ utf16_text: Vec<u16>,
+ utf8_text: Vec<u8>,
+ /// Where the UTF-8 of each non-ASCII name starts and ends, in the order of the names.
+ utf8_spans: Vec<(u32, u32)>,
+}
+
+impl NameTable {
+ pub(crate) fn push(&mut self, text: &[u8]) {
+ let is_ascii = text.is_ascii();
+ let start = if is_ascii {
+ self.ascii_text.len()
+ } else {
+ self.utf16_text.len()
+ };
+ if is_ascii {
+ self.ascii_text.extend_from_slice(text);
+ } else {
+ self.utf16_text.extend(String::from_utf8_lossy(text).encode_utf16());
+ let utf8_start = u32_from_usize(self.utf8_text.len());
+ self.utf8_text.extend_from_slice(text);
+ self.utf8_spans.push((utf8_start, u32_from_usize(self.utf8_text.len())));
+ }
+ let end = if is_ascii {
+ self.ascii_text.len()
+ } else {
+ self.utf16_text.len()
+ };
+ self.spans.push(NameSpan {
+ start: u32_from_usize(start),
+ length: u32_from_usize(end - start),
+ is_ascii,
+ });
}
- pub fn len(&self) -> usize {
- self.storage.len()
+ /// The names as a parser knows them, in the order of their ids.
+ pub(crate) fn parser_names(&self) -> impl ExactSizeIterator<Item = &[u8]> {
+ let mut utf8_spans = self.utf8_spans.iter();
+ self.spans.iter().map(move |span| {
+ if span.is_ascii {
+ &self.ascii_text[span.start as usize..(span.start + span.length) as usize]
+ } else {
+ let &(start, end) = utf8_spans.next().expect("every non-ASCII name has its UTF-8");
+ &self.utf8_text[start as usize..end as usize]
+ }
+ })
}
- pub fn is_empty(&self) -> bool {
- self.storage.is_empty()
+ fn text(&self, name: Name) -> Utf16View<'_> {
+ let span = self.spans[name.0 as usize];
+ let (start, end) = (span.start as usize, (span.start + span.length) as usize);
+ if span.is_ascii {
+ Utf16View::Ascii(&self.ascii_text[start..end])
+ } else {
+ Utf16View::Utf16(&self.utf16_text[start..end])
+ }
}
}
-impl Index<IdentifierId> for IdentifierArena {
- type Output = Identifier;
- fn index(&self, id: IdentifierId) -> &Identifier {
- &self.storage[id.0 as usize]
+// =============================================================================
+// Resolution
+// =============================================================================
+
+/// What scope analysis found out about one identifier, packed into a `u32` of the tree's resolution column. An
+/// identifier that it did not look at has the value zero.
+#[derive(Clone, Copy, Default)]
+pub(crate) struct Resolution(pub(crate) u32);
+
+impl Resolution {
+ const LOCAL_TYPE_MASK: u32 = 0b11;
+ const LOCAL_ARGUMENT: u32 = 1;
+ const LOCAL_VARIABLE: u32 = 2;
+ const DECLARATION_KIND_SHIFT: u32 = 2;
+ const DECLARATION_KIND_MASK: u32 = 0b11 << Self::DECLARATION_KIND_SHIFT;
+ const IS_GLOBAL: u32 = 1 << 4;
+ const IS_INSIDE_SCOPE_WITH_EVAL: u32 = 1 << 5;
+ const IS_HOISTED: u32 = 1 << 6;
+ const IS_DECLARED_FUNCTION: u32 = 1 << 7;
+ const IS_INSIDE_TREE_SCOPE_WITH_EVAL: u32 = 1 << 8;
+ const LOCAL_INDEX_SHIFT: u32 = 9;
+ /// A binding with a higher index stays in its environment.
+ pub(crate) const MAX_LOCAL_INDEX: u32 = u32::MAX >> Self::LOCAL_INDEX_SHIFT;
+
+ pub(crate) fn set_local(&mut self, binding: LocalBinding) {
+ let local_type = match binding.local_type {
+ LocalType::Argument => Self::LOCAL_ARGUMENT,
+ LocalType::Variable => Self::LOCAL_VARIABLE,
+ };
+ self.0 = (self.0 & !Self::LOCAL_TYPE_MASK & ((1 << Self::LOCAL_INDEX_SHIFT) - 1))
+ | local_type
+ | (binding.index << Self::LOCAL_INDEX_SHIFT);
}
-}
-impl IndexMut<IdentifierId> for IdentifierArena {
- fn index_mut(&mut self, id: IdentifierId) -> &mut Identifier {
- &mut self.storage[id.0 as usize]
+ pub(crate) fn set_declaration_kind(&mut self, kind: DeclarationKind) {
+ self.0 = (self.0 & !Self::DECLARATION_KIND_MASK) | ((kind as u32) << Self::DECLARATION_KIND_SHIFT);
}
-}
-/// Contiguous backing store for `ScopeData` nodes.
-#[derive(Debug, Default)]
-pub struct ScopeArena {
- storage: Vec<ScopeData>,
-}
+ pub(crate) fn set_is_global(&mut self) {
+ self.0 |= Self::IS_GLOBAL;
+ }
-impl ScopeArena {
- pub fn new() -> Self {
- Self { storage: Vec::new() }
+ pub(crate) fn set_is_inside_scope_with_eval(&mut self) {
+ self.0 |= Self::IS_INSIDE_SCOPE_WITH_EVAL;
}
- pub fn insert(&mut self, scope: ScopeData) -> ScopeId {
- let id = ScopeId(u32_from_usize(self.storage.len()));
- self.storage.push(scope);
- id
+ pub(crate) fn is_inside_scope_with_eval(self) -> bool {
+ self.0 & Self::IS_INSIDE_SCOPE_WITH_EVAL != 0
}
- pub fn len(&self) -> usize {
- self.storage.len()
+ /// Whether a scope with an eval around the identifier is one of the tree being resolved.
+ pub(crate) fn set_is_inside_tree_scope_with_eval(&mut self) {
+ self.0 |= Self::IS_INSIDE_TREE_SCOPE_WITH_EVAL;
}
- pub fn is_empty(&self) -> bool {
- self.storage.is_empty()
+ pub(crate) fn is_inside_tree_scope_with_eval(self) -> bool {
+ self.0 & Self::IS_INSIDE_TREE_SCOPE_WITH_EVAL != 0
}
-}
-impl Index<ScopeId> for ScopeArena {
- type Output = ScopeData;
- fn index(&self, id: ScopeId) -> &ScopeData {
- &self.storage[id.0 as usize]
+ pub(crate) fn clear_is_global(&mut self) {
+ self.0 &= !Self::IS_GLOBAL;
}
-}
-impl IndexMut<ScopeId> for ScopeArena {
- fn index_mut(&mut self, id: ScopeId) -> &mut ScopeData {
- &mut self.storage[id.0 as usize]
+ pub(crate) fn set_is_hoisted(&mut self) {
+ self.0 |= Self::IS_HOISTED;
}
-}
-/// Deduplicating string table. Repeated identifier names from the source
-/// (`length`, `i`, `this`, ...) all map to the same `StringId`, so the
-/// per-identifier name no longer allocates after the first occurrence.
-#[derive(Debug, Default)]
-pub struct StringInterner {
- storage: Vec<Utf16String>,
- lookup: HashMap<Utf16String, StringId>,
-}
+ pub(crate) fn is_hoisted(self) -> bool {
+ self.0 & Self::IS_HOISTED != 0
+ }
-impl StringInterner {
- pub fn new() -> Self {
- Self {
- storage: Vec::new(),
- lookup: HashMap::default(),
- }
+ /// Marks the resolution of a function node as being that of the name of its declaration.
+ pub(crate) fn set_is_declared_function(&mut self) {
+ self.0 |= Self::IS_DECLARED_FUNCTION;
}
- pub fn intern(&mut self, value: &[u16]) -> StringId {
- if let Some(&id) = self.lookup.get(value) {
- return id;
- }
- let id = StringId(u32_from_usize(self.storage.len()));
- let owned = Utf16String::from(value);
- self.storage.push(owned.clone());
- self.lookup.insert(owned, id);
- id
+ pub(crate) fn is_declared_function(self) -> bool {
+ self.0 & Self::IS_DECLARED_FUNCTION != 0
}
- pub fn intern_owned(&mut self, value: Utf16String) -> StringId {
- if let Some(&id) = self.lookup.get(value.as_slice()) {
- return id;
+ pub(crate) fn local_type(self) -> Option<LocalType> {
+ match self.0 & Self::LOCAL_TYPE_MASK {
+ Self::LOCAL_ARGUMENT => Some(LocalType::Argument),
+ Self::LOCAL_VARIABLE => Some(LocalType::Variable),
+ _ => None,
}
- let id = StringId(u32_from_usize(self.storage.len()));
- self.storage.push(value.clone());
- self.lookup.insert(value, id);
- id
}
- pub fn len(&self) -> usize {
- self.storage.len()
+ pub(crate) fn local_index(self) -> u32 {
+ self.0 >> Self::LOCAL_INDEX_SHIFT
+ }
+
+ pub(crate) fn declaration_kind(self) -> Option<DeclarationKind> {
+ match (self.0 & Self::DECLARATION_KIND_MASK) >> Self::DECLARATION_KIND_SHIFT {
+ 1 => Some(DeclarationKind::Var),
+ 2 => Some(DeclarationKind::Let),
+ 3 => Some(DeclarationKind::Const),
+ _ => None,
+ }
}
- pub fn is_empty(&self) -> bool {
- self.storage.is_empty()
+ pub(crate) fn is_global(self) -> bool {
+ self.0 & Self::IS_GLOBAL != 0
}
}
-impl Index<StringId> for StringInterner {
- type Output = Utf16String;
- fn index(&self, id: StringId) -> &Utf16String {
- &self.storage[id.0 as usize]
- }
+/// A local that scope analysis gave a function, a static block or a program.
+#[derive(Clone, Copy)]
+pub struct LocalVariable {
+ pub name: Name,
+ pub kind: LocalVarKind,
+ pub is_mutable: bool,
+ /// Where the block that declares it starts and ends, if a block does.
+ pub(crate) scope_offsets: Option<(u32, u32)>,
+ /// How many loops of its function the scope that declares it is in the body of, which is how often that scope can
+ /// start again.
+ pub(crate) enclosing_loops: u32,
}
-/// Bundles the three arenas. Owned by the parser during parsing, then handed
-/// to `ParsedProgram`/`CompiledProgram`. Since every contained type is plain
-/// data (no `Cell`/`RefCell`/`Rc`) once the parser is done, this is naturally
-/// `Send + Sync` and can be wrapped in `Arc` for concurrent codegen.
-#[derive(Debug, Default)]
-pub struct AstArena {
- pub identifiers: IdentifierArena,
- pub scopes: ScopeArena,
- pub strings: StringInterner,
+/// A resolved local binding: the operand type and index assigned by scope analysis.
+#[derive(Clone, Copy, Debug)]
+pub struct LocalBinding {
+ pub local_type: LocalType,
+ pub index: u32,
}
-impl AstArena {
- pub fn new() -> Self {
- Self::default()
- }
+/// A `var` binding that needs initialization during function entry.
+#[derive(Clone, Copy)]
+pub struct VarToInit {
+ pub name: Name,
+ pub is_parameter: bool,
+ pub is_function_name: bool,
+ /// If the scope analysis optimized this var to a local, stores the binding info.
+ pub local: Option<LocalBinding>,
+}
+
+/// A function declaration that needs hoisting: its index among the children of the scope.
+#[derive(Clone, Copy)]
+pub struct FunctionToInit {
+ pub child_index: u32,
+}
+
+/// A range of one of the columns of scope analysis results.
+#[derive(Clone, Copy, Default)]
+pub(crate) struct ColumnRange {
+ pub(crate) start: u32,
+ pub(crate) end: u32,
+}
- pub fn name_of(&self, id: IdentifierId) -> &Utf16String {
- &self.strings[self.identifiers[id].name]
+impl ColumnRange {
+ pub(crate) fn of<T>(self, column: &[T]) -> &[T] {
+ &column[self.start as usize..self.end as usize]
}
+}
- pub fn name_slice(&self, id: IdentifierId) -> &[u16] {
- self.strings[self.identifiers[id].name].as_slice()
+/// What scope analysis found out about a function, a static block or a program.
+#[derive(Clone, Copy, Default)]
+pub(crate) struct ScopeRow {
+ pub(crate) local_variables: ColumnRange,
+ pub(crate) vars_to_initialize: ColumnRange,
+ pub(crate) functions_to_initialize: ColumnRange,
+ pub(crate) annexb_function_names: ColumnRange,
+ pub(crate) non_local_var_count: u32,
+ pub(crate) non_local_var_count_for_parameter_expressions: u32,
+ pub(crate) has_function_scope_data: bool,
+ pub(crate) has_function_named_arguments: bool,
+ pub(crate) has_argument_parameter: bool,
+ pub(crate) has_lexically_declared_arguments: bool,
+ pub(crate) uses_this: bool,
+ pub(crate) uses_this_from_environment: bool,
+ pub(crate) contains_direct_call_to_eval: bool,
+ pub(crate) contains_access_to_arguments_object: bool,
+ /// Whether the code of the scope, which is everything but what its declaration instantiation does, can change the
+ /// running environment. The code of nested functions has its own.
+ pub(crate) creates_environment: bool,
+}
+
+/// The results of scope analysis, which are the same for the whole life of a tree.
+#[derive(Default)]
+pub(crate) struct ScopeTable {
+ /// One per function of the function index, then one per static block, then the program's.
+ pub(crate) rows: Vec<ScopeRow>,
+ pub(crate) local_variables: Vec<LocalVariable>,
+ pub(crate) vars_to_initialize: Vec<VarToInit>,
+ pub(crate) functions_to_initialize: Vec<FunctionToInit>,
+ pub(crate) annexb_function_names: Vec<Name>,
+}
+
+impl ScopeTable {
+ pub(crate) fn clear(&mut self) {
+ self.rows.clear();
+ self.local_variables.clear();
+ self.vars_to_initialize.clear();
+ self.functions_to_initialize.clear();
+ self.annexb_function_names.clear();
}
}
// =============================================================================
-// Function table (side table for FunctionData)
+// The tree
// =============================================================================
-/// Opaque handle into the `FunctionTable`. Copy + Clone so AST nodes can
-/// freely duplicate it without cloning the underlying `FunctionData`.
-#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
-pub struct FunctionId(u32);
+/// What a compile job works from: the tree of the code it compiles, and the results of scope analysis on that code. The
+/// tree of a program holds its top-level code and the functions it is likely to call right away, and the tree of a
+/// function holds that function, in both cases with nothing but a function node for every other function nested in it.
+pub struct SyntaxTree {
+ /// What stays of the source once the tree is gone.
+ pub(crate) script: Arc<ScriptData>,
+ pub(crate) ast: Ast,
+ pub(crate) root: u32,
+ pub(crate) first_token_start: u32,
+ pub(crate) is_strict_mode: bool,
+ pub(crate) has_top_level_await: bool,
+ pub(crate) eval_referenced_private_names: Vec<Name>,
+ /// The resolution of the identifier at each node, if there is one.
+ pub(crate) resolutions: Vec<Resolution>,
+ pub(crate) scopes: ScopeTable,
+ /// The row of the program in `scopes`.
+ pub(crate) program_scope_row: u32,
+ /// The row in `scopes` of each function node of the tree whose code the tree holds, sorted by node.
+ pub(crate) function_scope_rows: Vec<(u32, u32)>,
+ /// What scope analysis found out for the functions that the code of the tree goes on to compile.
+ pub(crate) outer_resolutions: Option<Arc<OuterResolutions>>,
+}
+
+impl SyntaxTree {
+ fn tag(&self, node: u32) -> u8 {
+ self.ast.tag[node as usize]
+ }
-/// Flat side table that owns all `FunctionData` produced during parsing.
-///
-/// The parser inserts `FunctionData` via `insert()` and receives a
-/// `FunctionId`. Later consumers (ast_dump, scope collector, codegen)
-/// either borrow via `get()` or take ownership via `take()`.
-///
-/// `take()` replaces the slot with `None` so each `FunctionData` is
-/// moved out exactly once (during codegen / GDI). This eliminates the
-/// deep clone that was previously required in `create_shared_function_data`.
-pub struct FunctionTable {
- functions: HashMap<FunctionId, Box<FunctionData>>,
- next_id: u32,
-}
+ pub(crate) fn a(&self, node: u32) -> u32 {
+ self.ast.a[node as usize]
+ }
-impl Clone for FunctionTable {
- fn clone(&self) -> Self {
- Self {
- functions: self.functions.iter().map(|(id, data)| (*id, data.clone())).collect(),
- next_id: self.next_id,
- }
+ pub(crate) fn b(&self, node: u32) -> u32 {
+ self.ast.b[node as usize]
}
-}
-impl Default for FunctionTable {
- fn default() -> Self {
- Self::new()
+ fn pos(&self, node: u32) -> u32 {
+ self.ast.pos[node as usize]
}
-}
-impl FunctionTable {
- pub fn new() -> Self {
- Self {
- functions: HashMap::default(),
- next_id: 0,
+ fn extra(&self, index: u32) -> u32 {
+ self.ast.extra[index as usize]
+ }
+
+ fn list(&self, start: u32) -> &[u32] {
+ let start = start as usize;
+ let count = self.ast.extra[start] as usize;
+ &self.ast.extra[start + 1..start + 1 + count]
+ }
+
+ /// Where the code after a block starts, given the list of the block's statements.
+ /// Where the block statement at `node` ends.
+ pub(crate) fn end_of_block(&self, node: u32) -> u32 {
+ self.block_end(self.a(node))
+ }
+
+ fn block_end(&self, list: u32) -> u32 {
+ self.extra(list + 1 + self.extra(list))
+ }
+
+ fn range(&self, offset: u32) -> SourceRange {
+ let position = self.script.positions.lines.position(offset);
+ SourceRange {
+ start: position,
+ end: position,
}
}
- /// Insert a `FunctionData`, returning a `FunctionId` handle.
- pub fn insert(&mut self, data: FunctionData) -> FunctionId {
- let id = FunctionId(self.next_id);
- self.next_id += 1;
- self.functions.insert(id, Box::new(data));
- id
+ pub(crate) fn range_between(&self, start: u32, end: u32) -> SourceRange {
+ SourceRange {
+ start: self.script.positions.lines.position(start),
+ end: self.script.positions.lines.position(end),
+ }
}
- /// Borrow the data (for read-only access like ast_dump).
- ///
- /// # Panics
- /// Panics if the slot was already taken.
- pub fn get(&self, id: FunctionId) -> &FunctionData {
- self.functions.get(&id).expect("FunctionTable::get: slot already taken")
+ fn source_text(&self) -> Utf16View<'_> {
+ Utf16View::of_string(&self.script.positions.source)
}
- /// Take ownership of the data (for codegen / GDI).
- ///
- /// # Panics
- /// Panics if the slot was already taken.
- pub fn take(&mut self, id: FunctionId) -> Box<FunctionData> {
- self.functions
- .remove(&id)
- .expect("FunctionTable::take: slot already taken")
+ pub(crate) fn source_units(&self, start: u32, end: u32) -> Utf16View<'_> {
+ self.source_text()
+ .substring_view(start as usize, (end - start) as usize)
}
- /// Take ownership if the slot is still present; returns None if already taken.
- fn try_take(&mut self, id: FunctionId) -> Option<Box<FunctionData>> {
- self.functions.remove(&id)
+ pub fn name_text(&self, name: Name) -> Utf16View<'_> {
+ self.script.names.text(name)
}
- /// Insert a `Box<FunctionData>` at a specific id.
- fn insert_at(&mut self, id: FunctionId, data: Box<FunctionData>) {
- self.functions.insert(id, data);
+ fn resolution(&self, node: u32) -> Resolution {
+ self.resolutions[node as usize]
}
- /// Extract the nested function subtree needed to compile `data` later.
- ///
- /// Parser-created functions carry an explicit child list, so this is
- /// normally proportional to the number of nested functions instead of the
- /// size of the function body.
- pub fn extract_reachable(&mut self, data: &FunctionData, scopes: &ScopeArena) -> FunctionTable {
- let mut subtable = FunctionTable::new();
- if let Some(nested_function_ids) = &data.nested_function_ids {
- for id in nested_function_ids {
- self.transfer(*id, &mut subtable, scopes);
- }
- } else {
- // Synthetic function wrappers created during codegen (for example
- // class field initializers) do not come from the parser's function
- // context stack, so keep the structural scan for those rare cases.
- for param in &data.parameters {
- if let Some(ref default) = param.default_value {
- self.collect_from_expression(default, &mut subtable, scopes);
- }
- if let FunctionParameterBinding::BindingPattern(ref pat) = param.binding {
- self.collect_from_pattern(pat, &mut subtable, scopes);
- }
- }
- self.collect_from_statement(&data.body, &mut subtable, scopes);
- }
- subtable
+ fn identifier(&self, name: Name, offset: u32, node: u32) -> Identifier<'_> {
+ Identifier::new(self, name, offset, self.resolution(node))
}
- fn transfer(&mut self, id: FunctionId, result: &mut FunctionTable, scopes: &ScopeArena) {
- if let Some(data) = self.try_take(id) {
- if let Some(nested_function_ids) = &data.nested_function_ids {
- for id in nested_function_ids {
- self.transfer(*id, result, scopes);
- }
- } else {
- for param in &data.parameters {
- if let Some(ref default) = param.default_value {
- self.collect_from_expression(default, result, scopes);
- }
- if let FunctionParameterBinding::BindingPattern(ref pat) = param.binding {
- self.collect_from_pattern(pat, result, scopes);
- }
- }
- self.collect_from_statement(&data.body, result, scopes);
- }
- result.insert_at(id, data);
- }
+ /// An identifier that scope analysis does not look at, such as a property name.
+ fn plain_identifier(&self, name: Name, offset: u32) -> Identifier<'_> {
+ Identifier::new(self, name, offset, Resolution::default())
}
- fn collect_from_statement(&mut self, stmt: &Statement, result: &mut FunctionTable, scopes: &ScopeArena) {
- match &stmt.inner {
- StatementKind::FunctionDeclaration(data) => {
- self.transfer(data.function_id, result, scopes);
- }
- StatementKind::Expression(expr) => self.collect_from_expression(expr, result, scopes),
- StatementKind::Block(scope) | StatementKind::FunctionBody { scope, .. } => {
- for child in &scopes[*scope].children {
- self.collect_from_statement(child, result, scopes);
- }
- }
- StatementKind::Program(data) => {
- for child in &scopes[data.scope].children {
- self.collect_from_statement(child, result, scopes);
- }
- }
- StatementKind::If(data) => {
- self.collect_from_expression(&data.test, result, scopes);
- self.collect_from_statement(&data.consequent, result, scopes);
- if let Some(alt) = &data.alternate {
- self.collect_from_statement(alt, result, scopes);
- }
- }
- StatementKind::While(data) => {
- self.collect_from_expression(&data.test, result, scopes);
- self.collect_from_statement(&data.body, result, scopes);
- }
- StatementKind::DoWhile(data) => {
- self.collect_from_statement(&data.body, result, scopes);
- self.collect_from_expression(&data.test, result, scopes);
- }
- StatementKind::For(data) => {
- if let Some(init) = &data.init {
- match init {
- ForInit::Expression(expr) => self.collect_from_expression(expr, result, scopes),
- ForInit::Declaration(decl) => self.collect_from_statement(decl, result, scopes),
- }
- }
- if let Some(test) = &data.test {
- self.collect_from_expression(test, result, scopes);
- }
- if let Some(update) = &data.update {
- self.collect_from_expression(update, result, scopes);
- }
- self.collect_from_statement(&data.body, result, scopes);
- }
- StatementKind::ForInOf(data) => {
- match &data.lhs {
- ForInOfLhs::Declaration(decl) => self.collect_from_statement(decl, result, scopes),
- ForInOfLhs::Expression(expr) => self.collect_from_expression(expr, result, scopes),
- ForInOfLhs::Pattern(pattern) => self.collect_from_pattern(pattern, result, scopes),
- }
- self.collect_from_expression(&data.rhs, result, scopes);
- self.collect_from_statement(&data.body, result, scopes);
- }
- StatementKind::Switch(data) => {
- self.collect_from_expression(&data.discriminant, result, scopes);
- for case in &data.cases {
- if let Some(ref test) = case.test {
- self.collect_from_expression(test, result, scopes);
- }
- for child in &scopes[case.scope].children {
- self.collect_from_statement(child, result, scopes);
- }
- }
- }
- StatementKind::With(data) => {
- self.collect_from_expression(&data.object, result, scopes);
- self.collect_from_statement(&data.body, result, scopes);
- }
- StatementKind::Labelled(data) => {
- self.collect_from_statement(&data.item, result, scopes);
- }
- StatementKind::Return(arg) => {
- if let Some(expr) = arg {
- self.collect_from_expression(expr, result, scopes);
- }
- }
- StatementKind::Throw(expr) => {
- self.collect_from_expression(expr, result, scopes);
- }
- StatementKind::Try(data) => {
- self.collect_from_statement(&data.block, result, scopes);
- if let Some(ref handler) = data.handler {
- if let Some(CatchBinding::BindingPattern(ref pat)) = handler.parameter {
- self.collect_from_pattern(pat, result, scopes);
- }
- self.collect_from_statement(&handler.body, result, scopes);
- }
- if let Some(ref finalizer) = data.finalizer {
- self.collect_from_statement(finalizer, result, scopes);
- }
- }
- StatementKind::VariableDeclaration(data) => {
- for decl in &data.declarations {
- self.collect_from_target(&decl.target, result, scopes);
- if let Some(ref init) = decl.init {
- self.collect_from_expression(init, result, scopes);
- }
- }
- }
- StatementKind::UsingDeclaration(declarations) => {
- for decl in &declarations.declarations {
- self.collect_from_target(&decl.target, result, scopes);
- if let Some(ref init) = decl.init {
- self.collect_from_expression(init, result, scopes);
- }
- }
- }
- StatementKind::ClassDeclaration(class_data) => {
- self.collect_from_class(class_data, result, scopes);
- }
- StatementKind::Export(data) => {
- if let Some(ref stmt) = data.statement {
- self.collect_from_statement(stmt, result, scopes);
- }
- }
- StatementKind::ClassFieldInitializer(data) => {
- self.collect_from_expression(&data.expression, result, scopes);
- }
- StatementKind::Empty
- | StatementKind::Debugger
- | StatementKind::Break { .. }
- | StatementKind::Continue { .. }
- | StatementKind::Import(_)
- | StatementKind::Error
- | StatementKind::ErrorDeclaration => {}
- }
+ pub fn program_type(&self) -> ProgramType {
+ self.script.program_type
}
- fn collect_from_expression(&mut self, expr: &Expression, result: &mut FunctionTable, scopes: &ScopeArena) {
- match &expr.inner {
- ExpressionKind::Function(function_id) => {
- self.transfer(*function_id, result, scopes);
- }
- ExpressionKind::Class(class_data) => {
- self.collect_from_class(class_data, result, scopes);
- }
- ExpressionKind::Binary(data) => {
- self.collect_from_expression(&data.lhs, result, scopes);
- self.collect_from_expression(&data.rhs, result, scopes);
- }
- ExpressionKind::Logical(data) => {
- self.collect_from_expression(&data.lhs, result, scopes);
- self.collect_from_expression(&data.rhs, result, scopes);
- }
- ExpressionKind::Unary { operand, .. } => {
- self.collect_from_expression(operand, result, scopes);
- }
- ExpressionKind::Update(data) => {
- self.collect_from_expression(&data.argument, result, scopes);
- }
- ExpressionKind::Assignment(data) => {
- match &data.lhs {
- AssignmentLhs::Expression(expr) => self.collect_from_expression(expr, result, scopes),
- AssignmentLhs::Pattern(pat) => self.collect_from_pattern(pat, result, scopes),
- }
- self.collect_from_expression(&data.rhs, result, scopes);
- }
- ExpressionKind::Conditional(data) => {
- self.collect_from_expression(&data.test, result, scopes);
- self.collect_from_expression(&data.consequent, result, scopes);
- self.collect_from_expression(&data.alternate, result, scopes);
- }
- ExpressionKind::Sequence(exprs) => {
- for expr in exprs.iter() {
- self.collect_from_expression(expr, result, scopes);
- }
- }
- ExpressionKind::Member(data) => {
- self.collect_from_expression(&data.object, result, scopes);
- self.collect_from_expression(&data.property, result, scopes);
- }
- ExpressionKind::OptionalChain(data) => {
- self.collect_from_expression(&data.base, result, scopes);
- for reference in &data.references {
- match reference {
- OptionalChainReference::Call { arguments, .. } => {
- for arg in arguments {
- self.collect_from_expression(&arg.value, result, scopes);
- }
- }
- OptionalChainReference::ComputedReference { expression, .. } => {
- self.collect_from_expression(expression, result, scopes);
- }
- OptionalChainReference::MemberReference { .. }
- | OptionalChainReference::PrivateMemberReference { .. } => {}
- }
- }
- }
- ExpressionKind::Call(data) | ExpressionKind::New(data) => {
- self.collect_from_expression(&data.callee, result, scopes);
- for arg in &data.arguments {
- self.collect_from_expression(&arg.value, result, scopes);
- }
- }
- ExpressionKind::SuperCall(data) => {
- for arg in &data.arguments {
- self.collect_from_expression(&arg.value, result, scopes);
- }
- }
- ExpressionKind::Spread(expr) | ExpressionKind::Await(expr) => {
- self.collect_from_expression(expr, result, scopes);
- }
- ExpressionKind::Array(elements) => {
- for expr in elements.iter().flatten() {
- self.collect_from_expression(expr, result, scopes);
- }
+ /// The range of the block that declares a local, if a block does.
+ pub fn local_variable_scope_range(&self, variable: &LocalVariable) -> Option<SourceRange> {
+ variable
+ .scope_offsets
+ .map(|(start, end)| self.range_between(start, end))
+ }
+
+ pub fn is_strict_mode(&self) -> bool {
+ self.is_strict_mode
+ }
+
+ pub fn has_top_level_await(&self) -> bool {
+ self.has_top_level_await
+ }
+
+ pub fn eval_referenced_private_names(&self) -> Vec<Utf16String> {
+ self.eval_referenced_private_names
+ .iter()
+ .map(|&name| {
+ let mut text = Utf16StringBuilder::new();
+ text.append_ascii("#");
+ text.append(self.name_text(name));
+ text.to_utf16_string()
+ })
+ .collect()
+ }
+
+ /// The statement of the whole program.
+ pub fn program(&self) -> Statement<'_> {
+ Statement::new(self, self.root)
+ }
+
+ fn scope_row(&self, row: u32) -> &ScopeRow {
+ &self.scopes.rows[row as usize]
+ }
+
+ pub(crate) fn function_scope(&self, function: u32) -> &ScopeRow {
+ let index = self
+ .function_scope_rows
+ .binary_search_by_key(&function, |&(node, _)| node)
+ .expect("the tree holds the code of the function");
+ self.scope_row(self.function_scope_rows[index].1)
+ }
+
+ fn string_units(&self, node: u32) -> Utf16View<'_> {
+ self.source_units(self.pos(node) + 1, self.a(node) - 1)
+ }
+
+ fn string_value(&self, node: u32) -> Utf16String {
+ literals::process_escape_sequences_impl(self.string_units(node), EscapeMode::StringLiteral).value
+ }
+
+ fn is_proto_key(&self, key: u32) -> bool {
+ match self.tag(key) {
+ tag::IDENT => self.a(key) == N_PROTO,
+ tag::STR => {
+ self.string_units(key).length_in_code_units() >= 9
+ && self.string_value(key).to_utf16().as_ref() == utf16!("__proto__")
}
- ExpressionKind::Object(properties) => {
- for prop in properties.iter() {
- self.collect_from_expression(&prop.key, result, scopes);
- if let Some(ref val) = prop.value {
- self.collect_from_expression(val, result, scopes);
- }
+ _ => false,
+ }
+ }
+
+ /// The offset of the property name after the `.` or `?.` at `offset`.
+ fn name_after(&self, offset: u32) -> u32 {
+ let source = self.source_text();
+ let at = |index: usize| source.code_unit_at(index);
+ let mut position = offset as usize + if at(offset as usize) == 0x3F { 2 } else { 1 };
+ loop {
+ let code_unit = at(position);
+ if matches!(
+ code_unit,
+ 0x20 | 0x09 | 0x0A | 0x0D | 0x0B | 0x0C | 0xA0 | 0xFEFF | 0x2028 | 0x2029
+ ) || matches!(code_unit, 0x1680 | 0x2000..=0x200A | 0x202F | 0x205F | 0x3000)
+ {
+ position += 1;
+ } else if code_unit == 0x2F && at(position + 1) == 0x2F {
+ while !matches!(at(position), 0x0A | 0x0D | 0x2028 | 0x2029) {
+ position += 1;
}
- }
- ExpressionKind::TemplateLiteral(data) => {
- for expr in &data.expressions {
- self.collect_from_expression(expr, result, scopes);
+ } else if code_unit == 0x2F && at(position + 1) == 0x2A {
+ position += 2;
+ while !(at(position) == 0x2A && at(position + 1) == 0x2F) {
+ position += 1;
}
+ position += 2;
+ } else {
+ return u32_from_usize(position);
}
- ExpressionKind::TaggedTemplateLiteral(data) => {
- self.collect_from_expression(&data.tag, result, scopes);
- self.collect_from_expression(&data.template_literal, result, scopes);
+ }
+ }
+
+ fn private_identifier(&self, name: u32, offset: u32) -> PrivateIdentifier<'_> {
+ PrivateIdentifier {
+ tree: self,
+ name: Name(name),
+ offset,
+ }
+ }
+
+ fn class(&self, node: u32) -> ClassData<'_> {
+ let name = self.a(node);
+ let extra = self.b(node);
+ let super_class = self.extra(extra);
+ let constructor = self.extra(extra + 3);
+ let start = self.pos(node);
+ let elements = self.list(self.extra(extra + 1));
+ let constructor_index = elements.iter().position(|&element| {
+ constructor != 0 && self.tag(element) == tag::METHOD && self.b(element) == constructor
+ });
+ ClassData {
+ name: (name != NONE).then(|| self.identifier(Name(name), start, node)),
+ source_text_start: start,
+ source_text_end: self.extra(extra + 4),
+ constructor: if constructor_index.is_some() {
+ Expression::new(self, constructor)
+ } else {
+ Expression::with_form(self, node, ExpressionForm::DefaultConstructor)
+ },
+ super_class: (super_class != 0).then(|| Expression::new(self, super_class)),
+ elements: ClassElements {
+ tree: self,
+ elements,
+ constructor_index,
+ class_start: start,
+ },
+ }
+ }
+
+ fn module_request(&self, source: u32) -> ModuleRequest {
+ let mut attributes = Vec::new();
+ if self.b(source) != 0 {
+ for pair in self.list(self.b(source)).chunks(2) {
+ attributes.push(ImportAttribute {
+ key: self.name_text(Name(pair[0])).into(),
+ value: self.name_text(Name(pair[1])).into(),
+ });
}
- ExpressionKind::Yield(data) => {
- if let Some(ref expr) = data.argument {
- self.collect_from_expression(expr, result, scopes);
+ }
+ ModuleRequest {
+ module_specifier: self.string_value(source),
+ attributes,
+ }
+ }
+
+ /// The value of a string literal that the tree holds as an interned name.
+ fn specifier_name(&self, node: u32) -> Utf16String {
+ self.name_text(Name(self.a(node))).into()
+ }
+
+ fn pattern_names(&self, node: u32, names: &mut Vec<Utf16String>) {
+ match self.tag(node) {
+ tag::IDENT => names.push(self.name_text(Name(self.a(node))).into()),
+ tag::ARRAY_PATTERN | tag::OBJECT_PATTERN => {
+ for &item in self.list(self.a(node)) {
+ self.pattern_names(item, names);
}
}
- ExpressionKind::ImportCall(data) => {
- self.collect_from_expression(&data.specifier, result, scopes);
- if let Some(ref opts) = data.options {
- self.collect_from_expression(opts, result, scopes);
- }
+ tag::PROPERTY | tag::COMPUTED_PROPERTY | tag::SHORTHAND => self.pattern_names(self.b(node), names),
+ tag::REST | tag::ASSIGN_PATTERN | tag::ASSIGN_BASE => self.pattern_names(self.a(node), names),
+ _ => {}
+ }
+ }
+
+ /// Whether the pattern at `node` has a computed key or an initializer, nested patterns included.
+ pub(crate) fn pattern_contains_expression(&self, node: u32) -> bool {
+ self.list(self.a(node)).iter().any(|&item| {
+ let item_tag = self.tag(item);
+ if item_tag == tag::COMPUTED_PROPERTY {
+ return true;
}
- ExpressionKind::NumericLiteral(_)
- | ExpressionKind::StringLiteral(_)
- | ExpressionKind::BooleanLiteral(_)
- | ExpressionKind::NullLiteral
- | ExpressionKind::BigIntLiteral(_)
- | ExpressionKind::RegExpLiteral(_)
- | ExpressionKind::Identifier(_)
- | ExpressionKind::PrivateIdentifier(_)
- | ExpressionKind::This
- | ExpressionKind::Super
- | ExpressionKind::MetaProperty(_)
- | ExpressionKind::Error => {}
- }
- }
-
- fn collect_from_class(&mut self, class_data: &ClassData, result: &mut FunctionTable, scopes: &ScopeArena) {
- if let Some(ref super_class) = class_data.super_class {
- self.collect_from_expression(super_class, result, scopes);
- }
- if let Some(ref constructor) = class_data.constructor {
- self.collect_from_expression(constructor, result, scopes);
- }
- for element in &class_data.elements {
- match &element.inner {
- ClassElement::Method { key, function, .. } => {
- self.collect_from_expression(key, result, scopes);
- self.collect_from_expression(function, result, scopes);
- }
- ClassElement::Field { key, initializer, .. } => {
- self.collect_from_expression(key, result, scopes);
- if let Some(init) = initializer {
- self.collect_from_expression(init, result, scopes);
- }
- }
- ClassElement::StaticInitializer { body } => {
- self.collect_from_statement(body, result, scopes);
+ let mut value = match item_tag {
+ tag::HOLE => return false,
+ tag::REST => self.a(item),
+ tag::PROPERTY | tag::SHORTHAND => self.b(item),
+ _ => item,
+ };
+ if matches!(self.tag(value), tag::ASSIGN_PATTERN | tag::ASSIGN_BASE) {
+ if self.b(value) != 0 {
+ return true;
}
+ value = self.a(value);
}
+ matches!(self.tag(value), tag::ARRAY_PATTERN | tag::OBJECT_PATTERN)
+ && self.pattern_contains_expression(value)
+ })
+ }
+
+ fn function_kind(&self, function: u32) -> FunctionKind {
+ let flags = self.script.index.flags[self.b(function) as usize];
+ FunctionKind::from_async_generator(flags & function_flag::ASYNC != 0, flags & function_flag::GENERATOR != 0)
+ }
+
+ fn function_declaration(&self, function: u32, name: u32) -> FunctionDeclarationData<'_> {
+ let name = if name == NONE {
+ self.script.default_export_name
+ } else {
+ Name(name)
+ };
+ FunctionDeclarationData {
+ function_id: FunctionId::function(function),
+ name: Some(self.identifier(name, self.pos(function), function)),
+ kind: self.function_kind(function),
+ is_hoisted: self.resolution(function).is_hoisted(),
}
}
- fn collect_from_pattern(&mut self, pattern: &BindingPattern, result: &mut FunctionTable, scopes: &ScopeArena) {
- for entry in &pattern.entries {
- if let Some(BindingEntryName::Expression(expr)) = entry.name.as_ref() {
- self.collect_from_expression(expr, result, scopes);
- }
- if let Some(ref alias) = entry.alias {
- match alias {
- BindingEntryAlias::BindingPattern(sub) => {
- self.collect_from_pattern(sub, result, scopes);
- }
- BindingEntryAlias::MemberExpression(expr) => {
- self.collect_from_expression(expr, result, scopes);
- }
- BindingEntryAlias::Identifier(_) => {}
+ /// What scope analysis found out about the program.
+ pub(crate) fn program_scope(&self) -> &ScopeRow {
+ self.scope_row(self.program_scope_row)
+ }
+
+ /// The row of the function behind `id`.
+ pub fn function_row(&self, id: FunctionId) -> FunctionRow {
+ let (node, extra_of_row) = match id.source {
+ FunctionSource::Function => return FunctionRow(self.b(id.node)),
+ FunctionSource::DefaultConstructor => return FunctionRow(self.extra(self.b(id.node) + 5)),
+ FunctionSource::ClassFieldInitializer => (self.b(id.node), 1),
+ FunctionSource::StaticInitializer { .. } => (id.node, 1),
+ };
+ FunctionRow(self.extra(self.b(node) + extra_of_row))
+ }
+
+ /// The function behind `id`. Only what is known without its tree is known of a function that the tree does not hold
+ /// the code of.
+ pub fn function(&self, id: FunctionId) -> FunctionData<'_> {
+ let node = id.node;
+ match id.source {
+ FunctionSource::Function => {
+ let tree = self.a(node);
+ let row = self.b(node) as usize;
+ let flags = self.script.index.flags[row];
+ let name = self.script.index.name[row];
+ let start = self.pos(node);
+ // NB: The parameters of a function that is not in the tree are not known to its surroundings.
+ let parameters = if tree == 0 { &[] } else { self.list(self.extra(tree)) };
+ let first_position = parameters.first().map_or(0, |&parameter| match self.tag(parameter) {
+ tag::ASSIGN_PATTERN | tag::ASSIGN_BASE => self.pos(self.a(parameter)),
+ _ => self.pos(parameter),
+ });
+ let is_method = flags & function_flag::METHOD != 0;
+ let name = if self.resolution(node).is_declared_function() {
+ let declared_name = self.script.index.name[row];
+ let name = if declared_name == NONE {
+ self.script.default_export_name
+ } else {
+ Name(declared_name)
+ };
+ Some(self.identifier(name, start, node))
+ } else if name != NONE && !is_method {
+ Some(self.plain_identifier(Name(name), start))
+ } else {
+ None
+ };
+ FunctionData {
+ name,
+ source_text_start: self.script.index.start[row],
+ source_text_end: self.script.index.end[row],
+ body: Statement::with_form(self, node, StatementForm::FunctionBody),
+ parameters: FunctionParameters {
+ tree: self,
+ parameters,
+ first_position,
+ rest_of_default_constructor: None,
+ },
+ parameter_count: self.script.index.parameter_count[row],
+ has_simple_parameter_list: flags & function_flag::SIMPLE_PARAMETERS != 0,
+ function_length: i32::try_from(self.script.index.length[row])
+ .expect("a function has a sane number of parameters"),
+ kind: FunctionKind::from_async_generator(
+ flags & function_flag::ASYNC != 0,
+ flags & function_flag::GENERATOR != 0,
+ ),
+ is_strict_mode: flags & function_flag::STRICT != 0,
+ is_arrow_function: flags & function_flag::ARROW != 0,
+ parsing_insights: FunctionParsingInsights {
+ uses_this: flags & function_flag::INSIGHT_USES_THIS != 0,
+ uses_this_from_environment: flags & function_flag::INSIGHT_THIS_FROM_ENVIRONMENT != 0,
+ contains_direct_call_to_eval: flags & function_flag::DIRECT_EVAL != 0,
+ might_need_arguments_object: flags & function_flag::MIGHT_NEED_ARGUMENTS != 0,
+ },
}
}
- if let Some(ref init) = entry.initializer {
- self.collect_from_expression(init, result, scopes);
+ FunctionSource::DefaultConstructor => {
+ let name = self.a(node);
+ let extra = self.b(node);
+ let start = self.pos(node);
+ let has_super_class = self.extra(extra) != 0;
+ self.synthetic_function(
+ (name != NONE).then(|| self.plain_identifier(Name(name), start)),
+ start,
+ self.extra(extra + 4),
+ Statement::with_form(self, node, StatementForm::DefaultConstructorBody),
+ FunctionParameters {
+ tree: self,
+ parameters: &[],
+ first_position: 0,
+ rest_of_default_constructor: has_super_class.then_some(start),
+ },
+ )
}
+ FunctionSource::ClassFieldInitializer => {
+ let initializer = self.b(node);
+ let expression = Expression::new(self, self.a(initializer));
+ self.synthetic_function(
+ None,
+ expression.range().start.offset,
+ self.pos(initializer),
+ Statement::with_form(self, node, StatementForm::ClassFieldInitializer),
+ FunctionParameters::empty(self),
+ )
+ }
+ FunctionSource::StaticInitializer { class_start } => self.synthetic_function(
+ None,
+ class_start,
+ self.block_end(self.a(node)),
+ Statement::with_form(self, node, StatementForm::StaticBlockBody { class_start }),
+ FunctionParameters::empty(self),
+ ),
}
}
- fn collect_from_target(
- &mut self,
- target: &VariableDeclaratorTarget,
- result: &mut FunctionTable,
- scopes: &ScopeArena,
- ) {
- if let VariableDeclaratorTarget::BindingPattern(pat) = target {
- self.collect_from_pattern(pat, result, scopes);
+ /// A function of a class that the code does not spell out, which is strict like everything in a class.
+ fn synthetic_function<'a>(
+ &'a self,
+ name: Option<Identifier<'a>>,
+ source_text_start: u32,
+ source_text_end: u32,
+ body: Statement<'a>,
+ parameters: FunctionParameters<'a>,
+ ) -> FunctionData<'a> {
+ FunctionData {
+ name,
+ source_text_start,
+ source_text_end,
+ body,
+ parameters,
+ parameter_count: u32_from_usize(parameters.len()),
+ has_simple_parameter_list: parameters.rest_of_default_constructor.is_none(),
+ function_length: 0,
+ kind: FunctionKind::Normal,
+ is_strict_mode: true,
+ is_arrow_function: false,
+ parsing_insights: FunctionParsingInsights {
+ uses_this: true,
+ uses_this_from_environment: true,
+ ..FunctionParsingInsights::default()
+ },
}
}
}
-/// Bundles a `FunctionData` with a subtable of all nested functions
-/// reachable from its body. Stored in the runtime's SharedFunctionInstanceData.
-#[derive(Clone)]
-pub struct FunctionPayload {
- pub data: FunctionData,
- pub function_table: FunctionTable,
- /// Shared access to the program-wide identifier/scope/string tables.
- /// Each lazy-compile SFD carries an Arc clone so it can resolve its
- /// identifier IDs without depending on a parent generator.
- pub arena: Arc<AstArena>,
- /// The environment the function closes over, as laid out by the
- /// generators of its enclosing functions.
- pub enclosing_environment_scope: Option<Arc<crate::bytecode::generator::EnclosingEnvironmentScope>>,
-}
-
// =============================================================================
-// Source location
+// Lists
// =============================================================================
-/// A UTF-16 encoded string.
-///
-/// Wraps `Vec<u16>` to provide type safety and distinguish UTF-16 text
-/// from arbitrary `u16` buffers. Access the inner Vec via `.0` when
-/// Vec-specific methods like `push` or `extend` are needed.
-#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Default)]
-pub struct Utf16String(pub Vec<u16>);
-
-impl std::ops::Deref for Utf16String {
- type Target = [u16];
- fn deref(&self) -> &[u16] {
- &self.0
- }
-}
+/// Something that reads as a sequence of views.
+pub trait Sequence: Copy {
+ type Item;
+ fn len(&self) -> usize;
+ fn at(&self, index: usize) -> Self::Item;
-impl std::ops::DerefMut for Utf16String {
- fn deref_mut(&mut self) -> &mut [u16] {
- &mut self.0
+ fn is_empty(&self) -> bool {
+ self.len() == 0
}
-}
-impl From<Vec<u16>> for Utf16String {
- fn from(v: Vec<u16>) -> Self {
- Self(v)
+ fn iter(&self) -> SequenceIterator<Self> {
+ SequenceIterator {
+ sequence: *self,
+ index: 0,
+ end: self.len(),
+ }
}
-}
-impl From<&[u16]> for Utf16String {
- fn from(s: &[u16]) -> Self {
- Self(s.to_vec())
+ fn first(&self) -> Option<Self::Item> {
+ (!self.is_empty()).then(|| self.at(0))
}
-}
-impl std::borrow::Borrow<[u16]> for Utf16String {
- fn borrow(&self) -> &[u16] {
- &self.0
+ fn last(&self) -> Option<Self::Item> {
+ (!self.is_empty()).then(|| self.at(self.len() - 1))
}
}
-impl AsRef<[u16]> for Utf16String {
- fn as_ref(&self) -> &[u16] {
- &self.0
- }
+#[derive(Clone)]
+pub struct SequenceIterator<S> {
+ sequence: S,
+ index: usize,
+ end: usize,
}
-impl PartialEq<[u16]> for Utf16String {
- fn eq(&self, other: &[u16]) -> bool {
- self.0 == other
- }
-}
+impl<S: Sequence> Iterator for SequenceIterator<S> {
+ type Item = S::Item;
-impl PartialEq<&[u16]> for Utf16String {
- fn eq(&self, other: &&[u16]) -> bool {
- self.0.as_slice() == *other
+ fn next(&mut self) -> Option<S::Item> {
+ if self.index == self.end {
+ return None;
+ }
+ self.index += 1;
+ Some(self.sequence.at(self.index - 1))
}
-}
-impl PartialEq<Vec<u16>> for Utf16String {
- fn eq(&self, other: &Vec<u16>) -> bool {
- self.0 == *other
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.end - self.index, Some(self.end - self.index))
}
}
-impl FromIterator<u16> for Utf16String {
- fn from_iter<I: IntoIterator<Item = u16>>(iter: I) -> Self {
- Self(iter.into_iter().collect())
- }
-}
+impl<S: Sequence> ExactSizeIterator for SequenceIterator<S> {}
-impl<'a> IntoIterator for &'a Utf16String {
- type Item = &'a u16;
- type IntoIter = std::slice::Iter<'a, u16>;
- fn into_iter(self) -> Self::IntoIter {
- self.0.iter()
+impl<S: Sequence> DoubleEndedIterator for SequenceIterator<S> {
+ fn next_back(&mut self) -> Option<S::Item> {
+ if self.index == self.end {
+ return None;
+ }
+ self.end -= 1;
+ Some(self.sequence.at(self.end))
}
}
-impl Utf16String {
- pub fn new() -> Self {
- Self(Vec::new())
- }
-
- pub fn as_slice(&self) -> &[u16] {
- &self.0
- }
-}
+/// Lets `for item in &sequence` and `for item in sequence` work.
+macro_rules! impl_sequence_into_iterator {
+ ($($type:ident),+) => {
+ $(
+ impl<'a> IntoIterator for $type<'a> {
+ type Item = <Self as Sequence>::Item;
+ type IntoIter = SequenceIterator<Self>;
+ fn into_iter(self) -> Self::IntoIter {
+ self.iter()
+ }
+ }
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct Position {
- pub line: u32,
- pub column: u32,
- pub offset: u32,
+ impl<'a> IntoIterator for &$type<'a> {
+ type Item = <$type<'a> as Sequence>::Item;
+ type IntoIter = SequenceIterator<$type<'a>>;
+ fn into_iter(self) -> Self::IntoIter {
+ self.iter()
+ }
+ }
+ )+
+ };
}
-#[derive(Clone, Copy, Debug)]
-pub struct SourceRange {
- pub start: Position,
- pub end: Position,
+/// A view that one list item of the tree turns into.
+pub trait ListItem<'a>: Sized {
+ type Context: Copy;
+ fn read(tree: &'a SyntaxTree, node: u32, context: Self::Context) -> Self;
}
-// =============================================================================
-// Node wrapper
-// =============================================================================
-
-/// Every AST node wraps its payload with source location.
-#[derive(Clone, Debug)]
-pub struct Node<T> {
- pub range: SourceRange,
- pub inner: T,
+/// A list of the tree, read as views of type `T`.
+pub struct List<'a, T: ListItem<'a>> {
+ tree: &'a SyntaxTree,
+ items: &'a [u32],
+ context: T::Context,
+ item_type: PhantomData<T>,
}
-pub type Expression = Node<ExpressionKind>;
-
-pub type Statement = Node<StatementKind>;
-
-impl<T> Node<T> {
- pub fn new(range: SourceRange, inner: T) -> Self {
- Self { range, inner }
+impl<'a, T: ListItem<'a>> Clone for List<'a, T> {
+ fn clone(&self) -> Self {
+ *self
}
}
-// =============================================================================
-// Operator enums — values are ABI-compatible for FFI
-// =============================================================================
+impl<'a, T: ListItem<'a>> Copy for List<'a, T> {}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum BinaryOp {
- Addition = 0,
- Subtraction = 1,
- Multiplication = 2,
- Division = 3,
- Modulo = 4,
- Exponentiation = 5,
- StrictlyEquals = 6,
- StrictlyInequals = 7,
- LooselyEquals = 8,
- LooselyInequals = 9,
- GreaterThan = 10,
- GreaterThanEquals = 11,
- LessThan = 12,
- LessThanEquals = 13,
- BitwiseAnd = 14,
- BitwiseOr = 15,
- BitwiseXor = 16,
- LeftShift = 17,
- RightShift = 18,
- UnsignedRightShift = 19,
- In = 20,
- InstanceOf = 21,
-}
+impl<'a, T: ListItem<'a>> List<'a, T> {
+ fn new(tree: &'a SyntaxTree, start: u32, context: T::Context) -> Self {
+ Self::of_items(tree, tree.list(start), context)
+ }
-#[derive(Clone, Copy, Debug)]
-#[repr(u8)]
-pub enum LogicalOp {
- And = 0,
- Or = 1,
- NullishCoalescing = 2,
+ fn of_items(tree: &'a SyntaxTree, items: &'a [u32], context: T::Context) -> Self {
+ Self {
+ tree,
+ items,
+ context,
+ item_type: PhantomData,
+ }
+ }
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum UnaryOp {
- BitwiseNot = 0,
- Not = 1,
- Plus = 2,
- Minus = 3,
- Typeof = 4,
- Void = 5,
- Delete = 6,
-}
+impl<'a, T: ListItem<'a>> Sequence for List<'a, T> {
+ type Item = T;
-#[derive(Clone, Copy, Debug)]
-#[repr(u8)]
-pub enum UpdateOp {
- Increment = 0,
- Decrement = 1,
-}
+ fn len(&self) -> usize {
+ self.items.len()
+ }
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum AssignmentOp {
- Assignment = 0,
- AdditionAssignment = 1,
- SubtractionAssignment = 2,
- MultiplicationAssignment = 3,
- DivisionAssignment = 4,
- ModuloAssignment = 5,
- ExponentiationAssignment = 6,
- BitwiseAndAssignment = 7,
- BitwiseOrAssignment = 8,
- BitwiseXorAssignment = 9,
- LeftShiftAssignment = 10,
- RightShiftAssignment = 11,
- UnsignedRightShiftAssignment = 12,
- AndAssignment = 13,
- OrAssignment = 14,
- NullishAssignment = 15,
+ fn at(&self, index: usize) -> T {
+ T::read(self.tree, self.items[index], self.context)
+ }
}
-// =============================================================================
-// Kind enums
-// =============================================================================
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum DeclarationKind {
- Var = 1,
- Let = 2,
- Const = 3,
+impl<'a, T: ListItem<'a>> IntoIterator for List<'a, T> {
+ type Item = T;
+ type IntoIter = SequenceIterator<Self>;
+ fn into_iter(self) -> Self::IntoIter {
+ self.iter()
+ }
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum FunctionKind {
- Normal = 0,
- Generator = 1,
- Async = 2,
- AsyncGenerator = 3,
+impl<'a, T: ListItem<'a>> IntoIterator for &List<'a, T> {
+ type Item = T;
+ type IntoIter = SequenceIterator<List<'a, T>>;
+ fn into_iter(self) -> Self::IntoIter {
+ self.iter()
+ }
}
-impl FunctionKind {
- pub fn from_async_generator(is_async: bool, is_generator: bool) -> Self {
- match (is_async, is_generator) {
- (true, true) => Self::AsyncGenerator,
- (true, false) => Self::Async,
- (false, true) => Self::Generator,
- (false, false) => Self::Normal,
- }
+impl<'a> ListItem<'a> for Expression<'a> {
+ type Context = ();
+ fn read(tree: &'a SyntaxTree, node: u32, _: ()) -> Self {
+ Expression::new(tree, node)
}
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum ProgramType {
- Script = 0,
- Module = 1,
+impl<'a> ListItem<'a> for Option<Expression<'a>> {
+ type Context = ();
+ fn read(tree: &'a SyntaxTree, node: u32, _: ()) -> Self {
+ (tree.tag(node) != tag::HOLE).then(|| Expression::new(tree, node))
+ }
}
-#[derive(Clone, Copy, Debug)]
-pub enum MetaPropertyType {
- NewTarget,
- ImportMeta,
+impl<'a> ListItem<'a> for Statement<'a> {
+ type Context = ();
+ fn read(tree: &'a SyntaxTree, node: u32, _: ()) -> Self {
+ Statement::new(tree, node)
+ }
}
// =============================================================================
-// Identifier
+// Identifiers
// =============================================================================
-/// Scope analysis result: how this identifier is resolved.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum LocalType {
- Argument,
- Variable,
-}
-
-/// An identifier reference or binding name.
-///
-/// Scope analysis writes the resolution fields via `&mut arena.identifiers[id]`
-/// during analyze(); after that the arena is logically frozen and these
-/// fields are read-only.
-#[derive(Clone, Debug)]
-pub struct Identifier {
- pub range: SourceRange,
- pub name: StringId,
- // Scope analysis results — set by scope collector after parsing.
+/// An identifier reference or binding name, with what scope analysis found out about it.
+#[derive(Clone, Copy)]
+pub struct Identifier<'a> {
+ tree: &'a SyntaxTree,
+ pub name: Name,
+ offset: u32,
pub local_type: Option<LocalType>,
pub local_index: u32,
pub is_global: bool,
@@ -946,39 +1187,61 @@ pub struct Identifier {
pub declaration_kind: Option<DeclarationKind>,
}
-impl Identifier {
- pub fn new(range: SourceRange, name: StringId) -> Self {
+impl<'a> Identifier<'a> {
+ fn new(tree: &'a SyntaxTree, name: Name, offset: u32, resolution: Resolution) -> Self {
Self {
- range,
+ tree,
name,
- local_type: None,
- local_index: 0,
- is_global: false,
- is_inside_scope_with_eval: false,
- declaration_kind: None,
+ offset,
+ local_type: resolution.local_type(),
+ local_index: resolution.local_index(),
+ is_global: resolution.is_global(),
+ is_inside_scope_with_eval: resolution.is_inside_scope_with_eval(),
+ declaration_kind: resolution.declaration_kind(),
}
}
pub fn is_local(&self) -> bool {
self.local_type.is_some()
}
+
+ pub fn text(&self) -> Utf16View<'a> {
+ self.tree.name_text(self.name)
+ }
+
+ pub fn range(&self) -> SourceRange {
+ self.tree.range(self.offset)
+ }
}
-#[derive(Clone, Debug)]
-pub struct PrivateIdentifier {
- pub range: SourceRange,
- pub name: Utf16String,
+#[derive(Clone, Copy)]
+pub struct PrivateIdentifier<'a> {
+ tree: &'a SyntaxTree,
+ name: Name,
+ offset: u32,
+}
+
+impl PrivateIdentifier<'_> {
+ /// The name with its `#`.
+ pub fn name(&self) -> Utf16String {
+ let mut text = Utf16StringBuilder::new();
+ text.append_ascii("#");
+ text.append(self.tree.name_text(self.name));
+ text.to_utf16_string()
+ }
+
+ pub fn range(&self) -> SourceRange {
+ self.tree.range(self.offset)
+ }
}
// =============================================================================
-// Function support types
+// Functions
// =============================================================================
/// Parsing insights collected during function body parsing.
///
-/// The scope collector populates `uses_this`, `uses_this_from_environment`,
-/// and `contains_direct_call_to_eval` during scope analysis.
-/// `might_need_arguments_object` is set by the parser during body parsing.
+/// All of these come out of scope analysis while parsing.
#[derive(Clone, Copy, Debug, Default)]
pub struct FunctionParsingInsights {
pub uses_this: bool,
@@ -987,132 +1250,351 @@ pub struct FunctionParsingInsights {
pub might_need_arguments_object: bool,
}
-#[derive(Clone, Debug)]
-pub struct FunctionParameter {
- pub binding: FunctionParameterBinding,
- pub default_value: Option<Expression>,
- pub is_rest: bool,
+#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
+enum FunctionSource {
+ /// A function that the code spells out, at a function node.
+ Function,
+ /// The constructor of the class node, which does not spell one out.
+ DefaultConstructor,
+ /// The initializer of the field node.
+ ClassFieldInitializer,
+ /// The static block node.
+ StaticInitializer { class_start: u32 },
}
-#[derive(Clone, Debug)]
-pub enum FunctionParameterBinding {
- Identifier(IdentifierId),
- BindingPattern(BindingPattern),
+/// A function of a tree, which stays valid for as long as the tree.
+#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
+pub struct FunctionId {
+ node: u32,
+ source: FunctionSource,
}
-/// Shared data for FunctionDeclaration and FunctionExpression.
-#[derive(Clone, Debug)]
-pub struct FunctionData {
- pub name: Option<IdentifierId>,
+impl FunctionId {
+ pub(crate) fn function(node: u32) -> Self {
+ Self {
+ node,
+ source: FunctionSource::Function,
+ }
+ }
+}
+
+/// Everything about a function, in FunctionDeclaration and FunctionExpression alike.
+#[derive(Clone, Copy)]
+pub struct FunctionData<'a> {
+ pub name: Option<Identifier<'a>>,
pub source_text_start: u32,
pub source_text_end: u32,
- pub body: Box<Statement>,
- pub parameters: Vec<FunctionParameter>,
+ pub body: Statement<'a>,
+ pub parameters: FunctionParameters<'a>,
+ pub parameter_count: u32,
+ pub has_simple_parameter_list: bool,
pub function_length: i32,
pub kind: FunctionKind,
pub is_strict_mode: bool,
pub is_arrow_function: bool,
pub parsing_insights: FunctionParsingInsights,
- /// Parser-created functions know their nested function ids up front, so
- /// lazy-compile payload extraction can move only that subtree instead of
- /// re-walking the full body. `None` is reserved for synthetic function
- /// wrappers built during codegen, where the old structural scan is still
- /// needed to discover nested functions inside the wrapped AST.
- pub nested_function_ids: Option<Vec<FunctionId>>,
+}
+
+#[derive(Clone, Copy)]
+pub struct FunctionParameters<'a> {
+ tree: &'a SyntaxTree,
+ parameters: &'a [u32],
+ /// Where the names of parameters count as being.
+ first_position: u32,
+ /// The class's start, if these are the parameters of the default constructor of a derived class.
+ rest_of_default_constructor: Option<u32>,
+}
+
+impl<'a> FunctionParameters<'a> {
+ fn empty(tree: &'a SyntaxTree) -> Self {
+ Self {
+ tree,
+ parameters: &[],
+ first_position: 0,
+ rest_of_default_constructor: None,
+ }
+ }
+}
+
+impl<'a> Sequence for FunctionParameters<'a> {
+ type Item = FunctionParameter<'a>;
+
+ fn len(&self) -> usize {
+ self.parameters.len() + usize::from(self.rest_of_default_constructor.is_some())
+ }
+
+ fn at(&self, index: usize) -> FunctionParameter<'a> {
+ let tree = self.tree;
+ if let Some(class_start) = self.rest_of_default_constructor {
+ return FunctionParameter {
+ binding: FunctionParameterBinding::Identifier(
+ tree.plain_identifier(tree.script.default_constructor_parameter_name, class_start),
+ ),
+ default_value: None,
+ is_rest: true,
+ };
+ }
+ let parameter = self.parameters[index];
+ let parameter_tag = tree.tag(parameter);
+ let (target, default) = match parameter_tag {
+ tag::REST => (tree.a(parameter), 0),
+ tag::ASSIGN_PATTERN | tag::ASSIGN_BASE => (tree.a(parameter), tree.b(parameter)),
+ _ => (parameter, 0),
+ };
+ let binding = if tree.tag(target) == tag::IDENT {
+ FunctionParameterBinding::Identifier(tree.identifier(Name(tree.a(target)), self.first_position, target))
+ } else {
+ FunctionParameterBinding::BindingPattern(BindingPattern::new(tree, target, PatternMode::Binding))
+ };
+ FunctionParameter {
+ binding,
+ default_value: (default != 0).then(|| Expression::new(tree, default)),
+ is_rest: parameter_tag == tag::REST,
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+pub struct FunctionParameter<'a> {
+ pub binding: FunctionParameterBinding<'a>,
+ pub default_value: Option<Expression<'a>>,
+ pub is_rest: bool,
+}
+
+#[derive(Clone, Copy)]
+pub enum FunctionParameterBinding<'a> {
+ Identifier(Identifier<'a>),
+ BindingPattern(BindingPattern<'a>),
}
// =============================================================================
-// Class support types
+// Classes
// =============================================================================
/// Shared data for ClassDeclaration and ClassExpression.
-#[derive(Clone, Debug)]
-pub struct ClassData {
- pub name: Option<IdentifierId>,
+#[derive(Clone, Copy)]
+pub struct ClassData<'a> {
+ pub name: Option<Identifier<'a>>,
pub source_text_start: u32,
pub source_text_end: u32,
- pub constructor: Option<Box<Expression>>,
- pub super_class: Option<Box<Expression>>,
- pub elements: Vec<Node<ClassElement>>,
+ pub constructor: Expression<'a>,
+ pub super_class: Option<Expression<'a>>,
+ pub elements: ClassElements<'a>,
}
-#[derive(Clone, Debug)]
-pub enum ClassElement {
+/// The elements of a class, other than its constructor.
+#[derive(Clone, Copy)]
+pub struct ClassElements<'a> {
+ tree: &'a SyntaxTree,
+ elements: &'a [u32],
+ constructor_index: Option<usize>,
+ class_start: u32,
+}
+
+impl<'a> Sequence for ClassElements<'a> {
+ type Item = ClassElementNode<'a>;
+
+ fn len(&self) -> usize {
+ self.elements.len() - usize::from(self.constructor_index.is_some())
+ }
+
+ fn at(&self, index: usize) -> ClassElementNode<'a> {
+ let index = match self.constructor_index {
+ Some(constructor_index) if index >= constructor_index => index + 1,
+ _ => index,
+ };
+ ClassElementNode {
+ tree: self.tree,
+ node: self.elements[index],
+ class_start: self.class_start,
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+pub struct ClassElementNode<'a> {
+ tree: &'a SyntaxTree,
+ node: u32,
+ class_start: u32,
+}
+
+impl<'a> ClassElementNode<'a> {
+ pub fn range(&self) -> SourceRange {
+ let tree = self.tree;
+ let inner = self.inner_node().0;
+ if tree.tag(inner) == tag::CLASS_STATIC_BLOCK {
+ tree.range(tree.pos(inner))
+ } else {
+ tree.range(self.class_start)
+ }
+ }
+
+ /// The element without its `static`, and whether it had one.
+ fn inner_node(&self) -> (u32, bool) {
+ let tree = self.tree;
+ if tree.tag(self.node) == tag::STATIC_ELEMENT {
+ (tree.a(self.node), true)
+ } else {
+ (self.node, false)
+ }
+ }
+
+ fn property_key(&self, key: u32, computed: bool) -> Expression<'a> {
+ if !computed && self.tree.tag(key) == tag::IDENT {
+ Expression::with_form(self.tree, key, ExpressionForm::PropertyKeyName)
+ } else {
+ Expression::new(self.tree, key)
+ }
+ }
+
+ pub fn kind(&self) -> ClassElement<'a> {
+ let tree = self.tree;
+ let (inner, is_static) = self.inner_node();
+ let (a, b) = (tree.a(inner), tree.b(inner));
+ let inner_tag = tree.tag(inner);
+ match inner_tag {
+ tag::CLASS_FIELD | tag::COMPUTED_CLASS_FIELD => ClassElement::Field {
+ key: self.property_key(a, inner_tag == tag::COMPUTED_CLASS_FIELD),
+ initializer: (b != 0).then(|| Expression::new(tree, tree.a(b))),
+ initializer_function: FunctionId {
+ node: inner,
+ source: FunctionSource::ClassFieldInitializer,
+ },
+ is_static,
+ },
+ tag::CLASS_STATIC_BLOCK => {
+ let class_start = self.class_start;
+ ClassElement::StaticInitializer {
+ body: Statement::with_form(tree, inner, StatementForm::StaticBlockBody { class_start }),
+ function: FunctionId {
+ node: inner,
+ source: FunctionSource::StaticInitializer { class_start },
+ },
+ }
+ }
+ other => {
+ let kind = match other {
+ tag::GETTER | tag::COMPUTED_GETTER => ClassMethodKind::Getter,
+ tag::SETTER | tag::COMPUTED_SETTER => ClassMethodKind::Setter,
+ _ => ClassMethodKind::Method,
+ };
+ let computed = matches!(
+ other,
+ tag::COMPUTED_METHOD | tag::COMPUTED_GETTER | tag::COMPUTED_SETTER
+ );
+ ClassElement::Method {
+ key: self.property_key(a, computed),
+ function: Expression::new(tree, b),
+ kind,
+ is_static,
+ }
+ }
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+pub enum ClassElement<'a> {
Method {
- key: Box<Expression>,
- function: Box<Expression>,
+ key: Expression<'a>,
+ function: Expression<'a>,
kind: ClassMethodKind,
is_static: bool,
},
Field {
- key: Box<Expression>,
- initializer: Option<Box<Expression>>,
+ key: Expression<'a>,
+ initializer: Option<Expression<'a>>,
+ /// The function that evaluates `initializer`, if there is one.
+ initializer_function: FunctionId,
is_static: bool,
},
StaticInitializer {
- body: Box<Statement>,
+ body: Statement<'a>,
+ function: FunctionId,
},
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum ClassMethodKind {
- Method = 0,
- Getter = 1,
- Setter = 2,
-}
-
// =============================================================================
-// Binding pattern types
+// Binding patterns
// =============================================================================
-#[derive(Clone, Debug)]
-pub struct BindingPattern {
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum PatternMode {
+ /// The pattern of a declaration, a parameter or a catch clause.
+ Binding,
+ /// The target of a destructuring assignment.
+ Assignment,
+}
+
+#[derive(Clone, Copy)]
+pub struct BindingPattern<'a> {
pub kind: BindingPatternKind,
- pub entries: Vec<BindingEntry>,
+ pub entries: List<'a, BindingEntry<'a>>,
}
-impl BindingPattern {
- pub fn contains_expression(&self) -> bool {
- for entry in &self.entries {
- if matches!(entry.name, Some(BindingEntryName::Expression(_))) {
- return true;
- }
- if entry.initializer.is_some() {
- return true;
- }
- if let Some(BindingEntryAlias::BindingPattern(ref nested)) = entry.alias
- && nested.contains_expression()
- {
- return true;
- }
+impl<'a> BindingPattern<'a> {
+ pub(crate) fn new(tree: &'a SyntaxTree, node: u32, mode: PatternMode) -> Self {
+ let is_array = tree.tag(node) == tag::ARRAY_PATTERN;
+ Self {
+ kind: if is_array {
+ BindingPatternKind::Array
+ } else {
+ BindingPatternKind::Object
+ },
+ entries: List::new(tree, tree.a(node), (is_array, mode)),
}
- false
}
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum BindingPatternKind {
- Array,
- Object,
-}
-
-#[derive(Clone, Debug)]
-pub struct BindingEntry {
- pub name: Option<BindingEntryName>,
- pub alias: Option<BindingEntryAlias>,
- pub initializer: Option<Expression>,
+#[derive(Clone, Copy)]
+pub struct BindingEntry<'a> {
+ pub name: Option<BindingEntryName<'a>>,
+ pub alias: Option<BindingEntryAlias<'a>>,
+ pub initializer: Option<Expression<'a>>,
pub is_rest: bool,
}
/// The "name" part of a binding entry.
/// - `None`: elision in array patterns (`[, , x]`)
/// - `Identifier`: object property shorthand (`{ x }`)
+/// - `Key`: property key (`{ x: y }`, `{ "x": y }`)
/// - `Expression`: computed property key (`{ [expression]: x }`)
-#[derive(Clone, Debug)]
-pub enum BindingEntryName {
- Identifier(IdentifierId),
- Expression(Box<Expression>),
+#[derive(Clone, Copy)]
+pub enum BindingEntryName<'a> {
+ Identifier(Identifier<'a>),
+ Key(PropertyKey<'a>),
+ Expression(Expression<'a>),
+}
+
+/// The key of a property in a pattern, which refers to no binding.
+#[derive(Clone, Copy)]
+pub struct PropertyKey<'a> {
+ tree: &'a SyntaxTree,
+ node: u32,
+}
+
+impl PropertyKey<'_> {
+ pub fn text(&self) -> Utf16String {
+ let tree = self.tree;
+ let key = self.node;
+ match tree.tag(key) {
+ tag::IDENT => tree.name_text(Name(tree.a(key))).into(),
+ tag::STR => tree.string_value(key),
+ tag::NUM => crate::host::js_number_to_utf16(literals::parse_numeric_value(
+ tree.source_units(tree.pos(key), tree.a(key)),
+ )),
+ _ => {
+ let literal = tree.source_units(tree.pos(key), tree.a(key)).to_utf8();
+ let value = crate::bytecode::constant_fold::parse_bigint(literal.trim_end_matches('n'))
+ .expect("the lexer only accepts valid BigInts");
+ Utf16String::from_utf8(&value.to_string())
+ }
+ }
+ }
+
+ pub fn range(&self) -> SourceRange {
+ self.tree.range(self.tree.pos(self.node))
+ }
}
/// The "alias" (target) of a binding entry.
@@ -1120,463 +1602,1017 @@ pub enum BindingEntryName {
/// - `Identifier`: simple binding (`{ x: y }`)
/// - `BindingPattern`: nested destructuring (`{ x: { a, b } }`)
/// - `MemberExpression`: assignment target (`{ x: obj.property }`)
-#[derive(Clone, Debug)]
-pub enum BindingEntryAlias {
- Identifier(IdentifierId),
- BindingPattern(Box<BindingPattern>),
- MemberExpression(Box<Expression>),
+#[derive(Clone, Copy)]
+pub enum BindingEntryAlias<'a> {
+ Identifier(Identifier<'a>),
+ BindingPattern(BindingPattern<'a>),
+ MemberExpression(Expression<'a>),
}
-// =============================================================================
-// Variable declaration types
-// =============================================================================
-
-#[derive(Clone, Debug)]
-pub struct VariableDeclarator {
- pub range: SourceRange,
- pub target: VariableDeclaratorTarget,
- pub init: Option<Expression>,
+fn pattern_alias(tree: &SyntaxTree, value: u32, mode: PatternMode) -> BindingEntryAlias<'_> {
+ match tree.tag(value) {
+ tag::ARRAY_PATTERN | tag::OBJECT_PATTERN => {
+ BindingEntryAlias::BindingPattern(BindingPattern::new(tree, value, mode))
+ }
+ tag::IDENT if mode == PatternMode::Binding => {
+ BindingEntryAlias::Identifier(tree.identifier(Name(tree.a(value)), tree.pos(value), value))
+ }
+ _ => {
+ let expression = Expression::new(tree, value);
+ match expression.kind() {
+ ExpressionKind::Identifier(identifier) => BindingEntryAlias::Identifier(identifier),
+ _ => BindingEntryAlias::MemberExpression(expression),
+ }
+ }
+ }
}
-#[derive(Clone, Debug)]
-pub enum VariableDeclaratorTarget {
- Identifier(IdentifierId),
- BindingPattern(BindingPattern),
+impl<'a> ListItem<'a> for BindingEntry<'a> {
+ type Context = (bool, PatternMode);
+
+ fn read(tree: &'a SyntaxTree, item: u32, (is_array, mode): Self::Context) -> Self {
+ let item_tag = tree.tag(item);
+ if item_tag == tag::HOLE {
+ return BindingEntry {
+ name: None,
+ alias: None,
+ initializer: None,
+ is_rest: false,
+ };
+ }
+ let is_rest = item_tag == tag::REST;
+ let mut value = match item_tag {
+ tag::REST => tree.a(item),
+ tag::PROPERTY | tag::COMPUTED_PROPERTY | tag::SHORTHAND => tree.b(item),
+ _ => item,
+ };
+ let mut initializer = 0;
+ if matches!(tree.tag(value), tag::ASSIGN_PATTERN | tag::ASSIGN_BASE) {
+ initializer = tree.b(value);
+ value = tree.a(value);
+ }
+
+ let mut name = None;
+ let mut alias = None;
+ if is_array {
+ alias = Some(pattern_alias(tree, value, mode));
+ } else if item_tag == tag::SHORTHAND {
+ name = Some(BindingEntryName::Identifier(tree.identifier(
+ Name(tree.a(item)),
+ tree.pos(value),
+ item,
+ )));
+ } else if is_rest {
+ if mode == PatternMode::Binding {
+ name = Some(BindingEntryName::Identifier(tree.identifier(
+ Name(tree.a(value)),
+ tree.pos(value),
+ value,
+ )));
+ } else {
+ let expression = Expression::new(tree, value);
+ match expression.kind() {
+ ExpressionKind::Identifier(identifier) => name = Some(BindingEntryName::Identifier(identifier)),
+ _ => alias = Some(BindingEntryAlias::MemberExpression(expression)),
+ }
+ }
+ } else {
+ let key = tree.a(item);
+ name = Some(if item_tag == tag::COMPUTED_PROPERTY {
+ BindingEntryName::Expression(Expression::new(tree, key))
+ } else {
+ BindingEntryName::Key(PropertyKey { tree, node: key })
+ });
+ alias = Some(pattern_alias(tree, value, mode));
+ }
+ BindingEntry {
+ name,
+ alias,
+ initializer: (initializer != 0).then(|| Expression::new(tree, initializer)),
+ is_rest,
+ }
+ }
}
// =============================================================================
-// Object literal types
+// Object literals
// =============================================================================
-#[derive(Clone, Debug)]
-pub struct ObjectProperty {
- pub range: SourceRange,
+#[derive(Clone, Copy)]
+pub struct ObjectProperty<'a> {
+ tree: &'a SyntaxTree,
+ offset: u32,
pub property_type: ObjectPropertyType,
- pub key: Box<Expression>,
- pub value: Option<Box<Expression>>,
+ pub key: Expression<'a>,
+ pub value: Option<Expression<'a>>,
pub is_method: bool,
pub is_computed: bool,
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum ObjectPropertyType {
- KeyValue = 0,
- Getter = 1,
- Setter = 2,
- Spread = 3,
- ProtoSetter = 4,
+impl ObjectProperty<'_> {
+ pub fn range(&self) -> SourceRange {
+ self.tree.range(self.offset)
+ }
+}
+
+impl<'a> ListItem<'a> for ObjectProperty<'a> {
+ /// Where the object starts.
+ type Context = u32;
+
+ fn read(tree: &'a SyntaxTree, property: u32, object_start: u32) -> Self {
+ let property_tag = tree.tag(property);
+ let (a, b) = (tree.a(property), tree.b(property));
+ match property_tag {
+ tag::SPREAD => ObjectProperty {
+ tree,
+ offset: tree.pos(property),
+ property_type: ObjectPropertyType::Spread,
+ key: Expression::new(tree, a),
+ value: None,
+ is_method: false,
+ is_computed: false,
+ },
+ tag::SHORTHAND => ObjectProperty {
+ tree,
+ offset: object_start,
+ property_type: ObjectPropertyType::KeyValue,
+ key: Expression::with_form(tree, property, ExpressionForm::ShorthandKey),
+ value: Some(Expression::with_form(
+ tree,
+ property,
+ ExpressionForm::ShorthandValue { object_start },
+ )),
+ is_method: false,
+ is_computed: false,
+ },
+ _ => {
+ let is_computed = matches!(
+ property_tag,
+ tag::COMPUTED_PROPERTY | tag::COMPUTED_METHOD | tag::COMPUTED_GETTER | tag::COMPUTED_SETTER
+ );
+ let is_method = !matches!(property_tag, tag::PROPERTY | tag::COMPUTED_PROPERTY);
+ let property_type = match property_tag {
+ tag::GETTER | tag::COMPUTED_GETTER => ObjectPropertyType::Getter,
+ tag::SETTER | tag::COMPUTED_SETTER => ObjectPropertyType::Setter,
+ tag::PROPERTY if tree.is_proto_key(a) => ObjectPropertyType::ProtoSetter,
+ _ => ObjectPropertyType::KeyValue,
+ };
+ let key = if !is_computed && tree.tag(a) == tag::IDENT {
+ Expression::with_form(tree, a, ExpressionForm::PropertyKeyName)
+ } else {
+ Expression::new(tree, a)
+ };
+ ObjectProperty {
+ tree,
+ offset: object_start,
+ property_type,
+ key,
+ value: Some(Expression::new(tree, b)),
+ is_method,
+ is_computed,
+ }
+ }
+ }
+ }
}
// =============================================================================
-// Call expression types
+// Calls
// =============================================================================
-#[derive(Clone, Debug)]
-pub struct CallArgument {
- pub value: Expression,
+#[derive(Clone, Copy)]
+pub struct CallArgument<'a> {
+ pub value: Expression<'a>,
pub is_spread: bool,
}
-#[derive(Clone, Debug)]
-pub struct CallExpressionData {
- pub callee: Box<Expression>,
- pub arguments: Vec<CallArgument>,
- pub is_parenthesized: bool,
- pub is_inside_parens: bool,
+impl<'a> ListItem<'a> for CallArgument<'a> {
+ type Context = ();
+
+ fn read(tree: &'a SyntaxTree, argument: u32, _: ()) -> Self {
+ let is_spread = tree.tag(argument) == tag::SPREAD;
+ CallArgument {
+ value: Expression::new(tree, if is_spread { tree.a(argument) } else { argument }),
+ is_spread,
+ }
+ }
}
-#[derive(Clone, Debug)]
-pub struct SuperCallData {
- pub arguments: Vec<CallArgument>,
+/// The arguments of a call, which are a list of the tree, or a spread of the parameter of a default constructor.
+#[derive(Clone, Copy)]
+pub enum CallArguments<'a> {
+ List(List<'a, CallArgument<'a>>),
+ DefaultConstructorSpread(CallArgument<'a>),
+}
+
+impl<'a> Sequence for CallArguments<'a> {
+ type Item = CallArgument<'a>;
+
+ fn len(&self) -> usize {
+ match self {
+ CallArguments::List(list) => list.len(),
+ CallArguments::DefaultConstructorSpread(_) => 1,
+ }
+ }
+
+ fn at(&self, index: usize) -> CallArgument<'a> {
+ match self {
+ CallArguments::List(list) => list.at(index),
+ CallArguments::DefaultConstructorSpread(argument) => *argument,
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+pub struct CallExpressionData<'a> {
+ pub callee: Expression<'a>,
+ pub arguments: CallArguments<'a>,
+}
+
+#[derive(Clone, Copy)]
+pub struct SuperCallData<'a> {
+ pub arguments: CallArguments<'a>,
pub is_synthetic: bool,
}
// =============================================================================
-// Optional chain types
+// Optional chains
// =============================================================================
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum OptionalChainMode {
- Optional,
- NotOptional,
-}
-
-#[derive(Clone, Debug)]
-pub enum OptionalChainReference {
+#[derive(Clone, Copy)]
+pub enum OptionalChainReference<'a> {
Call {
- arguments: Vec<CallArgument>,
+ arguments: CallArguments<'a>,
mode: OptionalChainMode,
},
ComputedReference {
- expression: Box<Expression>,
+ expression: Expression<'a>,
mode: OptionalChainMode,
},
MemberReference {
- identifier: IdentifierId,
+ identifier: Identifier<'a>,
mode: OptionalChainMode,
},
PrivateMemberReference {
- private_identifier: PrivateIdentifier,
+ private_identifier: PrivateIdentifier<'a>,
mode: OptionalChainMode,
},
}
-// =============================================================================
-// Template literal types
-// =============================================================================
+#[derive(Clone, Copy)]
+pub struct OptionalChainData<'a> {
+ tree: &'a SyntaxTree,
+ node: u32,
+}
+
+impl<'a> OptionalChainData<'a> {
+ fn is_link(tag: u8) -> bool {
+ matches!(
+ tag,
+ tag::MEMBER
+ | tag::INDEX
+ | tag::PRIVATE_MEMBER
+ | tag::CALL
+ | tag::OPT_MEMBER
+ | tag::OPT_INDEX
+ | tag::OPT_PRIVATE_MEMBER
+ | tag::OPT_CALL
+ )
+ }
-#[derive(Clone, Debug)]
-pub struct TemplateLiteralData {
- pub expressions: Vec<Expression>,
- pub raw_strings: Vec<Utf16String>,
+ fn is_optional(tag: u8) -> bool {
+ matches!(
+ tag,
+ tag::OPT_MEMBER | tag::OPT_INDEX | tag::OPT_PRIVATE_MEMBER | tag::OPT_CALL
+ )
+ }
+
+ /// The chain reaches down to its innermost optional link, and what is below that is its base. Returns the base and
+ /// the links, outermost first.
+ pub(crate) fn links(tree: &SyntaxTree, node: u32) -> (u32, Vec<u32>) {
+ let mut links = Vec::new();
+ let mut base = node;
+ let mut remaining_optional_links = 0;
+ let mut probe = node;
+ while Self::is_link(tree.tag(probe)) {
+ remaining_optional_links += u32::from(Self::is_optional(tree.tag(probe)));
+ probe = tree.a(probe);
+ }
+ while remaining_optional_links > 0 {
+ remaining_optional_links -= u32::from(Self::is_optional(tree.tag(base)));
+ links.push(base);
+ base = tree.a(base);
+ }
+ (base, links)
+ }
+
+ pub fn base(&self) -> Expression<'a> {
+ Expression::new(self.tree, Self::links(self.tree, self.node).0)
+ }
+
+ pub fn references(&self) -> Vec<OptionalChainReference<'a>> {
+ let tree = self.tree;
+ let (_, mut links) = Self::links(tree, self.node);
+ links.reverse();
+ links
+ .into_iter()
+ .map(|link| {
+ let link_tag = tree.tag(link);
+ let mode = if Self::is_optional(link_tag) {
+ OptionalChainMode::Optional
+ } else {
+ OptionalChainMode::NotOptional
+ };
+ let b = tree.b(link);
+ match link_tag {
+ tag::CALL | tag::OPT_CALL => OptionalChainReference::Call {
+ arguments: CallArguments::List(List::new(tree, b, ())),
+ mode,
+ },
+ tag::INDEX | tag::OPT_INDEX => OptionalChainReference::ComputedReference {
+ expression: Expression::new(tree, b),
+ mode,
+ },
+ tag::MEMBER | tag::OPT_MEMBER => OptionalChainReference::MemberReference {
+ identifier: tree.plain_identifier(Name(b), tree.name_after(tree.pos(link))),
+ mode,
+ },
+ _ => OptionalChainReference::PrivateMemberReference {
+ private_identifier: tree.private_identifier(b, tree.name_after(tree.pos(link))),
+ mode,
+ },
+ }
+ })
+ .collect()
+ }
}
// =============================================================================
-// RegExp literal
+// Literals
// =============================================================================
-#[derive(Clone, Debug)]
-pub struct RegExpLiteralData {
- pub pattern: Utf16String,
- pub flags: Utf16String,
+/// A numeric literal, whose value comes from its source text.
+#[derive(Clone, Copy)]
+pub struct NumericLiteral<'a> {
+ text: Utf16View<'a>,
}
-// =============================================================================
-// Try/Catch types
-// =============================================================================
+impl NumericLiteral<'_> {
+ pub fn value(&self) -> f64 {
+ literals::parse_numeric_value(self.text)
+ }
+}
-#[derive(Clone, Debug)]
-pub struct TryStatementData {
- pub block: Box<Statement>,
- pub handler: Option<CatchClause>,
- pub finalizer: Option<Box<Statement>>,
+/// A string, whose value comes from the source or a name.
+#[derive(Clone, Copy)]
+pub enum StringLiteral<'a> {
+ /// The value as it is.
+ Name(Utf16View<'a>),
+ /// Source text that may contain escape sequences.
+ Source(Utf16View<'a>, EscapeMode),
}
-#[derive(Clone, Debug)]
-pub struct CatchClause {
- pub range: SourceRange,
- pub parameter: Option<CatchBinding>,
- pub body: Box<Statement>,
+impl StringLiteral<'_> {
+ pub fn value(&self) -> Utf16String {
+ match *self {
+ StringLiteral::Name(text) => text.into(),
+ StringLiteral::Source(text, mode) => literals::process_escape_sequences_impl(text, mode).value,
+ }
+ }
}
-#[derive(Clone, Debug)]
-pub enum CatchBinding {
- Identifier(IdentifierId),
- BindingPattern(BindingPattern),
+#[derive(Clone, Copy)]
+pub struct RegExpLiteralData<'a> {
+ pub pattern: Utf16View<'a>,
+ pub flags: Utf16View<'a>,
}
-// =============================================================================
-// Switch types
-// =============================================================================
+/// An element of a template: one of its expressions, or one of the strings between them.
+#[derive(Clone, Copy)]
+pub struct TemplateElementContext {
+ is_tagged: bool,
+ template_start: u32,
+}
-#[derive(Clone, Debug)]
-pub struct SwitchStatementData {
- pub scope: ScopeId,
- pub discriminant: Box<Expression>,
- pub cases: Vec<SwitchCase>,
+impl<'a> ListItem<'a> for TemplateElement<'a> {
+ type Context = TemplateElementContext;
+
+ fn read(tree: &'a SyntaxTree, node: u32, context: TemplateElementContext) -> Self {
+ TemplateElement(if tree.tag(node) == tag::TEMPLATE_CHUNK {
+ Expression::with_form(
+ tree,
+ node,
+ ExpressionForm::TemplateChunk {
+ is_tagged: context.is_tagged,
+ template_start: context.template_start,
+ },
+ )
+ } else {
+ Expression::new(tree, node)
+ })
+ }
}
-#[derive(Clone, Debug)]
-pub struct SwitchCase {
- pub range: SourceRange,
- pub scope: ScopeId,
- pub test: Option<Expression>,
+#[derive(Clone, Copy)]
+pub struct TemplateElement<'a>(pub Expression<'a>);
+
+#[derive(Clone, Copy)]
+pub struct TemplateLiteralData<'a> {
+ tree: &'a SyntaxTree,
+ items: &'a [u32],
+ pub expressions: List<'a, TemplateElement<'a>>,
+}
+
+impl TemplateLiteralData<'_> {
+ /// The raw strings of a tagged template.
+ pub fn raw_strings(&self) -> Vec<Utf16String> {
+ let tree = self.tree;
+ self.items
+ .iter()
+ .filter(|&&item| tree.tag(item) == tag::TEMPLATE_CHUNK)
+ .map(|&item| literals::raw_template_value(template_chunk_units(tree, item)))
+ .collect()
+ }
+}
+
+fn template_chunk_units(tree: &SyntaxTree, chunk: u32) -> Utf16View<'_> {
+ let start = tree.a(chunk);
+ tree.source_units(start, start + (tree.b(chunk) >> 1))
}
// =============================================================================
-// Module types (import/export)
+// Statement data
// =============================================================================
-#[derive(Clone, Debug)]
-pub struct ModuleRequest {
- pub module_specifier: Utf16String,
- pub attributes: Vec<ImportAttribute>,
+#[derive(Clone, Copy)]
+pub struct VariableDeclarator<'a> {
+ tree: &'a SyntaxTree,
+ offset: u32,
+ pub target: VariableDeclaratorTarget<'a>,
+ pub init: Option<Expression<'a>>,
}
-#[derive(Clone, Debug)]
-pub struct ImportAttribute {
- pub key: Utf16String,
- pub value: Utf16String,
+#[derive(Clone, Copy)]
+pub enum VariableDeclaratorTarget<'a> {
+ Identifier(Identifier<'a>),
+ BindingPattern(BindingPattern<'a>),
}
-#[derive(Clone, Debug)]
-pub struct ImportEntry {
- /// `None` means namespace import (`import * as x`).
- pub import_name: Option<Utf16String>,
- pub local_name: Utf16String,
+impl VariableDeclarator<'_> {
+ pub fn range(&self) -> SourceRange {
+ self.tree.range(self.offset)
+ }
}
-#[derive(Clone, Debug)]
-pub struct ImportStatementData {
- pub module_request: ModuleRequest,
- pub entries: Vec<ImportEntry>,
+impl<'a> ListItem<'a> for VariableDeclarator<'a> {
+ /// Where the declaration starts.
+ type Context = u32;
+
+ fn read(tree: &'a SyntaxTree, declarator: u32, offset: u32) -> Self {
+ let (target, init) = (tree.a(declarator), tree.b(declarator));
+ VariableDeclarator {
+ tree,
+ offset,
+ target: if tree.tag(target) == tag::IDENT {
+ VariableDeclaratorTarget::Identifier(tree.identifier(Name(tree.a(target)), tree.pos(target), target))
+ } else {
+ VariableDeclaratorTarget::BindingPattern(BindingPattern::new(tree, target, PatternMode::Binding))
+ },
+ init: (init != 0).then(|| Expression::new(tree, init)),
+ }
+ }
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum ExportEntryKind {
- NamedExport = 0,
- ModuleRequestAll = 1,
- ModuleRequestAllButDefault = 2,
- EmptyNamedExport = 3,
+#[derive(Clone, Copy)]
+pub struct VariableDeclarationData<'a> {
+ pub kind: DeclarationKind,
+ pub declarations: List<'a, VariableDeclarator<'a>>,
}
-#[derive(Clone, Debug)]
-pub struct ExportEntry {
- pub kind: ExportEntryKind,
- pub export_name: Option<Utf16String>,
- pub local_or_import_name: Option<Utf16String>,
+/// A `using` or an `await using` declaration.
+#[derive(Clone, Copy)]
+pub struct UsingDeclarationData<'a> {
+ pub is_await: bool,
+ pub declarations: List<'a, VariableDeclarator<'a>>,
+}
+
+#[derive(Clone, Copy)]
+pub struct FunctionDeclarationData<'a> {
+ pub function_id: FunctionId,
+ pub name: Option<Identifier<'a>>,
+ pub kind: FunctionKind,
+ pub is_hoisted: bool,
+}
+
+/// The body of the function that evaluates the initializer of a class field.
+#[derive(Clone, Copy)]
+pub struct ClassFieldInitializerData<'a> {
+ pub expression: Expression<'a>,
+ /// The key of the field.
+ pub key: Expression<'a>,
+}
+
+impl ClassFieldInitializerData<'_> {
+ /// The name that an anonymous function in the field gets.
+ pub fn field_name(&self) -> Utf16String {
+ match self.key.kind() {
+ ExpressionKind::Identifier(identifier) => identifier.text().into(),
+ ExpressionKind::StringLiteral(literal) => literal.value(),
+ ExpressionKind::PrivateIdentifier(identifier) => identifier.name(),
+ ExpressionKind::NumericLiteral(literal) => crate::host::js_number_to_utf16(literal.value()),
+ ExpressionKind::BigIntLiteral(literal) => bigint_literal_digits(literal).into(),
+ _ => Utf16String::default(),
+ }
+ }
+}
+
+/// The digits of the source text of a BigInt literal, which ends in `n`.
+pub fn bigint_literal_digits(literal: Utf16View<'_>) -> Utf16View<'_> {
+ literal.substring_view(0, literal.length_in_code_units() - 1)
+}
+
+#[derive(Clone, Copy)]
+pub struct IfStatementData<'a> {
+ pub test: Expression<'a>,
+ pub consequent: Statement<'a>,
+ pub alternate: Option<Statement<'a>>,
+}
+
+#[derive(Clone, Copy)]
+pub struct WhileStatementData<'a> {
+ pub test: Expression<'a>,
+ pub body: Statement<'a>,
+}
+
+/// Init clause of a for loop: either a declaration or an expression.
+#[derive(Clone, Copy)]
+pub enum ForInit<'a> {
+ Declaration(Statement<'a>),
+ Expression(Expression<'a>),
+}
+
+#[derive(Clone, Copy)]
+pub struct ForStatementData<'a> {
+ pub init: Option<ForInit<'a>>,
+ pub test: Option<Expression<'a>>,
+ pub update: Option<Expression<'a>>,
+ pub body: Statement<'a>,
+}
+
+/// Left-hand side of for-in, for-of, for-await-of.
+#[derive(Clone, Copy)]
+pub enum ForInOfLhs<'a> {
+ /// A variable declaration (`for (let x of ...)`)
+ Declaration(Statement<'a>),
+ /// An expression (`for (x in obj)`)
+ Expression(Expression<'a>),
+ /// A binding pattern (`for ({a, b} of ...)`)
+ Pattern(BindingPattern<'a>),
+}
+
+#[derive(Clone, Copy)]
+pub struct ForInOfStatementData<'a> {
+ pub kind: ForInOfKind,
+ pub lhs: ForInOfLhs<'a>,
+ pub rhs: Expression<'a>,
+ pub body: Statement<'a>,
+}
+
+#[derive(Clone, Copy)]
+pub struct WithStatementData<'a> {
+ pub object: Expression<'a>,
+ pub body: Statement<'a>,
+}
+
+#[derive(Clone, Copy)]
+pub struct LabelledStatementData<'a> {
+ pub label: Utf16View<'a>,
+ pub item: Statement<'a>,
+}
+
+#[derive(Clone, Copy)]
+pub struct TryStatementData<'a> {
+ pub block: Statement<'a>,
+ pub handler: Option<CatchClause<'a>>,
+ pub finalizer: Option<Statement<'a>>,
+}
+
+#[derive(Clone, Copy)]
+pub struct CatchClause<'a> {
+ tree: &'a SyntaxTree,
+ offset: u32,
+ pub parameter: Option<CatchBinding<'a>>,
+ pub body: Statement<'a>,
+}
+
+impl CatchClause<'_> {
+ pub fn range(&self) -> SourceRange {
+ self.tree.range(self.offset)
+ }
+}
+
+#[derive(Clone, Copy)]
+pub enum CatchBinding<'a> {
+ Identifier(Identifier<'a>),
+ BindingPattern(BindingPattern<'a>),
+}
+
+#[derive(Clone, Copy)]
+pub struct SwitchStatementData<'a> {
+ pub discriminant: Expression<'a>,
+ pub cases: List<'a, SwitchCase<'a>>,
+}
+
+#[derive(Clone, Copy)]
+pub struct SwitchCase<'a> {
+ tree: &'a SyntaxTree,
+ offset: u32,
+ pub scope: Scope<'a>,
+ pub test: Option<Expression<'a>>,
}
-#[derive(Clone, Debug)]
-pub struct ExportStatementData {
- pub statement: Option<Box<Statement>>,
- pub entries: Vec<ExportEntry>,
- pub is_default_export: bool,
- pub module_request: Option<ModuleRequest>,
+impl SwitchCase<'_> {
+ pub fn range(&self) -> SourceRange {
+ self.tree.range(self.offset)
+ }
}
-// =============================================================================
-// For-in/of LHS
-// =============================================================================
+impl<'a> ListItem<'a> for SwitchCase<'a> {
+ type Context = ();
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum ForInOfKind {
- ForIn,
- ForOf,
- ForAwaitOf,
+ fn read(tree: &'a SyntaxTree, case: u32, _: ()) -> Self {
+ let test = tree.a(case);
+ SwitchCase {
+ tree,
+ offset: tree.pos(case),
+ scope: Scope::of_list(tree, tree.b(case)),
+ test: (test != 0).then(|| Expression::new(tree, test)),
+ }
+ }
}
-/// Init clause of a for loop: either a declaration or an expression.
-/// C++ stores this as a polymorphic `RefPtr<ASTNode>` that can be either
-/// an Expression or a VariableDeclaration. We use an explicit enum so that
-/// expression inits are NOT wrapped in an ExpressionStatement node.
-#[derive(Clone, Debug)]
-pub enum ForInit {
- Declaration(Box<Statement>),
- Expression(Box<Expression>),
+#[derive(Clone, Copy)]
+pub struct ImportStatementData<'a> {
+ tree: &'a SyntaxTree,
+ node: u32,
}
-/// Left-hand side of for-in, for-of, for-await-of.
-#[derive(Clone, Debug)]
-pub enum ForInOfLhs {
- /// A variable declaration (`for (let x of ...)`)
- Declaration(Box<Statement>),
- /// An expression (`for (x in obj)`)
- Expression(Box<Expression>),
- /// A binding pattern (`for ({a, b} of ...)`)
- Pattern(BindingPattern),
+impl ImportStatementData<'_> {
+ pub fn module_request(&self) -> ModuleRequest {
+ self.tree.module_request(self.tree.b(self.node))
+ }
+
+ pub fn entries(&self) -> Vec<ImportEntry> {
+ let tree = self.tree;
+ tree.list(tree.a(self.node))
+ .iter()
+ .map(|&specifier| {
+ let imported = tree.a(specifier);
+ ImportEntry {
+ import_name: match imported {
+ 0 => Some(Utf16String::from_utf16(utf16!("default"))),
+ NONE => None,
+ _ => Some(tree.specifier_name(imported)),
+ },
+ local_name: tree.name_text(Name(tree.b(specifier))).into(),
+ }
+ })
+ .collect()
+ }
}
-// =============================================================================
-// Assignment LHS
-// =============================================================================
+#[derive(Clone, Copy)]
+pub struct ExportStatementData<'a> {
+ tree: &'a SyntaxTree,
+ node: u32,
+ pub statement: Option<Statement<'a>>,
+ pub is_default_export: bool,
+}
-#[derive(Clone, Debug)]
-pub enum AssignmentLhs {
- Expression(Box<Expression>),
- Pattern(BindingPattern),
+impl ExportStatementData<'_> {
+ pub fn module_request(&self) -> Option<ModuleRequest> {
+ let tree = self.tree;
+ let (a, b) = (tree.a(self.node), tree.b(self.node));
+ match tree.tag(self.node) {
+ tag::EXPORT_ALL => Some(tree.module_request(b)),
+ tag::EXPORT_NAMED if a != 0 && b != 0 => Some(tree.module_request(b)),
+ _ => None,
+ }
+ }
+
+ pub fn entries(&self) -> Vec<ExportEntry> {
+ let tree = self.tree;
+ let (a, b) = (tree.a(self.node), tree.b(self.node));
+ let mut entries = Vec::new();
+ match tree.tag(self.node) {
+ tag::EXPORT_ALL => {
+ if a == 0 {
+ entries.push(ExportEntry {
+ kind: ExportEntryKind::ModuleRequestAllButDefault,
+ export_name: None,
+ local_or_import_name: None,
+ });
+ } else {
+ entries.push(ExportEntry {
+ kind: ExportEntryKind::ModuleRequestAll,
+ export_name: Some(tree.specifier_name(a)),
+ local_or_import_name: None,
+ });
+ }
+ }
+ tag::EXPORT_DEFAULT => {
+ let inner_tag = tree.tag(a);
+ let mut local_name = Utf16String::from_utf16(utf16!("*default*"));
+ if inner_tag == tag::FUNCTION && b != 0 {
+ let name = tree.script.index.name[tree.b(a) as usize];
+ if name != NONE {
+ local_name = tree.name_text(Name(name)).into();
+ }
+ } else if inner_tag == tag::CLASS_DECL {
+ local_name = tree.name_text(Name(tree.a(tree.a(a)))).into();
+ }
+ entries.push(ExportEntry {
+ kind: ExportEntryKind::NamedExport,
+ export_name: Some(Utf16String::from_utf16(utf16!("default"))),
+ local_or_import_name: Some(local_name),
+ });
+ }
+ _ if a != 0 => {
+ for &specifier in tree.list(a) {
+ entries.push(ExportEntry {
+ kind: ExportEntryKind::NamedExport,
+ export_name: Some(tree.specifier_name(tree.b(specifier))),
+ local_or_import_name: Some(tree.specifier_name(tree.a(specifier))),
+ });
+ }
+ if entries.is_empty() {
+ entries.push(ExportEntry {
+ kind: ExportEntryKind::EmptyNamedExport,
+ export_name: None,
+ local_or_import_name: None,
+ });
+ }
+ }
+ _ => {
+ let mut names = Vec::new();
+ match tree.tag(b) {
+ tag::FUNCTION_DECL => names.push(tree.name_text(Name(tree.b(b))).into()),
+ tag::CLASS_DECL => names.push(tree.name_text(Name(tree.a(tree.a(b)))).into()),
+ _ => {
+ for &declarator in tree.list(tree.a(b)) {
+ tree.pattern_names(tree.a(declarator), &mut names);
+ }
+ }
+ }
+ for name in names {
+ entries.push(ExportEntry {
+ kind: ExportEntryKind::NamedExport,
+ export_name: Some(name.clone()),
+ local_or_import_name: Some(name),
+ });
+ }
+ }
+ }
+ entries
+ }
+}
+
+#[derive(Clone, Copy)]
+pub struct ProgramData<'a> {
+ pub scope: Scope<'a>,
+ pub program_type: ProgramType,
+ pub is_strict_mode: bool,
+ pub has_top_level_await: bool,
}
// =============================================================================
-// Scope data
+// Scopes
// =============================================================================
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum LocalVarKind {
- Var = 0,
- LetOrConst = 1,
- Function = 2,
- ArgumentsObject = 3,
- CatchClauseParameter = 4,
+/// What statements a scope has, which the tree does not always hold as a list.
+#[derive(Clone, Copy)]
+pub enum ScopeChildren<'a> {
+ List(List<'a, Statement<'a>>),
+ One(Statement<'a>),
+ None,
}
-#[derive(Clone, Debug)]
-pub struct LocalVariable {
- pub name: Utf16String,
- pub kind: LocalVarKind,
- pub is_mutable: bool,
- pub scope_range: Option<SourceRange>,
-}
+impl<'a> Sequence for ScopeChildren<'a> {
+ type Item = Statement<'a>;
-/// Data shared by all scope-bearing nodes (Program, BlockStatement,
-/// FunctionBody, SwitchStatement, SwitchCase).
-///
-/// AST nodes refer to scopes via `ScopeId` indices into `ScopeArena`,
-/// so the AST itself is plain data — no `Rc`/`RefCell` and naturally
-/// `Send + Sync` once parsing is done. The scope collector's two-phase
-/// design (build tree during parse, analyze bottom-up afterwards)
-/// ensures only one mutable borrow of a given `ScopeData` is ever
-/// live at a time.
-#[derive(Clone, Debug, Default)]
-pub struct ScopeData {
- pub children: Vec<Statement>,
- pub source_range: Option<SourceRange>,
- pub local_variables: Vec<LocalVariable>,
- pub function_scope_data: Option<Box<FunctionScopeData>>,
- pub hoisted_functions: Vec<usize>,
- /// Function names hoisted from inner blocks via Annex B.3.3.
- /// The FDI should create `var` bindings initialized to `undefined`
- /// for each name.
- pub annexb_function_names: Vec<Utf16String>,
- // Scope analysis insights, written by the scope collector after analyze().
- pub uses_this: bool,
- pub uses_this_from_environment: bool,
- pub contains_direct_call_to_eval: bool,
- pub contains_access_to_arguments_object: bool,
- /// For the body of a named function expression: whether nothing can look up the function's own name in it, so
- /// that the environment that binds the name is never observed.
- pub function_name_is_unused: bool,
-}
+ fn len(&self) -> usize {
+ match self {
+ ScopeChildren::List(list) => list.len(),
+ ScopeChildren::One(_) => 1,
+ ScopeChildren::None => 0,
+ }
+ }
-/// Scope analysis data for function bodies, populated by the scope collector.
-#[derive(Clone, Debug)]
-pub struct FunctionScopeData {
- pub functions_to_initialize: Vec<FunctionToInit>,
- pub vars_to_initialize: Vec<VarToInit>,
- pub var_names: Vec<Utf16String>,
- pub has_function_named_arguments: bool,
- pub has_argument_parameter: bool,
- pub has_lexically_declared_arguments: bool,
- pub non_local_var_count: usize,
- pub non_local_var_count_for_parameter_expressions: usize,
-}
-
-/// Reference to a function declaration that needs hoisting/initialization.
-/// Stores the index within the parent ScopeData.children.
-#[derive(Clone, Debug)]
-pub struct FunctionToInit {
- pub child_index: usize,
+ fn at(&self, index: usize) -> Statement<'a> {
+ match self {
+ ScopeChildren::List(list) => list.at(index),
+ ScopeChildren::One(statement) => *statement,
+ ScopeChildren::None => unreachable!("a scope without children has no child {index}"),
+ }
+ }
}
-/// A resolved local binding: the operand type and index assigned by scope analysis.
-#[derive(Clone, Copy, Debug)]
-pub struct LocalBinding {
- pub local_type: LocalType,
- pub index: u32,
+/// A scope with statements of its own: a program, a function body, a block or a case of a switch.
+#[derive(Clone, Copy)]
+pub struct Scope<'a> {
+ tree: &'a SyntaxTree,
+ pub children: ScopeChildren<'a>,
+ /// What scope analysis found out if this is the scope of a function, a static block or a program.
+ row: Option<&'a ScopeRow>,
}
-/// A `var` binding that needs initialization during function entry.
-#[derive(Clone, Debug)]
-pub struct VarToInit {
- pub name: Utf16String,
- pub is_parameter: bool,
- pub is_function_name: bool,
- /// If the scope analysis optimized this var to a local, stores the binding info.
- pub local: Option<LocalBinding>,
+impl<'a> Scope<'a> {
+ fn new(tree: &'a SyntaxTree, children: ScopeChildren<'a>) -> Self {
+ Self {
+ tree,
+ children,
+ row: None,
+ }
+ }
+
+ fn of_list(tree: &'a SyntaxTree, list: u32) -> Self {
+ Self::new(tree, ScopeChildren::List(List::new(tree, list, ())))
+ }
+
+ fn of_function(tree: &'a SyntaxTree, children: ScopeChildren<'a>, row: &'a ScopeRow) -> Self {
+ Self {
+ tree,
+ children,
+ row: Some(row),
+ }
+ }
+
+ pub fn local_variables(&self) -> &'a [LocalVariable] {
+ self.row
+ .map_or(&[], |row| row.local_variables.of(&self.tree.scopes.local_variables))
+ }
+
+ /// Function names hoisted from inner blocks via Annex B.3.3. The FDI should create `var` bindings initialized to
+ /// `undefined` for each name.
+ pub fn annexb_function_names(&self) -> &'a [Name] {
+ self.row.map_or(&[], |row| {
+ row.annexb_function_names.of(&self.tree.scopes.annexb_function_names)
+ })
+ }
+
+ pub fn uses_this(&self) -> bool {
+ self.row.is_some_and(|row| row.uses_this)
+ }
+
+ pub fn uses_this_from_environment(&self) -> bool {
+ self.row.is_some_and(|row| row.uses_this_from_environment)
+ }
+
+ pub fn contains_direct_call_to_eval(&self) -> bool {
+ self.row.is_some_and(|row| row.contains_direct_call_to_eval)
+ }
+
+ pub fn contains_access_to_arguments_object(&self) -> bool {
+ self.row.is_some_and(|row| row.contains_access_to_arguments_object)
+ }
}
// =============================================================================
-// Expression data structs (boxed variants)
+// Expressions
// =============================================================================
-#[derive(Clone, Debug)]
-pub struct BinaryExprData {
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum ExpressionForm {
+ /// The expression that the node's tag says.
+ Node,
+ /// The name of an identifier node as a string.
+ PropertyKeyName,
+ /// The property name after a member node's dot, which has no node of its own.
+ MemberName,
+ /// The key of a shorthand property node.
+ ShorthandKey,
+ /// The value of a shorthand property node.
+ ShorthandValue { object_start: u32 },
+ /// The string of a template chunk node.
+ TemplateChunk { is_tagged: bool, template_start: u32 },
+ /// The template node of a tagged template.
+ TaggedTemplate,
+ /// The default constructor of a class node.
+ DefaultConstructor,
+ /// The `super(...args)` of the default constructor of a class node.
+ DefaultConstructorSuperCall,
+ /// The `args` of the default constructor of a class node.
+ DefaultConstructorArgument,
+}
+
+#[derive(Clone, Copy)]
+pub struct Expression<'a> {
+ tree: &'a SyntaxTree,
+ node: u32,
+ form: ExpressionForm,
+}
+
+#[derive(Clone, Copy)]
+pub struct BinaryExpressionData<'a> {
pub op: BinaryOp,
- pub lhs: Box<Expression>,
- pub rhs: Box<Expression>,
+ pub lhs: Expression<'a>,
+ pub rhs: Expression<'a>,
}
-#[derive(Clone, Debug)]
-pub struct LogicalExprData {
+#[derive(Clone, Copy)]
+pub struct LogicalExpressionData<'a> {
pub op: LogicalOp,
- pub lhs: Box<Expression>,
- pub rhs: Box<Expression>,
+ pub lhs: Expression<'a>,
+ pub rhs: Expression<'a>,
}
-#[derive(Clone, Debug)]
-pub struct UpdateExprData {
+#[derive(Clone, Copy)]
+pub struct UpdateExpressionData<'a> {
pub op: UpdateOp,
- pub argument: Box<Expression>,
+ pub argument: Expression<'a>,
pub prefixed: bool,
}
-#[derive(Clone, Debug)]
-pub struct AssignmentExprData {
+#[derive(Clone, Copy)]
+pub enum AssignmentLhs<'a> {
+ Expression(Expression<'a>),
+ Pattern(BindingPattern<'a>),
+}
+
+#[derive(Clone, Copy)]
+pub struct AssignmentExpressionData<'a> {
pub op: AssignmentOp,
- pub lhs: AssignmentLhs,
- pub rhs: Box<Expression>,
+ pub lhs: AssignmentLhs<'a>,
+ pub rhs: Expression<'a>,
pub lhs_is_parenthesized: bool,
}
-#[derive(Clone, Debug)]
-pub struct ConditionalExprData {
- pub test: Box<Expression>,
- pub consequent: Box<Expression>,
- pub alternate: Box<Expression>,
+#[derive(Clone, Copy)]
+pub struct ConditionalExpressionData<'a> {
+ pub test: Expression<'a>,
+ pub consequent: Expression<'a>,
+ pub alternate: Expression<'a>,
}
-#[derive(Clone, Debug)]
-pub struct MemberExprData {
- pub object: Box<Expression>,
- pub property: Box<Expression>,
+#[derive(Clone, Copy)]
+pub struct MemberExpressionData<'a> {
+ pub object: Expression<'a>,
+ pub property: Expression<'a>,
pub computed: bool,
}
-#[derive(Clone, Debug)]
-pub struct OptionalChainData {
- pub base: Box<Expression>,
- pub references: Vec<OptionalChainReference>,
-}
-
-#[derive(Clone, Debug)]
-pub struct TaggedTemplateData {
- pub tag: Box<Expression>,
- pub template_literal: Box<Expression>,
+#[derive(Clone, Copy)]
+pub struct TaggedTemplateData<'a> {
+ pub tag: Expression<'a>,
+ pub template_literal: Expression<'a>,
}
-#[derive(Clone, Debug)]
-pub struct ImportCallData {
- pub specifier: Box<Expression>,
- pub options: Option<Box<Expression>>,
+#[derive(Clone, Copy)]
+pub struct ImportCallData<'a> {
+ pub specifier: Expression<'a>,
+ pub options: Option<Expression<'a>>,
}
-#[derive(Clone, Debug)]
-pub struct YieldExprData {
- pub argument: Option<Box<Expression>>,
+#[derive(Clone, Copy)]
+pub struct YieldExpressionData<'a> {
+ pub argument: Option<Expression<'a>>,
pub is_yield_from: bool,
}
-// =============================================================================
-// Expression enum
-// =============================================================================
-
-#[derive(Clone, Debug)]
-pub enum ExpressionKind {
+#[derive(Clone, Copy)]
+pub enum ExpressionKind<'a> {
// Literals
- NumericLiteral(f64),
- StringLiteral(Box<Utf16String>),
+ NumericLiteral(NumericLiteral<'a>),
+ StringLiteral(StringLiteral<'a>),
BooleanLiteral(bool),
NullLiteral,
- BigIntLiteral(Box<Utf16String>),
- RegExpLiteral(Box<RegExpLiteralData>),
+ BigIntLiteral(Utf16View<'a>),
+ RegExpLiteral(RegExpLiteralData<'a>),
// Identifiers
- Identifier(IdentifierId),
- PrivateIdentifier(Box<PrivateIdentifier>),
+ Identifier(Identifier<'a>),
+ PrivateIdentifier(PrivateIdentifier<'a>),
// Operators
- Binary(Box<BinaryExprData>),
- Logical(Box<LogicalExprData>),
- Unary { op: UnaryOp, operand: Box<Expression> },
- Update(Box<UpdateExprData>),
- Assignment(Box<AssignmentExprData>),
- Conditional(Box<ConditionalExprData>),
- Sequence(Box<Vec<Expression>>),
+ Binary(BinaryExpressionData<'a>),
+ Logical(LogicalExpressionData<'a>),
+ Unary { op: UnaryOp, operand: Expression<'a> },
+ Update(UpdateExpressionData<'a>),
+ Assignment(AssignmentExpressionData<'a>),
+ Conditional(ConditionalExpressionData<'a>),
+ Sequence(List<'a, Expression<'a>>),
// Member access
- Member(Box<MemberExprData>),
- OptionalChain(Box<OptionalChainData>),
+ Member(MemberExpressionData<'a>),
+ OptionalChain(OptionalChainData<'a>),
// Calls
- Call(Box<CallExpressionData>),
- New(Box<CallExpressionData>),
- SuperCall(Box<SuperCallData>),
+ Call(CallExpressionData<'a>),
+ New(CallExpressionData<'a>),
+ SuperCall(SuperCallData<'a>),
// Spread
- Spread(Box<Expression>),
+ Spread(Expression<'a>),
// This / Super
This,
@@ -1586,179 +2622,725 @@ pub enum ExpressionKind {
Function(FunctionId),
// Classes
- Class(Box<ClassData>),
+ Class(ClassData<'a>),
// Collections
- Array(Box<Vec<Option<Expression>>>),
- Object(Box<Vec<ObjectProperty>>),
+ Array(List<'a, Option<Expression<'a>>>),
+ Object(List<'a, ObjectProperty<'a>>),
// Templates
- TemplateLiteral(Box<TemplateLiteralData>),
- TaggedTemplateLiteral(Box<TaggedTemplateData>),
+ TemplateLiteral(TemplateLiteralData<'a>),
+ TaggedTemplateLiteral(TaggedTemplateData<'a>),
// Meta
MetaProperty(MetaPropertyType),
- ImportCall(Box<ImportCallData>),
+ ImportCall(ImportCallData<'a>),
// Async / Generator
- Yield(Box<YieldExprData>),
- Await(Box<Expression>),
-
- // Error recovery
- Error,
-}
-
-// =============================================================================
-// Statement data structs
-// =============================================================================
-
-#[derive(Clone, Debug)]
-pub struct IfStatementData {
- pub test: Box<Expression>,
- pub consequent: Box<Statement>,
- pub alternate: Option<Box<Statement>>,
-}
-
-#[derive(Clone, Debug)]
-pub struct WhileStatementData {
- pub test: Box<Expression>,
- pub body: Box<Statement>,
-}
+ Yield(YieldExpressionData<'a>),
+ Await(Expression<'a>),
+}
+
+pub(crate) const BINARY_OPERATORS: [Option<BinaryOp>; 25] = [
+ None,
+ None,
+ None,
+ Some(BinaryOp::BitwiseOr),
+ Some(BinaryOp::BitwiseXor),
+ Some(BinaryOp::BitwiseAnd),
+ Some(BinaryOp::LooselyEquals),
+ Some(BinaryOp::LooselyInequals),
+ Some(BinaryOp::StrictlyEquals),
+ Some(BinaryOp::StrictlyInequals),
+ Some(BinaryOp::LessThan),
+ Some(BinaryOp::GreaterThan),
+ Some(BinaryOp::LessThanEquals),
+ Some(BinaryOp::GreaterThanEquals),
+ Some(BinaryOp::LeftShift),
+ Some(BinaryOp::RightShift),
+ Some(BinaryOp::UnsignedRightShift),
+ Some(BinaryOp::Addition),
+ Some(BinaryOp::Subtraction),
+ Some(BinaryOp::Multiplication),
+ Some(BinaryOp::Division),
+ Some(BinaryOp::Modulo),
+ Some(BinaryOp::Exponentiation),
+ Some(BinaryOp::In),
+ Some(BinaryOp::InstanceOf),
+];
+
+pub(crate) const ASSIGNMENT_OPERATORS: [AssignmentOp; 16] = [
+ AssignmentOp::Assignment,
+ AssignmentOp::AdditionAssignment,
+ AssignmentOp::SubtractionAssignment,
+ AssignmentOp::MultiplicationAssignment,
+ AssignmentOp::DivisionAssignment,
+ AssignmentOp::ModuloAssignment,
+ AssignmentOp::ExponentiationAssignment,
+ AssignmentOp::LeftShiftAssignment,
+ AssignmentOp::RightShiftAssignment,
+ AssignmentOp::UnsignedRightShiftAssignment,
+ AssignmentOp::BitwiseAndAssignment,
+ AssignmentOp::BitwiseOrAssignment,
+ AssignmentOp::BitwiseXorAssignment,
+ AssignmentOp::AndAssignment,
+ AssignmentOp::OrAssignment,
+ AssignmentOp::NullishAssignment,
+];
+
+impl<'a> Expression<'a> {
+ /// The expression at `node`, which a pair of parentheses leaves as it is.
+ pub(crate) fn new(tree: &'a SyntaxTree, mut node: u32) -> Self {
+ while tree.tag(node) == tag::PAREN {
+ node = tree.a(node);
+ }
+ Self::with_form(tree, node, ExpressionForm::Node)
+ }
-#[derive(Clone, Debug)]
-pub struct ForStatementData {
- pub init: Option<ForInit>,
- pub test: Option<Box<Expression>>,
- pub update: Option<Box<Expression>>,
- pub body: Box<Statement>,
-}
+ fn with_form(tree: &'a SyntaxTree, node: u32, form: ExpressionForm) -> Self {
+ Self { tree, node, form }
+ }
-#[derive(Clone, Debug)]
-pub struct ForInOfStatementData {
- pub kind: ForInOfKind,
- pub lhs: ForInOfLhs,
- pub rhs: Box<Expression>,
- pub body: Box<Statement>,
-}
+ /// Where the expression starts in the source.
+ pub fn source_offset(&self) -> u32 {
+ let tree = self.tree;
+ match self.form {
+ ExpressionForm::Node if tree.tag(self.node) == tag::STR => tree.b(self.node),
+ ExpressionForm::MemberName => tree.name_after(tree.pos(self.node)),
+ ExpressionForm::ShorthandKey => tree.pos(tree.b(self.node)),
+ ExpressionForm::ShorthandValue { object_start } => object_start,
+ ExpressionForm::TemplateChunk { template_start, .. } if self.is_failed_template_chunk() => template_start,
+ _ => tree.pos(self.node),
+ }
+ }
-#[derive(Clone, Debug)]
-pub struct WithStatementData {
- pub object: Box<Expression>,
- pub body: Box<Statement>,
-}
+ pub fn range(&self) -> SourceRange {
+ self.tree.range(self.source_offset())
+ }
-#[derive(Clone, Debug)]
-pub struct LabelledStatementData {
- pub label: Utf16String,
- pub item: Box<Statement>,
-}
+ fn is_failed_template_chunk(&self) -> bool {
+ let ExpressionForm::TemplateChunk { is_tagged: true, .. } = self.form else {
+ return false;
+ };
+ literals::process_escape_sequences_impl(template_chunk_units(self.tree, self.node), EscapeMode::TaggedTemplate)
+ .failed
+ }
-#[derive(Clone, Debug)]
-pub struct VariableDeclarationData {
- pub kind: DeclarationKind,
- pub declarations: Vec<VariableDeclarator>,
-}
+ fn template(&self, is_tagged: bool) -> TemplateLiteralData<'a> {
+ let tree = self.tree;
+ let items = tree.list(tree.a(self.node));
+ TemplateLiteralData {
+ tree,
+ items,
+ expressions: List::of_items(
+ tree,
+ items,
+ TemplateElementContext {
+ is_tagged,
+ template_start: tree.pos(self.node),
+ },
+ ),
+ }
+ }
-/// A `using` or an `await using` declaration.
-#[derive(Clone, Debug)]
-pub struct UsingDeclarationData {
- pub is_await: bool,
- pub declarations: Vec<VariableDeclarator>,
-}
+ pub fn kind(&self) -> ExpressionKind<'a> {
+ let tree = self.tree;
+ let node = self.node;
+ let (a, b) = (tree.a(node), tree.b(node));
+ match self.form {
+ ExpressionForm::Node => {}
+ ExpressionForm::PropertyKeyName => {
+ return ExpressionKind::StringLiteral(StringLiteral::Name(tree.name_text(Name(a))));
+ }
+ ExpressionForm::MemberName => {
+ let offset = tree.name_after(tree.pos(node));
+ return if tree.tag(node) == tag::MEMBER {
+ ExpressionKind::Identifier(tree.plain_identifier(Name(b), offset))
+ } else {
+ ExpressionKind::PrivateIdentifier(tree.private_identifier(b, offset))
+ };
+ }
+ ExpressionForm::ShorthandKey => {
+ return ExpressionKind::StringLiteral(StringLiteral::Name(tree.name_text(Name(a))));
+ }
+ ExpressionForm::ShorthandValue { object_start } => {
+ return ExpressionKind::Identifier(tree.identifier(Name(a), object_start, node));
+ }
+ ExpressionForm::TemplateChunk { is_tagged, .. } => {
+ return if self.is_failed_template_chunk() {
+ ExpressionKind::NullLiteral
+ } else {
+ let mode = if is_tagged {
+ EscapeMode::TaggedTemplate
+ } else {
+ EscapeMode::StringLiteral
+ };
+ ExpressionKind::StringLiteral(StringLiteral::Source(template_chunk_units(tree, node), mode))
+ };
+ }
+ ExpressionForm::TaggedTemplate => return ExpressionKind::TemplateLiteral(self.template(true)),
+ ExpressionForm::DefaultConstructor => {
+ return ExpressionKind::Function(FunctionId {
+ node,
+ source: FunctionSource::DefaultConstructor,
+ });
+ }
+ ExpressionForm::DefaultConstructorSuperCall => {
+ return ExpressionKind::SuperCall(SuperCallData {
+ arguments: CallArguments::DefaultConstructorSpread(CallArgument {
+ value: Expression::with_form(tree, node, ExpressionForm::DefaultConstructorArgument),
+ is_spread: true,
+ }),
+ is_synthetic: true,
+ });
+ }
+ ExpressionForm::DefaultConstructorArgument => {
+ return ExpressionKind::Identifier(
+ tree.plain_identifier(tree.script.default_constructor_parameter_name, tree.pos(node)),
+ );
+ }
+ }
+ let node_tag = tree.tag(node);
+ let start = tree.pos(node);
+ match node_tag {
+ tag::IDENT => ExpressionKind::Identifier(tree.identifier(Name(a), start, node)),
+ tag::NUM => ExpressionKind::NumericLiteral(NumericLiteral {
+ text: tree.source_units(start, a),
+ }),
+ tag::BIGINT => ExpressionKind::BigIntLiteral(tree.source_units(start, a)),
+ tag::STR => ExpressionKind::StringLiteral(StringLiteral::Source(
+ tree.string_units(node),
+ EscapeMode::StringLiteral,
+ )),
+ tag::REGEX => ExpressionKind::RegExpLiteral(RegExpLiteralData {
+ pattern: tree.source_units(start + 1, a),
+ flags: tree.source_units(a + 1, b),
+ }),
+ tag::TRUE => ExpressionKind::BooleanLiteral(true),
+ tag::FALSE => ExpressionKind::BooleanLiteral(false),
+ tag::NULL => ExpressionKind::NullLiteral,
+ tag::THIS => ExpressionKind::This,
+ tag::SUPER => ExpressionKind::Super,
+ tag::NEW_TARGET => ExpressionKind::MetaProperty(MetaPropertyType::NewTarget),
+ tag::IMPORT_META => ExpressionKind::MetaProperty(MetaPropertyType::ImportMeta),
+ tag::PRIVATE_NAME => ExpressionKind::PrivateIdentifier(tree.private_identifier(a, start)),
+ tag::FUNCTION => ExpressionKind::Function(FunctionId::function(node)),
+ tag::MEMBER | tag::PRIVATE_MEMBER => ExpressionKind::Member(MemberExpressionData {
+ object: Expression::new(tree, a),
+ property: Expression::with_form(tree, node, ExpressionForm::MemberName),
+ computed: false,
+ }),
+ tag::INDEX => ExpressionKind::Member(MemberExpressionData {
+ object: Expression::new(tree, a),
+ property: Expression::new(tree, b),
+ computed: true,
+ }),
+ tag::CHAIN => ExpressionKind::OptionalChain(OptionalChainData { tree, node: a }),
+ tag::SPREAD => ExpressionKind::Spread(Expression::new(tree, a)),
+ tag::YIELD | tag::YIELD_STAR => ExpressionKind::Yield(YieldExpressionData {
+ argument: (a != 0).then(|| Expression::new(tree, a)),
+ is_yield_from: node_tag == tag::YIELD_STAR,
+ }),
+ tag::AWAIT => ExpressionKind::Await(Expression::new(tree, a)),
+ tag::CONDITIONAL => ExpressionKind::Conditional(ConditionalExpressionData {
+ test: Expression::new(tree, a),
+ consequent: Expression::new(tree, tree.extra(b)),
+ alternate: Expression::new(tree, tree.extra(b + 1)),
+ }),
+ tag::UNARY => {
+ let op = match b {
+ token if token == T::Not as u32 => UnaryOp::Not,
+ token if token == T::Tilde as u32 => UnaryOp::BitwiseNot,
+ token if token == T::Plus as u32 => UnaryOp::Plus,
+ token if token == T::Minus as u32 => UnaryOp::Minus,
+ token if token == T::KTypeof as u32 => UnaryOp::Typeof,
+ token if token == T::KVoid as u32 => UnaryOp::Void,
+ _ => UnaryOp::Delete,
+ };
+ ExpressionKind::Unary {
+ op,
+ operand: Expression::new(tree, a),
+ }
+ }
+ tag::PREFIX_UPDATE | tag::POSTFIX_UPDATE => ExpressionKind::Update(UpdateExpressionData {
+ op: if b == T::Inc as u32 {
+ UpdateOp::Increment
+ } else {
+ UpdateOp::Decrement
+ },
+ argument: Expression::new(tree, a),
+ prefixed: node_tag == tag::PREFIX_UPDATE,
+ }),
+ tag::TAGGED_TEMPLATE => ExpressionKind::TaggedTemplateLiteral(TaggedTemplateData {
+ tag: Expression::new(tree, a),
+ template_literal: Expression::with_form(tree, b, ExpressionForm::TaggedTemplate),
+ }),
+ tag::IMPORT_CALL => ExpressionKind::ImportCall(ImportCallData {
+ specifier: Expression::new(tree, a),
+ options: (b != 0).then(|| Expression::new(tree, b)),
+ }),
+ tag::CALL if tree.tag(a) == tag::SUPER => ExpressionKind::SuperCall(SuperCallData {
+ arguments: CallArguments::List(List::new(tree, b, ())),
+ is_synthetic: false,
+ }),
+ tag::CALL | tag::NEW => {
+ let data = CallExpressionData {
+ callee: Expression::new(tree, a),
+ arguments: CallArguments::List(List::new(tree, b, ())),
+ };
+ if node_tag == tag::CALL {
+ ExpressionKind::Call(data)
+ } else {
+ ExpressionKind::New(data)
+ }
+ }
+ tag::ARRAY => ExpressionKind::Array(List::new(tree, a, ())),
+ tag::OBJECT => ExpressionKind::Object(List::new(tree, a, start)),
+ tag::SEQUENCE => ExpressionKind::Sequence(List::new(tree, a, ())),
+ tag::TEMPLATE => ExpressionKind::TemplateLiteral(self.template(false)),
+ tag::CLASS => ExpressionKind::Class(tree.class(node)),
+ tag::ASSIGN_PATTERN => self.assignment(0, a, b),
+ _ if node_tag >= tag::BINARY_BASE => self.binary(node_tag - tag::BINARY_BASE, a, b),
+ _ if node_tag >= tag::ASSIGN_BASE => self.assignment(node_tag - tag::ASSIGN_BASE, a, b),
+ other => unreachable!("tag {other} is no expression"),
+ }
+ }
-#[derive(Clone, Debug)]
-pub struct FunctionDeclarationData {
- pub function_id: FunctionId,
- pub name: Option<IdentifierId>,
- pub kind: FunctionKind,
- pub is_hoisted: bool,
-}
+ fn binary(&self, operator: u8, a: u32, b: u32) -> ExpressionKind<'a> {
+ let lhs = Expression::new(self.tree, a);
+ let rhs = Expression::new(self.tree, b);
+ match BINARY_OPERATORS[operator as usize] {
+ Some(op) => ExpressionKind::Binary(BinaryExpressionData { op, lhs, rhs }),
+ None => {
+ let op = match operator {
+ 0 => LogicalOp::NullishCoalescing,
+ 1 => LogicalOp::Or,
+ _ => LogicalOp::And,
+ };
+ ExpressionKind::Logical(LogicalExpressionData { op, lhs, rhs })
+ }
+ }
+ }
-#[derive(Clone, Debug)]
-pub struct ClassFieldInitializerData {
- pub expression: Box<Expression>,
- /// The name of the field, unless its key is computed.
- pub field_name: Option<Utf16String>,
+ fn assignment(&self, operator: u8, a: u32, b: u32) -> ExpressionKind<'a> {
+ let tree = self.tree;
+ let lhs = if matches!(tree.tag(a), tag::ARRAY_PATTERN | tag::OBJECT_PATTERN) {
+ AssignmentLhs::Pattern(BindingPattern::new(tree, a, PatternMode::Assignment))
+ } else {
+ AssignmentLhs::Expression(Expression::new(tree, a))
+ };
+ ExpressionKind::Assignment(AssignmentExpressionData {
+ op: ASSIGNMENT_OPERATORS[operator as usize],
+ lhs,
+ rhs: Expression::new(tree, b),
+ lhs_is_parenthesized: tree.tag(a) == tag::PAREN,
+ })
+ }
}
// =============================================================================
-// Statement enum
+// Statements
// =============================================================================
-#[derive(Clone, Debug)]
-pub enum StatementKind {
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum StatementForm {
+ /// The statement that the node's tag says.
+ Node,
+ /// The body of a function node.
+ FunctionBody,
+ /// The `return` that the expression of an arrow function node means.
+ ExpressionBodyReturn,
+ /// The body of a static block node.
+ StaticBlockBody { class_start: u32 },
+ /// The expression of `export default` at the node.
+ ExportedExpression,
+ /// The declaration of `export default` of a function node.
+ ExportedFunction,
+ /// The evaluation of the initializer of a class field node.
+ ClassFieldInitializer,
+ /// The body of the default constructor of a class node.
+ DefaultConstructorBody,
+ /// The `return super(...args)` of the default constructor of a class node.
+ DefaultConstructorReturn,
+}
+
+#[derive(Clone, Copy)]
+pub struct Statement<'a> {
+ tree: &'a SyntaxTree,
+ node: u32,
+ form: StatementForm,
+}
+
+#[derive(Clone, Copy)]
+pub enum StatementKind<'a> {
// Basic
Empty,
- Error,
- Expression(Box<Expression>),
+ Expression(Expression<'a>),
Debugger,
// Blocks (carry ScopeData for scope analysis)
- Block(ScopeId),
- FunctionBody { scope: ScopeId, in_strict_mode: bool },
- Program(Box<ProgramData>),
+ Block(Scope<'a>),
+ FunctionBody { scope: Scope<'a>, in_strict_mode: bool },
+ Program(ProgramData<'a>),
// Control flow
- If(Box<IfStatementData>),
- While(Box<WhileStatementData>),
- DoWhile(Box<WhileStatementData>),
- For(Box<ForStatementData>),
- ForInOf(Box<ForInOfStatementData>),
- Switch(Box<SwitchStatementData>),
- With(Box<WithStatementData>),
- Labelled(Box<LabelledStatementData>),
+ If(IfStatementData<'a>),
+ While(WhileStatementData<'a>),
+ DoWhile(WhileStatementData<'a>),
+ For(ForStatementData<'a>),
+ ForInOf(ForInOfStatementData<'a>),
+ Switch(SwitchStatementData<'a>),
+ With(WithStatementData<'a>),
+ Labelled(LabelledStatementData<'a>),
// Jumps
- Break { target_label: Option<Utf16String> },
- Continue { target_label: Option<Utf16String> },
- Return(Option<Box<Expression>>),
- Throw(Box<Expression>),
- Try(Box<TryStatementData>),
+ Break { target_label: Option<Utf16View<'a>> },
+ Continue { target_label: Option<Utf16View<'a>> },
+ Return(Option<Expression<'a>>),
+ Throw(Expression<'a>),
+ Try(TryStatementData<'a>),
// Declarations
- VariableDeclaration(Box<VariableDeclarationData>),
- UsingDeclaration(Box<UsingDeclarationData>),
- FunctionDeclaration(Box<FunctionDeclarationData>),
- ClassDeclaration(Box<ClassData>),
- ErrorDeclaration,
+ VariableDeclaration(VariableDeclarationData<'a>),
+ UsingDeclaration(UsingDeclarationData<'a>),
+ FunctionDeclaration(FunctionDeclarationData<'a>),
+ ClassDeclaration(ClassData<'a>),
// Module
- Import(Box<ImportStatementData>),
- Export(Box<ExportStatementData>),
+ Import(ImportStatementData<'a>),
+ Export(ExportStatementData<'a>),
// Special
- ClassFieldInitializer(Box<ClassFieldInitializerData>),
+ ClassFieldInitializer(ClassFieldInitializerData<'a>),
}
-impl StatementKind {
- pub fn function_declaration_for_labelled_item(&self) -> Option<&FunctionDeclarationData> {
- // https://tc39.es/ecma262/#sec-static-semantics-lexicallyscopeddeclarations
- // LabelledItem : FunctionDeclaration
- // 1. Return « |FunctionDeclaration| ».
- match self {
- StatementKind::FunctionDeclaration(function) => Some(function),
- StatementKind::Labelled(data) => data.item.inner.function_declaration_for_labelled_item(),
- _ => None,
+impl<'a> Statement<'a> {
+ pub(crate) fn new(tree: &'a SyntaxTree, node: u32) -> Self {
+ Self::with_form(tree, node, StatementForm::Node)
+ }
+
+ fn with_form(tree: &'a SyntaxTree, node: u32, form: StatementForm) -> Self {
+ Self { tree, node, form }
+ }
+
+ /// Where the statement starts in the source.
+ pub fn source_offset(&self) -> u32 {
+ let tree = self.tree;
+ let node = self.node;
+ match self.form {
+ StatementForm::Node => match tree.tag(node) {
+ tag::PROGRAM => tree.first_token_start,
+ tag::FUNCTION_DECL => tree.pos(tree.a(node)),
+ _ => tree.pos(node),
+ },
+ StatementForm::FunctionBody => {
+ let function_tree = tree.a(node);
+ if tree.extra(function_tree + 6) != 0 {
+ tree.pos(node)
+ } else {
+ tree.extra(function_tree + 5)
+ }
+ }
+ StatementForm::StaticBlockBody { class_start } => class_start,
+ StatementForm::ExportedExpression => Expression::new(tree, node).source_offset(),
+ StatementForm::ClassFieldInitializer => Expression::new(tree, tree.a(tree.b(node))).source_offset(),
+ StatementForm::ExpressionBodyReturn
+ | StatementForm::ExportedFunction
+ | StatementForm::DefaultConstructorBody
+ | StatementForm::DefaultConstructorReturn => tree.pos(node),
}
}
- pub fn function_declaration_for_labelled_item_mut(&mut self) -> Option<&mut FunctionDeclarationData> {
- match self {
+ pub fn range(&self) -> SourceRange {
+ let tree = self.tree;
+ let node = self.node;
+ match self.form {
+ StatementForm::Node if tree.tag(node) == tag::BLOCK => {
+ tree.range_between(tree.pos(node), tree.block_end(tree.a(node)))
+ }
+ StatementForm::StaticBlockBody { class_start } => {
+ tree.range_between(class_start, tree.block_end(tree.a(node)))
+ }
+ StatementForm::ClassFieldInitializer => {
+ let initializer = tree.b(node);
+ let mut range = Expression::new(tree, tree.a(initializer)).range();
+ range.end = tree.script.positions.lines.position(tree.pos(initializer));
+ range
+ }
+ _ => tree.range(self.source_offset()),
+ }
+ }
+
+ fn function_scope(&self, children: ScopeChildren<'a>) -> Scope<'a> {
+ Scope::of_function(self.tree, children, self.tree.function_scope(self.node))
+ }
+
+ fn static_block_scope(&self) -> Scope<'a> {
+ let tree = self.tree;
+ let row = tree.scope_row(tree.resolution(self.node).0);
+ Scope::of_function(tree, ScopeChildren::List(List::new(tree, tree.a(self.node), ())), row)
+ }
+
+ fn loop_kind(&self) -> StatementKind<'a> {
+ let tree = self.tree;
+ let node = self.node;
+ let (a, b) = (tree.a(node), tree.b(node));
+ let is_declaration = |node: u32| {
+ matches!(
+ tree.tag(node),
+ tag::VAR | tag::LET | tag::CONST | tag::USING | tag::AWAIT_USING
+ )
+ };
+ match tree.tag(node) {
+ tag::FOR => {
+ let (test, update, body) = (tree.extra(b), tree.extra(b + 1), tree.extra(b + 2));
+ StatementKind::For(ForStatementData {
+ init: (a != 0).then(|| {
+ if is_declaration(a) {
+ ForInit::Declaration(Statement::new(tree, a))
+ } else {
+ ForInit::Expression(Expression::new(tree, a))
+ }
+ }),
+ test: (test != 0).then(|| Expression::new(tree, test)),
+ update: (update != 0).then(|| Expression::new(tree, update)),
+ body: Statement::new(tree, body),
+ })
+ }
+ other => {
+ let kind = match other {
+ tag::FOR_IN => ForInOfKind::ForIn,
+ tag::FOR_OF => ForInOfKind::ForOf,
+ _ => ForInOfKind::ForAwaitOf,
+ };
+ let (right, body) = (tree.extra(b), tree.extra(b + 1));
+ let lhs = if matches!(tree.tag(a), tag::ARRAY_PATTERN | tag::OBJECT_PATTERN) {
+ ForInOfLhs::Pattern(BindingPattern::new(tree, a, PatternMode::Assignment))
+ } else if is_declaration(a) {
+ ForInOfLhs::Declaration(Statement::new(tree, a))
+ } else {
+ ForInOfLhs::Expression(Expression::new(tree, a))
+ };
+ StatementKind::ForInOf(ForInOfStatementData {
+ kind,
+ lhs,
+ rhs: Expression::new(tree, right),
+ body: Statement::new(tree, body),
+ })
+ }
+ }
+ }
+
+ fn export_kind(&self) -> StatementKind<'a> {
+ let tree = self.tree;
+ let node = self.node;
+ let (a, b) = (tree.a(node), tree.b(node));
+ let (statement, is_default_export) = match tree.tag(node) {
+ tag::EXPORT_ALL => (None, false),
+ tag::EXPORT_DEFAULT => {
+ let inner_tag = tree.tag(a);
+ let statement = if inner_tag == tag::FUNCTION && b != 0 {
+ Statement::with_form(tree, a, StatementForm::ExportedFunction)
+ } else if inner_tag == tag::CLASS_DECL {
+ Statement::new(tree, a)
+ } else {
+ Statement::with_form(tree, a, StatementForm::ExportedExpression)
+ };
+ (Some(statement), true)
+ }
+ _ if a != 0 => (None, false),
+ _ => (Some(Statement::new(tree, b)), false),
+ };
+ StatementKind::Export(ExportStatementData {
+ tree,
+ node,
+ statement,
+ is_default_export,
+ })
+ }
+
+ pub fn kind(&self) -> StatementKind<'a> {
+ let tree = self.tree;
+ let node = self.node;
+ match self.form {
+ StatementForm::Node => {}
+ StatementForm::FunctionBody => {
+ let function_tree = tree.a(node);
+ let body = tree.extra(function_tree + 1);
+ let is_expression = tree.extra(function_tree + 6) != 0;
+ let children = if is_expression {
+ ScopeChildren::One(Statement::with_form(tree, node, StatementForm::ExpressionBodyReturn))
+ } else {
+ ScopeChildren::List(List::new(tree, body, ()))
+ };
+ return StatementKind::FunctionBody {
+ scope: self.function_scope(children),
+ in_strict_mode: tree.script.index.flags[tree.b(node) as usize] & function_flag::STRICT != 0,
+ };
+ }
+ StatementForm::ExpressionBodyReturn => {
+ return StatementKind::Return(Some(Expression::new(tree, tree.extra(tree.a(node) + 1))));
+ }
+ StatementForm::StaticBlockBody { .. } => {
+ return StatementKind::FunctionBody {
+ scope: self.static_block_scope(),
+ in_strict_mode: true,
+ };
+ }
+ StatementForm::ExportedExpression => return StatementKind::Expression(Expression::new(tree, node)),
+ StatementForm::ExportedFunction => {
+ let name = tree.script.index.name[tree.b(node) as usize];
+ return StatementKind::FunctionDeclaration(tree.function_declaration(node, name));
+ }
+ StatementForm::ClassFieldInitializer => {
+ return StatementKind::ClassFieldInitializer(ClassFieldInitializerData {
+ expression: Expression::new(tree, tree.a(tree.b(node))),
+ key: ClassElementNode {
+ tree,
+ node,
+ class_start: 0,
+ }
+ .property_key(tree.a(node), tree.tag(node) == tag::COMPUTED_CLASS_FIELD),
+ });
+ }
+ StatementForm::DefaultConstructorBody => {
+ let has_super_class = tree.extra(tree.b(node)) != 0;
+ return StatementKind::Block(Scope::new(
+ tree,
+ if has_super_class {
+ ScopeChildren::One(Statement::with_form(
+ tree,
+ node,
+ StatementForm::DefaultConstructorReturn,
+ ))
+ } else {
+ ScopeChildren::None
+ },
+ ));
+ }
+ StatementForm::DefaultConstructorReturn => {
+ return StatementKind::Return(Some(Expression::with_form(
+ tree,
+ node,
+ ExpressionForm::DefaultConstructorSuperCall,
+ )));
+ }
+ }
+ let (a, b) = (tree.a(node), tree.b(node));
+ match tree.tag(node) {
+ tag::PROGRAM => StatementKind::Program(ProgramData {
+ scope: Scope::of_function(
+ tree,
+ ScopeChildren::List(List::new(tree, a, ())),
+ tree.scope_row(tree.program_scope_row),
+ ),
+ program_type: tree.program_type(),
+ is_strict_mode: tree.is_strict_mode,
+ has_top_level_await: tree.has_top_level_await,
+ }),
+ tag::EMPTY => StatementKind::Empty,
+ tag::DEBUGGER => StatementKind::Debugger,
+ tag::EXPR_STMT => StatementKind::Expression(Expression::new(tree, a)),
+ tag::SCOPED => StatementKind::Block(Scope::new(tree, ScopeChildren::One(Statement::new(tree, a)))),
+ tag::FOR | tag::FOR_IN | tag::FOR_OF | tag::FOR_AWAIT_OF => self.loop_kind(),
+ tag::IF_FUNCTION_BLOCK => {
+ StatementKind::Block(Scope::new(tree, ScopeChildren::One(Statement::new(tree, a))))
+ }
+ tag::BLOCK => StatementKind::Block(Scope::of_list(tree, a)),
+ tag::IF => {
+ let (consequent, alternate) = (tree.extra(b), tree.extra(b + 1));
+ StatementKind::If(IfStatementData {
+ test: Expression::new(tree, a),
+ consequent: Statement::new(tree, consequent),
+ alternate: (alternate != 0).then(|| Statement::new(tree, alternate)),
+ })
+ }
+ tag::WHILE => StatementKind::While(WhileStatementData {
+ test: Expression::new(tree, a),
+ body: Statement::new(tree, b),
+ }),
+ tag::DO_WHILE => StatementKind::DoWhile(WhileStatementData {
+ test: Expression::new(tree, b),
+ body: Statement::new(tree, a),
+ }),
+ tag::SWITCH => StatementKind::Switch(SwitchStatementData {
+ discriminant: Expression::new(tree, a),
+ cases: List::new(tree, tree.extra(b), ()),
+ }),
+ tag::WITH => StatementKind::With(WithStatementData {
+ object: Expression::new(tree, a),
+ body: Statement::new(tree, tree.extra(b)),
+ }),
+ tag::LABELED => StatementKind::Labelled(LabelledStatementData {
+ label: tree.name_text(Name(a)),
+ item: Statement::new(tree, b),
+ }),
+ tag::BREAK => StatementKind::Break {
+ target_label: (a != NONE).then(|| tree.name_text(Name(a))),
+ },
+ tag::CONTINUE => StatementKind::Continue {
+ target_label: (a != NONE).then(|| tree.name_text(Name(a))),
+ },
+ tag::RETURN => StatementKind::Return((a != 0).then(|| Expression::new(tree, a))),
+ tag::THROW => StatementKind::Throw(Expression::new(tree, a)),
+ tag::TRY => {
+ let (parameter, handler, finalizer) = (tree.extra(b), tree.extra(b + 1), tree.extra(b + 2));
+ StatementKind::Try(TryStatementData {
+ block: Statement::new(tree, a),
+ handler: (handler != 0).then(|| CatchClause {
+ tree,
+ offset: tree.extra(b + 3),
+ parameter: (parameter != 0).then(|| {
+ if tree.tag(parameter) == tag::IDENT {
+ CatchBinding::Identifier(tree.identifier(
+ Name(tree.a(parameter)),
+ tree.pos(parameter),
+ parameter,
+ ))
+ } else {
+ CatchBinding::BindingPattern(BindingPattern::new(tree, parameter, PatternMode::Binding))
+ }
+ }),
+ body: Statement::new(tree, handler),
+ }),
+ finalizer: (finalizer != 0).then(|| Statement::new(tree, finalizer)),
+ })
+ }
+ node_tag @ (tag::VAR | tag::LET | tag::CONST | tag::USING | tag::AWAIT_USING) => {
+ let declarations = List::new(tree, a, tree.pos(node));
+ match node_tag {
+ tag::USING | tag::AWAIT_USING => StatementKind::UsingDeclaration(UsingDeclarationData {
+ is_await: node_tag == tag::AWAIT_USING,
+ declarations,
+ }),
+ _ => StatementKind::VariableDeclaration(VariableDeclarationData {
+ kind: match node_tag {
+ tag::VAR => DeclarationKind::Var,
+ tag::LET => DeclarationKind::Let,
+ _ => DeclarationKind::Const,
+ },
+ declarations,
+ }),
+ }
+ }
+ tag::FUNCTION_DECL => StatementKind::FunctionDeclaration(tree.function_declaration(a, b)),
+ tag::CLASS_DECL => StatementKind::ClassDeclaration(tree.class(a)),
+ tag::IMPORT => StatementKind::Import(ImportStatementData { tree, node }),
+ tag::EXPORT_ALL | tag::EXPORT_DEFAULT | tag::EXPORT_NAMED => self.export_kind(),
+ other => unreachable!("tag {other} is no statement"),
+ }
+ }
+
+ pub fn function_declaration_for_labelled_item(&self) -> Option<FunctionDeclarationData<'a>> {
+ // https://tc39.es/ecma262/#sec-static-semantics-lexicallyscopeddeclarations
+ // LabelledItem : FunctionDeclaration
+ // 1. Return « |FunctionDeclaration| ».
+ match self.kind() {
StatementKind::FunctionDeclaration(function) => Some(function),
- StatementKind::Labelled(data) => data.item.inner.function_declaration_for_labelled_item_mut(),
+ StatementKind::Labelled(data) => data.item.function_declaration_for_labelled_item(),
_ => None,
}
}
}
-// =============================================================================
-// Program data
-// =============================================================================
-
-#[derive(Clone, Debug)]
-pub struct ProgramData {
- pub scope: ScopeId,
- pub program_type: ProgramType,
- pub is_strict_mode: bool,
- pub has_top_level_await: bool,
-}
+impl_sequence_into_iterator!(FunctionParameters, ClassElements, ScopeChildren, CallArguments);
diff --git a/Libraries/LibJS/Rust/src/ast_dump.rs b/Libraries/LibJS/Rust/src/ast_dump.rs
index ed36be5c0af..1bd9c9dd222 100644
--- a/Libraries/LibJS/Rust/src/ast_dump.rs
+++ b/Libraries/LibJS/Rust/src/ast_dump.rs
@@ -9,6 +9,7 @@
//! Produces tree-drawing output to stdout via `println!`.
use crate::ast::*;
+use crate::utf16::Utf16View;
use std::cell::RefCell;
use std::fmt::Write;
@@ -59,20 +60,7 @@ struct DumpState<'a> {
is_root: bool,
use_color: bool,
output: Option<&'a RefCell<String>>,
- function_table: &'a FunctionTable,
- arena: &'a crate::ast::AstArena,
-}
-
-impl DumpState<'_> {
- fn function_table(&self) -> &FunctionTable {
- self.function_table
- }
- fn identifier(&self, id: crate::ast::IdentifierId) -> &crate::ast::Identifier {
- &self.arena.identifiers[id]
- }
- fn name_slice(&self, id: crate::ast::IdentifierId) -> &[u16] {
- self.arena.name_slice(id)
- }
+ tree: &'a SyntaxTree,
}
fn print_node(state: &DumpState, text: &str) {
@@ -116,8 +104,7 @@ fn child_state<'a>(state: &DumpState<'a>, is_last: bool) -> DumpState<'a> {
is_root: false,
use_color: state.use_color,
output: state.output,
- function_table: state.function_table,
- arena: state.arena,
+ tree: state.tree,
}
}
@@ -146,7 +133,7 @@ fn color_string(state: &DumpState, value: &str) -> String {
format!("{GREEN}\"{value}\"{RESET}")
}
-fn color_string_utf16(state: &DumpState, value: &[u16]) -> String {
+fn color_string_utf16<'a>(state: &DumpState, value: impl Into<Utf16View<'a>>) -> String {
color_string(state, &utf16_to_string(value))
}
@@ -210,8 +197,8 @@ fn color_flag(state: &DumpState, flag: &str) -> String {
}
/// Convert UTF-16 to a valid UTF-8 string, replacing lone surrogates with U+FFFD.
-fn utf16_to_string(s: &[u16]) -> String {
- char::decode_utf16(s.iter().copied())
+fn utf16_to_string<'a>(s: impl Into<Utf16View<'a>>) -> String {
+ char::decode_utf16(s.into().code_units())
.map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
.collect()
}
@@ -282,30 +269,7 @@ fn dump_labeled_statement(label: &str, statement: &Statement, is_last: bool, sta
// Entry point
// ============================================================================
-pub fn dump_program(
- program: &Statement,
- use_color: bool,
- function_table: &FunctionTable,
- arena: &crate::ast::AstArena,
-) {
- let state = DumpState {
- prefix: String::new(),
- is_last: false,
- is_root: true,
- use_color,
- output: None,
- function_table,
- arena,
- };
- dump_statement(program, &state);
- println!();
-}
-
-pub fn dump_program_to_string(
- program: &Statement,
- function_table: &FunctionTable,
- arena: &crate::ast::AstArena,
-) -> String {
+pub fn dump_program_to_string(tree: &SyntaxTree) -> String {
let output = RefCell::new(String::new());
let state = DumpState {
prefix: String::new(),
@@ -313,10 +277,9 @@ pub fn dump_program_to_string(
is_root: true,
use_color: false,
output: Some(&output),
- function_table,
- arena,
+ tree,
};
- dump_statement(program, &state);
+ dump_statement(&tree.program(), &state);
output.into_inner()
}
@@ -325,39 +288,43 @@ pub fn dump_program_to_string(
// ============================================================================
fn dump_statement(statement: &Statement, state: &DumpState) {
- match &statement.inner {
+ match &statement.kind() {
StatementKind::Empty => {
- dump_node!(state, "EmptyStatement", &statement.range);
+ dump_node!(state, "EmptyStatement", &statement.range());
}
StatementKind::Debugger => {
- dump_node!(state, "DebuggerStatement", &statement.range);
+ dump_node!(state, "DebuggerStatement", &statement.range());
}
StatementKind::Expression(expression) => {
- dump_node!(state, "ExpressionStatement", &statement.range);
+ dump_node!(state, "ExpressionStatement", &statement.range());
dump_expression(expression, &child_state(state, true));
}
StatementKind::Block(scope) => {
- let s = &state.arena.scopes[*scope];
+ let s = scope;
// The parser wraps for-loops in a Block for scope. The dump does
// not show it, so skip the wrapper and dump the child directly.
- if s.children.len() == 1 && matches!(s.children[0].inner, StatementKind::For(_) | StatementKind::ForInOf(_))
+ if s.children.len() == 1
+ && matches!(
+ s.children.at(0).kind(),
+ StatementKind::For(_) | StatementKind::ForInOf(_)
+ )
{
- dump_statement(&s.children[0], state);
+ dump_statement(&s.children.at(0), state);
return;
}
- dump_scope_node("BlockStatement", s, &statement.range, state);
+ dump_scope_node("BlockStatement", s, &statement.range(), state);
}
StatementKind::FunctionBody { scope, .. } => {
- let s = &state.arena.scopes[*scope];
- dump_scope_node("FunctionBody", s, &statement.range, state);
+ let s = scope;
+ dump_scope_node("FunctionBody", s, &statement.range(), state);
}
StatementKind::Program(data) => {
- let scope = &state.arena.scopes[data.scope];
+ let scope = &data.scope;
let mut desc = color_node_name(state, "Program");
let type_str = if data.program_type == ProgramType::Module {
"module"
@@ -371,16 +338,16 @@ fn dump_statement(statement: &Statement, state: &DumpState) {
if data.has_top_level_await {
desc.push_str(&format!(" {}", color_flag(state, "top-level-await")));
}
- desc.push_str(&format_position(state, &statement.range));
+ desc.push_str(&format_position(state, &statement.range()));
print_node(state, &desc);
let children = &scope.children;
for (i, child) in children.iter().enumerate() {
- dump_statement(child, &child_state(state, i == children.len() - 1));
+ dump_statement(&child, &child_state(state, i == children.len() - 1));
}
}
StatementKind::If(data) => {
- dump_node!(state, "IfStatement", &statement.range);
+ dump_node!(state, "IfStatement", &statement.range());
let has_alternate = data.alternate.is_some();
dump_labeled_expression("test", &data.test, false, state);
dump_labeled_statement("consequent", &data.consequent, !has_alternate, state);
@@ -390,19 +357,19 @@ fn dump_statement(statement: &Statement, state: &DumpState) {
}
StatementKind::While(data) => {
- dump_node!(state, "WhileStatement", &statement.range);
+ dump_node!(state, "WhileStatement", &statement.range());
dump_labeled_expression("test", &data.test, false, state);
dump_labeled_statement("body", &data.body, true, state);
}
StatementKind::DoWhile(data) => {
- dump_node!(state, "DoWhileStatement", &statement.range);
+ dump_node!(state, "DoWhileStatement", &statement.range());
dump_labeled_statement("body", &data.body, false, state);
dump_labeled_expression("test", &data.test, true, state);
}
StatementKind::For(data) => {
- dump_node!(state, "ForStatement", &statement.range);
+ dump_node!(state, "ForStatement", &statement.range());
if let Some(init) = &data.init {
let init_state = child_state(state, false);
print_node(&init_state, &color_label(state, "init"));
@@ -430,7 +397,7 @@ fn dump_statement(statement: &Statement, state: &DumpState) {
ForInOfKind::ForOf => "ForOfStatement",
ForInOfKind::ForAwaitOf => "ForAwaitOfStatement",
};
- dump_node!(state, name, &statement.range);
+ dump_node!(state, name, &statement.range());
let lhs_state = child_state(state, false);
print_node(&lhs_state, &color_label(state, "lhs"));
dump_for_in_of_lhs(&data.lhs, &child_state(&lhs_state, true));
@@ -439,15 +406,15 @@ fn dump_statement(statement: &Statement, state: &DumpState) {
}
StatementKind::Switch(data) => {
- dump_node!(state, "SwitchStatement", &statement.range);
+ dump_node!(state, "SwitchStatement", &statement.range());
dump_labeled_expression("discriminant", &data.discriminant, data.cases.is_empty(), state);
for (i, case) in data.cases.iter().enumerate() {
- dump_switch_case(case, &child_state(state, i == data.cases.len() - 1), state);
+ dump_switch_case(&case, &child_state(state, i == data.cases.len() - 1), state);
}
}
StatementKind::With(data) => {
- dump_node!(state, "WithStatement", &statement.range);
+ dump_node!(state, "WithStatement", &statement.range());
dump_labeled_expression("object", &data.object, false, state);
dump_labeled_statement("body", &data.body, true, state);
}
@@ -456,34 +423,34 @@ fn dump_statement(statement: &Statement, state: &DumpState) {
dump_node!(
state,
"LabelledStatement",
- &statement.range,
- color_string_utf16(state, &data.label)
+ &statement.range(),
+ color_string_utf16(state, data.label)
);
dump_statement(&data.item, &child_state(state, true));
}
StatementKind::Break { .. } => {
- dump_node!(state, "BreakStatement", &statement.range);
+ dump_node!(state, "BreakStatement", &statement.range());
}
StatementKind::Continue { .. } => {
- dump_node!(state, "ContinueStatement", &statement.range);
+ dump_node!(state, "ContinueStatement", &statement.range());
}
StatementKind::Return(argument) => {
- dump_node!(state, "ReturnStatement", &statement.range);
+ dump_node!(state, "ReturnStatement", &statement.range());
if let Some(argument) = argument {
dump_expression(argument, &child_state(state, true));
}
}
StatementKind::Throw(argument) => {
- dump_node!(state, "ThrowStatement", &statement.range);
+ dump_node!(state, "ThrowStatement", &statement.range());
dump_expression(argument, &child_state(state, true));
}
StatementKind::Try(data) => {
- dump_node!(state, "TryStatement", &statement.range);
+ dump_node!(state, "TryStatement", &statement.range());
let has_handler = data.handler.is_some();
let has_finalizer = data.finalizer.is_some();
dump_labeled_statement("block", &data.block, !has_handler && !has_finalizer, state);
@@ -501,12 +468,12 @@ fn dump_statement(statement: &Statement, state: &DumpState) {
dump_node!(
state,
"VariableDeclaration",
- &statement.range,
+ &statement.range(),
color_op(state, declaration_kind_to_string(data.kind))
);
for (i, declaration) in data.declarations.iter().enumerate() {
dump_variable_declarator(
- declaration,
+ &declaration,
&child_state(state, i == data.declarations.len() - 1),
state,
);
@@ -519,10 +486,10 @@ fn dump_statement(statement: &Statement, state: &DumpState) {
} else {
"UsingDeclaration"
};
- dump_node!(state, node_name, &statement.range);
+ dump_node!(state, node_name, &statement.range());
for (i, declaration) in data.declarations.iter().enumerate() {
dump_variable_declarator(
- declaration,
+ &declaration,
&child_state(state, i == data.declarations.len() - 1),
state,
);
@@ -530,33 +497,33 @@ fn dump_statement(statement: &Statement, state: &DumpState) {
}
StatementKind::FunctionDeclaration(data) => {
- let function_data = state.function_table().get(data.function_id);
- dump_function(function_data, "FunctionDeclaration", &statement.range, state);
+ let function_data = state.tree.function(data.function_id);
+ dump_function(&function_data, "FunctionDeclaration", &statement.range(), state);
}
StatementKind::ClassDeclaration(class_data) => {
- dump_node!(state, "ClassDeclaration", &statement.range);
- dump_class(class_data, &statement.range, &child_state(state, true), state);
+ dump_node!(state, "ClassDeclaration", &statement.range());
+ dump_class(class_data, &statement.range(), &child_state(state, true), state);
}
StatementKind::Import(data) => {
- let module_spec = utf16_to_string(&data.module_request.module_specifier);
- let assert_clauses = format_assert_clauses(&data.module_request);
+ let module_spec = utf16_to_string(&data.module_request().module_specifier);
+ let assert_clauses = format_assert_clauses(&data.module_request());
dump_node!(
state,
"ImportStatement",
- &statement.range,
+ &statement.range(),
format!("from {}{}", color_string(state, &module_spec), assert_clauses)
);
- if !data.entries.is_empty() {
- for (i, entry) in data.entries.iter().enumerate() {
+ if !data.entries().is_empty() {
+ for (i, entry) in data.entries().iter().enumerate() {
let import_name = match &entry.import_name {
Some(name) => utf16_to_string(name),
None => "None".to_string(),
};
let local_name = utf16_to_string(&entry.local_name);
print_node(
- &child_state(state, i == data.entries.len() - 1),
+ &child_state(state, i == data.entries().len() - 1),
&format!("ImportName: {import_name}, LocalName: {local_name}"),
);
}
@@ -564,22 +531,22 @@ fn dump_statement(statement: &Statement, state: &DumpState) {
}
StatementKind::Export(data) => {
- dump_node!(state, "ExportStatement", &statement.range);
+ dump_node!(state, "ExportStatement", &statement.range());
let has_statement = data.statement.is_some();
- let has_entries = !data.entries.is_empty();
+ let has_entries = !data.entries().is_empty();
if has_entries {
print_node(&child_state(state, !has_statement), &color_label(state, "entries"));
let entries_state = child_state(state, !has_statement);
- for (i, entry) in data.entries.iter().enumerate() {
+ for (i, entry) in data.entries().iter().enumerate() {
let export_name = match &entry.export_name {
Some(name) => format!("\"{}\"", utf16_to_string(name)),
None => "null".to_string(),
};
// When the entry is a module re-export, the dump prints
// "null" for LocalName regardless of the stored value.
- let local_name = if data.module_request.is_some() {
+ let local_name = if data.module_request().is_some() {
"null".to_string()
} else {
match &entry.local_or_import_name {
@@ -588,14 +555,14 @@ fn dump_statement(statement: &Statement, state: &DumpState) {
}
};
let mut desc = format!("ExportName: {export_name}, LocalName: {local_name}");
- if let Some(ref module_request) = data.module_request {
+ if let Some(ref module_request) = data.module_request() {
desc.push_str(&format!(
", ModuleRequest: {}{}",
utf16_to_string(&module_request.module_specifier),
format_assert_clauses(module_request)
));
}
- print_node(&child_state(&entries_state, i == data.entries.len() - 1), &desc);
+ print_node(&child_state(&entries_state, i == data.entries().len() - 1), &desc);
}
}
@@ -605,7 +572,7 @@ fn dump_statement(statement: &Statement, state: &DumpState) {
// For `export default <expression>`, the dump shows the
// expression directly without an ExpressionStatement wrapper,
// so unwrap StatementKind::Expression here.
- if let StatementKind::Expression(ref expression) = statement.inner {
+ if let StatementKind::Expression(ref expression) = statement.kind() {
dump_expression(expression, inner_state);
} else {
dump_statement(statement, inner_state);
@@ -616,10 +583,6 @@ fn dump_statement(statement: &Statement, state: &DumpState) {
StatementKind::ClassFieldInitializer(_) => {
// This should not be dumped as it is never part of an actual AST.
}
-
- StatementKind::Error | StatementKind::ErrorDeclaration => {
- dump_node!(state, "ErrorStatement", &statement.range);
- }
}
}
@@ -628,13 +591,13 @@ fn dump_statement(statement: &Statement, state: &DumpState) {
// ============================================================================
fn dump_expression(expression: &Expression, state: &DumpState) {
- match &expression.inner {
+ match &expression.kind() {
ExpressionKind::NumericLiteral(value) => {
dump_node!(
state,
"NumericLiteral",
- &expression.range,
- color_number_f64(state, *value)
+ &expression.range(),
+ color_number_f64(state, value.value())
);
}
@@ -642,8 +605,8 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
dump_node!(
state,
"StringLiteral",
- &expression.range,
- color_string_utf16(state, value)
+ &expression.range(),
+ color_string_utf16(state, &value.value())
);
}
@@ -651,46 +614,46 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
dump_node!(
state,
"BooleanLiteral",
- &expression.range,
+ &expression.range(),
color_number_bool(state, *value)
);
}
ExpressionKind::NullLiteral => {
- dump_node!(state, "NullLiteral", &expression.range);
+ dump_node!(state, "NullLiteral", &expression.range());
}
ExpressionKind::BigIntLiteral(value) => {
- let value = utf16_to_string(&value.0);
+ let value = utf16_to_string(*value);
dump_node!(
state,
"BigIntLiteral",
- &expression.range,
+ &expression.range(),
color_number_str(state, &value)
);
}
ExpressionKind::RegExpLiteral(data) => {
- let pattern = utf16_to_string(&data.pattern);
- let flags = utf16_to_string(&data.flags);
+ let pattern = utf16_to_string(data.pattern);
+ let flags = utf16_to_string(data.flags);
dump_node!(
state,
"RegExpLiteral",
- &expression.range,
+ &expression.range(),
format!("/{}/{}", pattern, flags)
);
}
ExpressionKind::Identifier(ident) => {
- dump_identifier(state.identifier(*ident), &expression.range, state);
+ dump_identifier(ident, &expression.range(), state);
}
ExpressionKind::PrivateIdentifier(ident) => {
dump_node!(
state,
"PrivateIdentifier",
- &expression.range,
- color_string_utf16(state, &ident.name)
+ &expression.range(),
+ color_string_utf16(state, &ident.name())
);
}
@@ -698,7 +661,7 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
dump_node!(
state,
"BinaryExpression",
- &expression.range,
+ &expression.range(),
color_op(state, binary_op_to_string(data.op))
);
dump_expression(&data.lhs, &child_state(state, false));
@@ -709,7 +672,7 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
dump_node!(
state,
"LogicalExpression",
- &expression.range,
+ &expression.range(),
color_op(state, logical_op_to_string(data.op))
);
dump_expression(&data.lhs, &child_state(state, false));
@@ -720,7 +683,7 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
dump_node!(
state,
"UnaryExpression",
- &expression.range,
+ &expression.range(),
color_op(state, unary_op_to_string(*op))
);
dump_expression(operand, &child_state(state, true));
@@ -731,7 +694,7 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
dump_node!(
state,
"UpdateExpression",
- &expression.range,
+ &expression.range(),
format!("({}, {})", update_op_to_string(data.op), prefix_str)
);
dump_expression(&data.argument, &child_state(state, true));
@@ -741,7 +704,7 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
dump_node!(
state,
"AssignmentExpression",
- &expression.range,
+ &expression.range(),
color_op(state, assignment_op_to_string(data.op))
);
match &data.lhs {
@@ -756,16 +719,16 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
}
ExpressionKind::Conditional(data) => {
- dump_node!(state, "ConditionalExpression", &expression.range);
+ dump_node!(state, "ConditionalExpression", &expression.range());
dump_labeled_expression("test", &data.test, false, state);
dump_labeled_expression("consequent", &data.consequent, false, state);
dump_labeled_expression("alternate", &data.alternate, true, state);
}
ExpressionKind::Sequence(expressions) => {
- dump_node!(state, "SequenceExpression", &expression.range);
+ dump_node!(state, "SequenceExpression", &expression.range());
for (i, child) in expressions.iter().enumerate() {
- dump_expression(child, &child_state(state, i == expressions.len() - 1));
+ dump_expression(&child, &child_state(state, i == expressions.len() - 1));
}
}
@@ -775,16 +738,16 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
} else {
"MemberExpression"
};
- dump_node!(state, name, &expression.range);
+ dump_node!(state, name, &expression.range());
dump_expression(&data.object, &child_state(state, false));
dump_expression(&data.property, &child_state(state, true));
}
ExpressionKind::OptionalChain(data) => {
- dump_node!(state, "OptionalChain", &expression.range);
- dump_expression(&data.base, &child_state(state, data.references.is_empty()));
- for (i, reference) in data.references.iter().enumerate() {
- let ref_state = child_state(state, i == data.references.len() - 1);
+ dump_node!(state, "OptionalChain", &expression.range());
+ dump_expression(&data.base(), &child_state(state, data.references().is_empty()));
+ for (i, reference) in data.references().iter().enumerate() {
+ let ref_state = child_state(state, i == data.references().len() - 1);
match reference {
OptionalChainReference::Call { arguments, mode } => {
print_node(&ref_state, &format!("Call({})", optional_mode_str(*mode)));
@@ -798,7 +761,7 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
}
OptionalChainReference::MemberReference { identifier, mode } => {
print_node(&ref_state, &format!("MemberReference({})", optional_mode_str(*mode)));
- dump_identifier_id(*identifier, &child_state(&ref_state, true));
+ dump_identifier_id(identifier, &child_state(&ref_state, true));
}
OptionalChainReference::PrivateMemberReference {
private_identifier,
@@ -813,8 +776,8 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
&format!(
"{} {}{}",
color_node_name(state, "PrivateIdentifier"),
- color_string_utf16(state, &private_identifier.name),
- format_position(state, &private_identifier.range)
+ color_string_utf16(state, &private_identifier.name()),
+ format_position(state, &private_identifier.range())
),
);
}
@@ -823,7 +786,7 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
}
ExpressionKind::Call(data) => {
- dump_node!(state, "CallExpression", &expression.range);
+ dump_node!(state, "CallExpression", &expression.range());
dump_expression(&data.callee, &child_state(state, data.arguments.is_empty()));
for (i, argument) in data.arguments.iter().enumerate() {
dump_expression(&argument.value, &child_state(state, i == data.arguments.len() - 1));
@@ -831,7 +794,7 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
}
ExpressionKind::New(data) => {
- dump_node!(state, "NewExpression", &expression.range);
+ dump_node!(state, "NewExpression", &expression.range());
dump_expression(&data.callee, &child_state(state, data.arguments.is_empty()));
for (i, argument) in data.arguments.iter().enumerate() {
dump_expression(&argument.value, &child_state(state, i == data.arguments.len() - 1));
@@ -839,40 +802,40 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
}
ExpressionKind::SuperCall(data) => {
- dump_node!(state, "SuperCall", &expression.range);
+ dump_node!(state, "SuperCall", &expression.range());
for (i, argument) in data.arguments.iter().enumerate() {
dump_expression(&argument.value, &child_state(state, i == data.arguments.len() - 1));
}
}
ExpressionKind::Spread(target) => {
- dump_node!(state, "SpreadExpression", &expression.range);
+ dump_node!(state, "SpreadExpression", &expression.range());
dump_expression(target, &child_state(state, true));
}
ExpressionKind::This => {
- dump_node!(state, "ThisExpression", &expression.range);
+ dump_node!(state, "ThisExpression", &expression.range());
}
ExpressionKind::Super => {
- dump_node!(state, "SuperExpression", &expression.range);
+ dump_node!(state, "SuperExpression", &expression.range());
}
ExpressionKind::Function(function_id) => {
- let function_data = state.function_table().get(*function_id);
- dump_function(function_data, "FunctionExpression", &expression.range, state);
+ let function_data = state.tree.function(*function_id);
+ dump_function(&function_data, "FunctionExpression", &expression.range(), state);
}
ExpressionKind::Class(class_data) => {
- dump_class(class_data, &expression.range, state, state);
+ dump_class(class_data, &expression.range(), state, state);
}
ExpressionKind::Array(elements) => {
- dump_node!(state, "ArrayExpression", &expression.range);
+ dump_node!(state, "ArrayExpression", &expression.range());
for (i, element) in elements.iter().enumerate() {
let cs = child_state(state, i == elements.len() - 1);
if let Some(element) = element {
- dump_expression(element, &cs);
+ dump_expression(&element, &cs);
} else {
print_node(&cs, "<elision>");
}
@@ -880,21 +843,21 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
}
ExpressionKind::Object(properties) => {
- dump_node!(state, "ObjectExpression", &expression.range);
+ dump_node!(state, "ObjectExpression", &expression.range());
for (i, property) in properties.iter().enumerate() {
- dump_object_property(property, &child_state(state, i == properties.len() - 1), state);
+ dump_object_property(&property, &child_state(state, i == properties.len() - 1), state);
}
}
ExpressionKind::TemplateLiteral(data) => {
- dump_node!(state, "TemplateLiteral", &expression.range);
+ dump_node!(state, "TemplateLiteral", &expression.range());
for (i, child) in data.expressions.iter().enumerate() {
- dump_expression(child, &child_state(state, i == data.expressions.len() - 1));
+ dump_expression(&child.0, &child_state(state, i == data.expressions.len() - 1));
}
}
ExpressionKind::TaggedTemplateLiteral(data) => {
- dump_node!(state, "TaggedTemplateLiteral", &expression.range);
+ dump_node!(state, "TaggedTemplateLiteral", &expression.range());
dump_labeled_expression("tag", &data.tag, false, state);
dump_labeled_expression("template", &data.template_literal, true, state);
}
@@ -904,11 +867,11 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
MetaPropertyType::NewTarget => "new.target",
MetaPropertyType::ImportMeta => "import.meta",
};
- dump_node!(state, "MetaProperty", &expression.range, name);
+ dump_node!(state, "MetaProperty", &expression.range(), name);
}
ExpressionKind::ImportCall(data) => {
- dump_node!(state, "ImportCall", &expression.range);
+ dump_node!(state, "ImportCall", &expression.range());
dump_expression(&data.specifier, &child_state(state, data.options.is_none()));
if let Some(ref opts) = data.options {
dump_labeled_expression("options", opts, true, state);
@@ -920,7 +883,7 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
if data.is_yield_from {
desc.push_str(&format!(" {}", color_flag(state, "yield*")));
}
- desc.push_str(&format_position(state, &expression.range));
+ desc.push_str(&format_position(state, &expression.range()));
print_node(state, &desc);
if let Some(ref argument) = data.argument {
dump_expression(argument, &child_state(state, true));
@@ -928,13 +891,9 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
}
ExpressionKind::Await(argument) => {
- dump_node!(state, "AwaitExpression", &expression.range);
+ dump_node!(state, "AwaitExpression", &expression.range());
dump_expression(argument, &child_state(state, true));
}
-
- ExpressionKind::Error => {
- dump_node!(state, "ErrorExpression", &expression.range);
- }
}
}
@@ -942,18 +901,13 @@ fn dump_expression(expression: &Expression, state: &DumpState) {
// Identifier dumper
// ============================================================================
-fn dump_identifier_id(id: crate::ast::IdentifierId, state: &DumpState) {
- let ident = state.identifier(id);
- let range = ident.range;
- dump_identifier(ident, &range, state);
+fn dump_identifier_id(ident: &Identifier, state: &DumpState) {
+ dump_identifier(ident, &ident.range(), state);
}
fn dump_identifier(ident: &Identifier, range: &SourceRange, state: &DumpState) {
let mut desc = color_node_name(state, "Identifier");
- desc.push_str(&format!(
- " {}",
- color_string_utf16(state, state.arena.strings[ident.name].as_slice())
- ));
+ desc.push_str(&format!(" {}", color_string_utf16(state, ident.text())));
if ident.is_local() {
let kind = if ident.local_type == Some(LocalType::Argument) {
"argument"
@@ -981,10 +935,10 @@ fn dump_identifier(ident: &Identifier, range: &SourceRange, state: &DumpState) {
// Helper dumpers
// ============================================================================
-fn dump_scope_node(class_name: &str, scope: &ScopeData, range: &SourceRange, state: &DumpState) {
+fn dump_scope_node(class_name: &str, scope: &Scope, range: &SourceRange, state: &DumpState) {
dump_node!(state, class_name, range);
for (i, child) in scope.children.iter().enumerate() {
- dump_statement(child, &child_state(state, i == scope.children.len() - 1));
+ dump_statement(&child, &child_state(state, i == scope.children.len() - 1));
}
}
@@ -1000,7 +954,7 @@ fn dump_function(function_data: &FunctionData, class_name: &str, range: &SourceR
desc.push('*');
}
let name_str = match function_data.name {
- Some(id) => utf16_to_string(state.name_slice(id)),
+ Some(id) => utf16_to_string(id.text()),
None => String::new(),
};
desc.push_str(&format!(" {}", color_string(state, &name_str)));
@@ -1035,7 +989,7 @@ fn dump_function(function_data: &FunctionData, class_name: &str, range: &SourceR
print_node(&parameter_state, &color_label(state, "rest"));
match &parameter.binding {
FunctionParameterBinding::Identifier(id) => {
- dump_identifier_id(*id, &child_state(&parameter_state, !has_default));
+ dump_identifier_id(id, &child_state(&parameter_state, !has_default));
}
FunctionParameterBinding::BindingPattern(pattern) => {
dump_binding_pattern(pattern, &child_state(&parameter_state, !has_default), state);
@@ -1045,7 +999,7 @@ fn dump_function(function_data: &FunctionData, class_name: &str, range: &SourceR
match &parameter.binding {
FunctionParameterBinding::Identifier(id) => {
dump_identifier_id(
- *id,
+ id,
&child_state(&parameters_state, i == function_data.parameters.len() - 1),
);
}
@@ -1074,7 +1028,7 @@ fn dump_function(function_data: &FunctionData, class_name: &str, range: &SourceR
fn dump_class(class_data: &ClassData, range: &SourceRange, state: &DumpState, root_state: &DumpState) {
let name_str = match class_data.name {
- Some(id) => utf16_to_string(state.name_slice(id)),
+ Some(id) => utf16_to_string(id.text()),
None => String::new(),
};
print_node(
@@ -1100,20 +1054,21 @@ fn dump_class(class_data: &ClassData, range: &SourceRange, state: &DumpState, ro
);
}
- if let Some(ref constructor) = class_data.constructor {
- print_node(
- &child_state(state, !has_elements),
- &color_label(root_state, "constructor"),
- );
- dump_expression(constructor, &child_state(&child_state(state, !has_elements), true));
- }
+ print_node(
+ &child_state(state, !has_elements),
+ &color_label(root_state, "constructor"),
+ );
+ dump_expression(
+ &class_data.constructor,
+ &child_state(&child_state(state, !has_elements), true),
+ );
if has_elements {
print_node(&child_state(state, true), &color_label(root_state, "elements"));
for (i, element) in class_data.elements.iter().enumerate() {
dump_class_element(
- &element.inner,
- &element.range,
+ &element.kind(),
+ &element.range(),
&child_state(&child_state(state, true), i == class_data.elements.len() - 1),
root_state,
);
@@ -1148,6 +1103,7 @@ fn dump_class_element(element: &ClassElement, range: &SourceRange, state: &DumpS
key,
initializer,
is_static,
+ ..
} => {
let mut desc = color_node_name(root_state, "ClassField");
if *is_static {
@@ -1161,7 +1117,7 @@ fn dump_class_element(element: &ClassElement, range: &SourceRange, state: &DumpS
dump_expression(init, &child_state(&child_state(state, true), true));
}
}
- ClassElement::StaticInitializer { body } => {
+ ClassElement::StaticInitializer { body, .. } => {
print_node(
state,
&format!(
@@ -1192,7 +1148,7 @@ fn dump_binding_pattern(pattern: &BindingPattern, state: &DumpState, root_state:
for (i, entry) in pattern.entries.iter().enumerate() {
let entry_state = child_state(state, i == pattern.entries.len() - 1);
- if pattern.kind == BindingPatternKind::Array && is_elision(entry) {
+ if pattern.kind == BindingPatternKind::Array && is_elision(&entry) {
print_node(&entry_state, &color_node_name(root_state, "Elision"));
continue;
}
@@ -1214,10 +1170,21 @@ fn dump_binding_pattern(pattern: &BindingPattern, state: &DumpState, root_state:
&color_label(root_state, "name"),
);
dump_identifier_id(
- *ident,
+ ident,
&child_state(&child_state(&entry_state, !has_alias && !has_initializer), true),
);
}
+ Some(BindingEntryName::Key(key)) => {
+ print_node(
+ &child_state(&entry_state, !has_alias && !has_initializer),
+ &color_label(root_state, "name"),
+ );
+ let key_state = child_state(&child_state(&entry_state, !has_alias && !has_initializer), true);
+ let mut desc = color_node_name(&key_state, "Identifier");
+ desc.push_str(&format!(" {}", color_string_utf16(&key_state, &key.text())));
+ desc.push_str(&format_position(&key_state, &key.range()));
+ print_node(&key_state, &desc);
+ }
Some(BindingEntryName::Expression(expression)) => {
print_node(
&child_state(&entry_state, !has_alias && !has_initializer),
@@ -1239,7 +1206,7 @@ fn dump_binding_pattern(pattern: &BindingPattern, state: &DumpState, root_state:
);
match alias {
BindingEntryAlias::Identifier(ident) => {
- dump_identifier_id(*ident, &child_state(&child_state(&entry_state, !has_initializer), true));
+ dump_identifier_id(ident, &child_state(&child_state(&entry_state, !has_initializer), true));
}
BindingEntryAlias::BindingPattern(sub) => {
dump_binding_pattern(
@@ -1280,13 +1247,13 @@ fn dump_variable_declarator(declaration: &VariableDeclarator, state: &DumpState,
&format!(
"{}{}",
color_node_name(root_state, "VariableDeclarator"),
- format_position(root_state, &declaration.range)
+ format_position(root_state, &declaration.range())
),
);
let has_init = declaration.init.is_some();
match &declaration.target {
VariableDeclaratorTarget::Identifier(ident) => {
- dump_identifier_id(*ident, &child_state(state, !has_init));
+ dump_identifier_id(ident, &child_state(state, !has_init));
}
VariableDeclaratorTarget::BindingPattern(pattern) => {
dump_binding_pattern(pattern, &child_state(state, !has_init), root_state);
@@ -1305,7 +1272,7 @@ fn dump_object_property(property: &ObjectProperty, state: &DumpState, root_state
"{} {}{}",
color_node_name(root_state, "ObjectProperty"),
color_op(root_state, "spread"),
- format_position(root_state, &property.range)
+ format_position(root_state, &property.range())
),
);
dump_expression(&property.key, &child_state(state, true));
@@ -1318,7 +1285,7 @@ fn dump_object_property(property: &ObjectProperty, state: &DumpState, root_state
} else if property.property_type == ObjectPropertyType::Setter {
desc.push_str(&format!(" {}", color_op(root_state, "setter")));
}
- desc.push_str(&format_position(root_state, &property.range));
+ desc.push_str(&format_position(root_state, &property.range()));
print_node(state, &desc);
dump_expression(&property.key, &child_state(state, false));
if let Some(ref value) = property.value {
@@ -1333,14 +1300,14 @@ fn dump_catch_clause(clause: &CatchClause, state: &DumpState, root_state: &DumpS
&format!(
"{}{}",
color_node_name(root_state, "CatchClause"),
- format_position(root_state, &clause.range)
+ format_position(root_state, &clause.range())
),
);
if let Some(parameter) = &clause.parameter {
match parameter {
CatchBinding::Identifier(ident) => {
print_node(&child_state(state, false), &color_label(root_state, "parameter"));
- dump_identifier_id(*ident, &child_state(&child_state(state, false), true));
+ dump_identifier_id(ident, &child_state(&child_state(state, false), true));
}
CatchBinding::BindingPattern(pattern) => {
print_node(&child_state(state, false), &color_label(root_state, "parameter"));
@@ -1358,7 +1325,7 @@ fn dump_switch_case(case: &SwitchCase, state: &DumpState, root_state: &DumpState
&format!(
"{}{}",
color_node_name(root_state, "SwitchCase"),
- format_position(root_state, &case.range)
+ format_position(root_state, &case.range())
),
);
print_node(&child_state(state, false), &color_label(root_state, "test"));
@@ -1370,16 +1337,16 @@ fn dump_switch_case(case: &SwitchCase, state: &DumpState, root_state: &DumpState
"{} {}{}",
color_node_name(root_state, "SwitchCase"),
color_op(root_state, "default"),
- format_position(root_state, &case.range)
+ format_position(root_state, &case.range())
),
);
}
print_node(&child_state(state, true), &color_label(root_state, "consequent"));
let consequent_state = child_state(&child_state(state, true), true);
- let scope = &state.arena.scopes[case.scope];
+ let scope = &case.scope;
let children = &scope.children;
for (i, child) in children.iter().enumerate() {
- dump_statement(child, &child_state(&consequent_state, i == children.len() - 1));
+ dump_statement(&child, &child_state(&consequent_state, i == children.len() - 1));
}
}
diff --git a/Libraries/LibJS/Rust/src/breakpoint_positions.rs b/Libraries/LibJS/Rust/src/breakpoint_positions.rs
index afb8a5476e6..7bdf29c5bda 100644
--- a/Libraries/LibJS/Rust/src/breakpoint_positions.rs
+++ b/Libraries/LibJS/Rust/src/breakpoint_positions.rs
@@ -8,12 +8,13 @@
use crate::ast::ProgramType;
use crate::bytecode::executable_data::ExecutableData;
-use crate::bytecode::generator::PrecompiledFunction;
-use crate::compile::CompiledProgram;
-use crate::compile::CompiledProgramBytecode;
-use crate::compile::FunctionPrecompileMode;
+use crate::bytecode::executable_data::PendingSharedFunctionData;
+use crate::compile::FunctionPayload;
+use crate::compile::compile_function;
use crate::compile::compile_parsed_program_off_thread;
use crate::compile::parse;
+use crate::parser::base::DEFAULT_STACK_BUDGET;
+use crate::parser::stack_limit_for_budget;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BreakpointPosition {
@@ -22,9 +23,10 @@ pub struct BreakpointPosition {
}
/// The breakpoint positions of `source`, sorted and without repeats, with lines counted as [`parse()`] counts them
-/// from `initial_line_number`. A source with syntax errors has none.
+/// from `initial_line_number`. A source with syntax errors has none. Every function gets compiled to find them, on its
+/// own, the way that it would on its first call. The positions of what does not fit the stack left out.
pub fn breakpoint_positions_for_source(
- source: &[u16],
+ source: &ak::Utf16String,
program_type: ProgramType,
initial_line_number: usize,
) -> Vec<BreakpointPosition> {
@@ -32,50 +34,53 @@ pub fn breakpoint_positions_for_source(
if parsed.has_errors() {
return Vec::new();
}
- let compiled = compile_parsed_program_off_thread(parsed, source.len(), FunctionPrecompileMode::All);
+ let compiled = compile_parsed_program_off_thread(parsed);
let mut positions = Vec::new();
- compiled.for_each_breakpoint_position(|position| positions.push(position));
+ match program_type {
+ ProgramType::Script => {
+ let script = compiled.into_script();
+ add_positions_of_executable(&script.executable, &mut positions);
+ for function in &script.declarations.functions_to_initialize {
+ add_positions_of_function(&function.shared_function_data, &mut positions);
+ }
+ }
+ ProgramType::Module => {
+ let module = compiled.into_module();
+ add_positions_of_executable(&module.executable, &mut positions);
+ for function in &module.declarations.functions_to_initialize {
+ add_positions_of_payload(&function.description.payload, &mut positions);
+ }
+ }
+ }
positions.sort_unstable();
positions.dedup();
positions
}
-impl CompiledProgram {
- /// Calls `callback` with the position of every source map entry in the bytecode of the program and of the
- /// functions that were compiled with it, in no particular order and with repeats.
- pub fn for_each_breakpoint_position(&self, mut callback: impl FnMut(BreakpointPosition)) {
- fn for_each_in_precompiled_function(
- precompiled: &PrecompiledFunction,
- callback: &mut dyn FnMut(BreakpointPosition),
- ) {
- for_each_in_executable(&precompiled.executable, callback);
+fn add_positions_of_executable(executable: &ExecutableData, positions: &mut Vec<BreakpointPosition>) {
+ for entry in executable.source_positions() {
+ if entry.line != 0 {
+ positions.push(BreakpointPosition {
+ line: entry.line,
+ column: entry.column,
+ });
}
+ }
+ for function in &executable.shared_function_data {
+ add_positions_of_function(function, positions);
+ }
+}
- fn for_each_in_executable(executable: &ExecutableData, callback: &mut dyn FnMut(BreakpointPosition)) {
- for entry in &executable.source_map {
- if entry.line != 0 {
- callback(BreakpointPosition {
- line: entry.line,
- column: entry.column,
- });
- }
- }
- for shared_data in &executable.shared_function_data {
- if let Some(precompiled) = &shared_data.precompiled_function {
- for_each_in_precompiled_function(precompiled, callback);
- }
- }
- }
+fn add_positions_of_function(function: &PendingSharedFunctionData, positions: &mut Vec<BreakpointPosition>) {
+ if let Some(precompiled) = &function.precompiled_function {
+ add_positions_of_executable(&precompiled.executable, positions);
+ } else {
+ add_positions_of_payload(&function.description.payload, positions);
+ }
+}
- match &self.bytecode {
- CompiledProgramBytecode::Program(executable) | CompiledProgramBytecode::AsyncModule(executable) => {
- for_each_in_executable(executable, &mut callback);
- }
- }
- for declaration in &self.declaration_functions {
- if let Some(precompiled) = &declaration.precompiled_function {
- for_each_in_precompiled_function(precompiled, &mut callback);
- }
- }
+fn add_positions_of_payload(payload: &FunctionPayload, positions: &mut Vec<BreakpointPosition>) {
+ if let Ok(compiled) = compile_function(payload, false, stack_limit_for_budget(DEFAULT_STACK_BUDGET)) {
+ add_positions_of_executable(&compiled.executable, positions);
}
}
diff --git a/Libraries/LibJS/Rust/src/bytecode/class_blueprint.rs b/Libraries/LibJS/Rust/src/bytecode/class_blueprint.rs
index 74118d45e47..346ad43be6d 100644
--- a/Libraries/LibJS/Rust/src/bytecode/class_blueprint.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/class_blueprint.rs
@@ -8,11 +8,13 @@
use std::rc::Rc;
-use ak::{Utf16FlyString, Utf16String};
+use ak::Utf16FlyString;
+
+use crate::utf16::Utf16View;
use libjs_abi::ClassElementKind;
use libjs_runtime_macros::Trace;
-use crate::bytecode::generator::{PendingClassBlueprint, PendingClassElement, PendingLiteralValueKind};
+use crate::bytecode::executable_data::{PendingClassBlueprint, PendingClassElement, PendingLiteralValueKind};
use crate::gc::defer_gc::DeferGc;
use crate::interpreter::vm::Vm;
use crate::layout::value::Value;
@@ -64,7 +66,7 @@ impl ClassBlueprint {
_defer_gc: &DeferGc<'_>,
) -> ClassBlueprint {
let name = match &blueprint.name {
- Some(name) if !name.is_empty() => Utf16FlyString::from_utf16(name),
+ Some(name) if !name.is_empty() => Utf16View::of_string(name).to_utf16_fly_string(),
_ => Utf16FlyString::default(),
};
let elements = blueprint
@@ -89,7 +91,7 @@ impl ClassBlueprint {
.private_identifier
.as_ref()
.filter(|identifier| !identifier.is_empty())
- .map(|identifier| Utf16FlyString::from_utf16(identifier));
+ .map(|identifier| Utf16View::of_string(identifier).to_utf16_fly_string());
let literal_value = match element.literal_value_kind {
PendingLiteralValueKind::None => None,
PendingLiteralValueKind::Number => Some(Value::from_f64(element.literal_value_number)),
@@ -97,10 +99,7 @@ impl ClassBlueprint {
PendingLiteralValueKind::BooleanFalse => Some(Value::FALSE),
PendingLiteralValueKind::Null => Some(Value::NULL),
PendingLiteralValueKind::String => {
- let string = element
- .literal_value_string
- .as_ref()
- .map_or_else(Utf16String::default, |string| Utf16String::from_utf16(string));
+ let string = element.literal_value_string.clone().unwrap_or_default();
Some(Value::from_string(PrimitiveString::create(vm, string)))
}
};
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/mod.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/mod.rs
new file mode 100644
index 00000000000..b912f2c347e
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/mod.rs
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Bytecode generation from the columns of the syntax tree, straight into bytes.
+//!
+//! A top level has marks in its rows from its first parse, and a function gets parsed again with them. `sweep` goes
+//! through the rows in one loop, leaving what does not come in the order of its rows to `constructs`. Both call the emission core in `stream`, which
+//! knows nothing of rows, and writes each instruction into bytes. What names mean comes from `scope`, which goes by a
+//! summary of the first parse. Everything with memory of its own is in `context`, and comes back for the next compile
+//! on the thread.
+
+mod bindings;
+mod builtins;
+mod constants;
+mod constructs;
+mod context;
+pub mod emitter;
+mod environment;
+mod generators;
+mod members;
+mod names;
+mod nodes;
+mod operators;
+mod registers;
+pub mod scope;
+pub mod stream;
+mod sweep;
+
+use std::sync::Arc;
+
+use crate::ast::FunctionKind;
+use crate::ast::SyntaxTree;
+use crate::bytecode::executable_data::ExecutableData;
+use crate::bytecode::executable_data::PrecompiledFunction;
+use crate::bytecode::instruction::typed as op;
+use crate::parser::EnclosingCode;
+use crate::parser::OutOfStack;
+use context::Generator;
+pub use environment::EnclosingEnvironmentScope;
+use nodes::NodeId;
+pub use stream::DisposableResourceKind;
+
+/// Compiles the function at `row`, which gets parsed again for that.
+pub fn compile_function(
+ script: &Arc<crate::parser::ScriptData>,
+ row: crate::parser::FunctionRow,
+ enclosing_environment_scope: Option<Arc<EnclosingEnvironmentScope>>,
+ enclosing_code: &Arc<EnclosingCode>,
+ builtin_abstract_operations_enabled: bool,
+ stack_limit: usize,
+) -> Result<PrecompiledFunction, OutOfStack> {
+ let (tree, node) = script.reparse_for_sweep(row, stack_limit)?;
+ let result = {
+ let mut generator = Generator::new(&tree, enclosing_code.clone(), stack_limit);
+ generator.enclosing_environment_scope = enclosing_environment_scope;
+ generator.builtin_abstract_operations_enabled = builtin_abstract_operations_enabled;
+ generator.begin_function_scope(row);
+ let function = NodeId(node);
+ let flags = script.index.flags[row.0 as usize];
+ use crate::parser::columns::function_flag::*;
+ let swept = if flags & FIELD_INITIALIZER != 0 {
+ generator.sweep_field_initializer(function)
+ } else if flags & STATIC_BLOCK != 0 {
+ generator.sweep_static_block(function)
+ } else if flags & DEFAULT_CONSTRUCTOR != 0 {
+ generator.current_source_offset =
+ crate::bytecode::source_map::SourceOffset(script.index.start[row.0 as usize]);
+ generator.generate_default_constructor(flags & DERIVED_CONSTRUCTOR != 0);
+ Ok(())
+ } else {
+ generator.sweep_parameter_names(function);
+ generator
+ .sweep_parameters(function)
+ .and_then(|()| sweep::sweep_function_body(&mut generator, function))
+ };
+ swept.map(|()| generator.finish_function())
+ };
+ tree.give_back_memory();
+ result
+}
+
+/// What a compile needs to know of a program, which `compile.rs` works out.
+pub struct ProgramInput<'a> {
+ pub tree: &'a Arc<SyntaxTree>,
+ pub strict: bool,
+ /// Whether the program is a module with top-level await, which runs like an async function.
+ pub is_async_module: bool,
+ pub eager_compile_direct_iifes: bool,
+ pub enclosing_environment_scope: Option<Arc<EnclosingEnvironmentScope>>,
+ pub stack_limit: usize,
+}
+
+/// Compiles the script, module or eval that is the program of the tree in `input`, from the rows that its parse left.
+pub fn compile_program(input: &ProgramInput<'_>) -> Result<ExecutableData, OutOfStack> {
+ let parsed = input.tree;
+ let script = &parsed.script;
+ let (tree, node) = script.take_top_level_rows()?;
+ let kind = if script.program_type == crate::ast::ProgramType::Module {
+ scope::ProgramKind::Module
+ } else if script.program_context.has_no_globals {
+ scope::ProgramKind::WithoutGlobals
+ } else {
+ scope::ProgramKind::Script
+ };
+ let compiled = {
+ let mut generator = Generator::new(&tree, EnclosingCode::of_program(parsed), input.stack_limit);
+ generator.strict = input.strict;
+ generator.eager_compile_direct_iifes = input.eager_compile_direct_iifes;
+ generator.enclosing_environment_scope = input.enclosing_environment_scope.clone();
+ if input.is_async_module {
+ generator.enclosing_function_kind = FunctionKind::Async;
+ }
+ generator.context.annexb_function_names.extend_from_slice(
+ parsed
+ .program_scope()
+ .annexb_function_names
+ .of(&parsed.scopes.annexb_function_names),
+ );
+ generator.begin_program_scope(kind, input.is_async_module);
+ sweep::sweep_program(&mut generator, NodeId(node)).map(|()| generator.finish_function())
+ };
+ tree.give_back_memory();
+ let mut executable = Arc::into_inner(compiled?.executable).expect("nothing else holds on to new code");
+ for pending in &mut executable.shared_function_data {
+ if pending.should_eager_compile {
+ pending.precompiled_function =
+ crate::compile::compile_function(&pending.description.payload, false, input.stack_limit)
+ .ok()
+ .map(Arc::new);
+ }
+ }
+ Ok(executable)
+}
+
+/// The code of a program that nests too deeply to generate code for it with the stack there is. Running it throws, like
+/// a function does that is too deep to compile.
+pub fn compile_program_too_deep_to_generate(tree: &Arc<SyntaxTree>) -> ExecutableData {
+ let tree_ref: &SyntaxTree = tree;
+ let mut generator = Generator::new(tree_ref, EnclosingCode::of_program(tree_ref), 0);
+ generator.begin_program_scope(scope::ProgramKind::Script, true);
+ let exception = generator.temporary();
+ let error_string = generator.intern_string_text(crate::utf16::Utf16View::Utf16(utf16!(
+ "Maximum call stack size exceeded"
+ )));
+ generator.put(op::NewTypeError {
+ dst: exception,
+ error_string,
+ });
+ generator.put(op::Throw { src: exception });
+ let compiled = generator.finish_function();
+ Arc::into_inner(compiled.executable).expect("nothing else holds on to new code")
+}
diff --git a/Libraries/LibJS/Rust/src/bytecode/constant.rs b/Libraries/LibJS/Rust/src/bytecode/constant.rs
index 98576e130bd..d071dcb694d 100644
--- a/Libraries/LibJS/Rust/src/bytecode/constant.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/constant.rs
@@ -4,8 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! Constants whose value depends on the VM, so codegen records only which one it needs, and the tags of the encoding
-//! that the runtime and the bytecode cache store constants in.
+//! Constants whose value depends on the VM, so codegen records only which one it needs.
/// Well-known symbol IDs that the runtime resolves when materializing an Executable.
#[repr(u8)]
@@ -26,18 +25,3 @@ pub enum AbstractOperationKind {
IteratorComplete = 4,
ArraySpeciesCreate = 5,
}
-
-/// Constant tags for the FFI constant buffer (ABI-compatible).
-#[repr(u8)]
-pub enum ConstantTag {
- Number = 0,
- BooleanTrue = 1,
- BooleanFalse = 2,
- Null = 3,
- Undefined = 4,
- Empty = 5,
- String = 6,
- BigInt = 7,
- WellKnownSymbol = 8,
- AbstractOperation = 9,
-}
diff --git a/Libraries/LibJS/Rust/src/bytecode/dump.rs b/Libraries/LibJS/Rust/src/bytecode/dump.rs
index 7023c64f14f..21dfc94c1d3 100644
--- a/Libraries/LibJS/Rust/src/bytecode/dump.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/dump.rs
@@ -6,7 +6,7 @@
use super::encoding::PropertyKeyTableIndex;
use super::executable::{Executable, append_double_formatted_like_ak, append_value_formatted_like_ak};
-use super::generator::ExceptionHandler;
+use super::executable_data::ExceptionHandler;
use super::instruction::dump_instruction_from_bytes;
use super::instruction::instruction_is_terminator_from_opcode;
use super::instruction::instruction_length_from_bytes;
@@ -14,7 +14,7 @@ use super::instruction::instruction_name_from_opcode;
use super::instruction::visit_labels_from_bytes;
use super::native_disassembler::disassemble;
use super::operand::Operand;
-use super::validator::read_u32;
+use super::operand::read_u32;
use crate::bytecode::encoded_value::EncodedValue;
use crate::bytecode::encoded_value::EncodedValueKind;
use crate::interpreter::run::should_dump_interpreter_assembly;
@@ -278,12 +278,12 @@ impl BytecodeDumper<'_> {
pub fn append_identifier_quoted(&mut self, index: u32) {
self.append_quoted(Utf16View::of_fly_string(
- &self.executable.identifier_table[index as usize],
+ &self.executable.identifier_table()[index as usize],
));
}
pub fn append_identifier_plain(&mut self, index: u32) {
- Utf16View::of_fly_string(&self.executable.identifier_table[index as usize]).append_as_wtf8_to(self.output);
+ Utf16View::of_fly_string(&self.executable.identifier_table()[index as usize]).append_as_wtf8_to(self.output);
}
/// A PropertyKey is the text it was made from, since only canonical index strings become numbers.
@@ -304,7 +304,7 @@ impl BytecodeDumper<'_> {
}
pub fn append_string(&mut self, index: u32) {
- Utf16View::of_fly_string(&self.executable.string_table[index as usize]).append_as_wtf8_to(self.output);
+ Utf16View::of_fly_string(&self.executable.string_table()[index as usize]).append_as_wtf8_to(self.output);
}
pub fn append_bool(&mut self, name: &str, value: bool) {
@@ -446,7 +446,7 @@ fn collect_basic_block_start_offsets(bytecode: &[u8], exception_handlers: &[Exce
while at < bytecode.len() {
let opcode = bytecode[at];
let length = instruction_length_from_bytes(opcode, bytecode, at)
- .expect("validated bytecode should have valid instruction lengths");
+ .expect("generated bytecode has valid instruction lengths");
let next_offset = at + length;
visit_labels_from_bytes(opcode, bytecode, at, &mut |address| {
@@ -470,16 +470,16 @@ fn collect_basic_block_start_offsets(bytecode: &[u8], exception_handlers: &[Exce
offsets
}
-/// Count basic blocks in a validated bytecode instruction stream.
+/// Count basic blocks in a bytecode instruction stream.
pub fn count_basic_blocks(executable: &Executable) -> usize {
- collect_basic_block_start_offsets(executable.bytecode(), &executable.exception_handlers).len()
+ collect_basic_block_start_offsets(executable.bytecode(), executable.exception_handlers()).len()
}
-/// Dump the validated bytecode of an executable, and with LADYBIRD_JS_INTERPRETER_DUMP set, the native code of the
+/// Dump the bytecode of an executable, and with LADYBIRD_JS_INTERPRETER_DUMP set, the native code of the
/// interpreter handler of each instruction.
pub fn dump_bytecode(output: &mut Vec<u8>, executable: &Executable) {
let bytecode = executable.bytecode();
- let exception_handlers = &executable.exception_handlers;
+ let exception_handlers = executable.exception_handlers();
let dump_interpreter = should_dump_interpreter_assembly();
let basic_block_start_offsets = collect_basic_block_start_offsets(bytecode, exception_handlers);
let mut dumper = BytecodeDumper {
@@ -522,7 +522,7 @@ pub fn dump_bytecode(output: &mut Vec<u8>, executable: &Executable) {
}
at += instruction_length_from_bytes(bytecode[at], bytecode, at)
- .expect("validated bytecode should have valid instruction lengths");
+ .expect("generated bytecode has valid instruction lengths");
}
dumper.append_exception_handlers(exception_handlers);
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rs
index 4441a81cb06..d8eb4c7cb04 100644
--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs
@@ -8,21 +8,19 @@ use core::cell::{Cell, OnceCell, RefCell};
use std::collections::HashMap;
use std::io::Write;
use std::rc::Rc;
+use std::sync::Arc;
use ak::Utf16FlyString;
use crate::breakpoint::BreakpointID;
-use crate::bytecode::basic_block::SourceMapEntry;
use crate::bytecode::class_blueprint::ClassBlueprint;
use crate::bytecode::constant::{AbstractOperationKind, WellKnownSymbolKind};
use crate::bytecode::dump::{count_basic_blocks, dump_bytecode};
use crate::bytecode::encoding::{IdentifierTableIndex, PropertyKeyTableIndex, StringTableIndex};
-use crate::bytecode::executable_data::ExecutableCacheCounts as FrontendExecutableCacheCounts;
-use crate::bytecode::executable_data::ExecutableData;
+use crate::bytecode::executable_data::{ConstantValue, ExceptionHandler};
+use crate::bytecode::executable_data::{ExecutableData, LocalVariableMetadata};
use crate::bytecode::feedback::{ExecutableFeedback, FeedbackSlotCounts};
-use crate::bytecode::generator::{ConstantValue, ExceptionHandler};
-use crate::bytecode::generator::{LocalVariable, PendingClassBlueprint};
-use crate::bytecode_cache::{DecodedBytecodeBytes, DecodedExecutableRecord};
+use crate::bytecode::source_map::SourceMapEntry;
use crate::gc::class::{Finalize, GcCell, define_cell};
use crate::gc::defer_gc::DeferGc;
use crate::gc::root::MarkedVec;
@@ -611,49 +609,6 @@ impl PropertyLookupCache {
self.data.set(0);
}
- pub fn copy_from(&self, other: &PropertyLookupCache) {
- self.clear();
- if other.is_keyed_generic() {
- self.data.set(PROPERTY_LOOKUP_CACHE_KEYED_GENERIC_DATA);
- return;
- }
- if let Some(data) = other.monomorphic_data() {
- self.set_data(
- Box::new(MonomorphicData {
- entry: PropertyLookupCacheEntry::from_data(data.entry.get()),
- }),
- 0,
- );
- return;
- }
- if let Some(data) = other.polymorphic_data() {
- self.set_data(
- Box::new(PolymorphicData {
- entries: core::array::from_fn(|index| {
- PropertyLookupCacheEntry::from_data(data.entries[index].get())
- }),
- }),
- POLYMORPHIC_DATA_TAG,
- );
- return;
- }
- if let Some(data) = other.megamorphic_data() {
- self.set_data(
- Box::new(MegamorphicData {
- entry: PropertyLookupCacheEntry::from_data(data.entry.get()),
- primary_entries: core::array::from_fn(|index| {
- PropertyLookupCacheEntry::from_data(data.primary_entries[index].get())
- }),
- secondary_entries: core::array::from_fn(|index| {
- PropertyLookupCacheEntry::from_data(data.secondary_entries[index].get())
- }),
- keyed_misses: Cell::new(data.keyed_misses.get()),
- }),
- MEGAMORPHIC_DATA_TAG,
- );
- }
- }
-
/// Forgets the entries with a cell that died in this collection.
pub fn remove_dead_entries(&self, sweep: &Sweep<'_>) {
if let Some(data) = self.megamorphic_data() {
@@ -1221,54 +1176,6 @@ impl ObjectPropertyIteratorCacheData {
}
}
-/// Where the bytecode of an executable lives: in memory of its own, or in place in the bytecode cache blob it was
-/// materialized from, which it keeps alive.
-///
-/// One word: the data of a ThinSlice<u8> of its own, or a Box<DecodedBytecodeBytes> with the lowest bit set.
-pub struct ExecutableBytecode(usize);
-
-const _: () = assert!(align_of::<DecodedBytecodeBytes>() > 1);
-
-impl ExecutableBytecode {
- const IN_BYTECODE_CACHE_BLOB: usize = 1;
-
- fn owned(bytecode: ThinSlice<u8>) -> Self {
- let bytecode = core::mem::ManuallyDrop::new(bytecode);
- let data = bytecode.data as usize;
- assert!(data & Self::IN_BYTECODE_CACHE_BLOB == 0);
- Self(data)
- }
-
- fn in_bytecode_cache_blob(bytecode: DecodedBytecodeBytes) -> Self {
- Self(Box::into_raw(Box::new(bytecode)) as usize | Self::IN_BYTECODE_CACHE_BLOB)
- }
-
- fn is_in_bytecode_cache_blob(&self) -> bool {
- self.0 & Self::IN_BYTECODE_CACHE_BLOB != 0
- }
-
- pub fn as_slice(&self) -> &[u8] {
- if self.is_in_bytecode_cache_blob() {
- // SAFETY: The tagged word came from Box::into_raw() in in_bytecode_cache_blob(), and is dropped with self.
- return unsafe { &*((self.0 & !Self::IN_BYTECODE_CACHE_BLOB) as *const DecodedBytecodeBytes) }.as_slice();
- }
- let bytecode = core::mem::ManuallyDrop::new(ThinSlice::<u8>::from_data(self.0 as *mut u8));
- // SAFETY: The thin slice this word came from lives as long as self, as does the memory of the bytes.
- unsafe { ak::slice_from_raw_parts(bytecode.as_ptr(), bytecode.len()) }
- }
-}
-
-impl Drop for ExecutableBytecode {
- fn drop(&mut self) {
- if self.is_in_bytecode_cache_blob() {
- // SAFETY: The tagged word came from Box::into_raw() in in_bytecode_cache_blob().
- drop(unsafe { Box::from_raw((self.0 & !Self::IN_BYTECODE_CACHE_BLOB) as *mut DecodedBytecodeBytes) });
- } else {
- drop(ThinSlice::<u8>::from_data(self.0 as *mut u8));
- }
- }
-}
-
/// The parts of an executable that few executables need.
#[derive(Default)]
struct ExecutableRareData {
@@ -1286,7 +1193,8 @@ struct ExecutableRareData {
#[repr(C)]
pub struct Executable {
pub head: ExecutableHead,
- bytecode: ExecutableBytecode,
+ /// What this executable runs, which other executables of the same code share.
+ code: Arc<ExecutableData>,
environment_shape_caches: ThinSlice<NullableMember<EnvironmentShape>>,
object_shape_caches: ThinSlice<ObjectShapeCache>,
/// How many feedback slots of each kind the bytecode indexes into.
@@ -1306,23 +1214,13 @@ pub struct Executable {
/// Whether LIBJS_JIT=dump-feedback printed the executable's feedback already.
has_dumped_feedback: Cell<bool>,
pub is_strict_mode: bool,
- pub identifier_table: ThinSlice<ak::Utf16FlyString>,
/// The property keys, made once, since turning a string into a property key checks whether it is an array index.
property_keys: ThinSlice<PropertyKey>,
- pub string_table: ThinSlice<ak::Utf16FlyString>,
- /// Sorted by start offset, and not overlapping.
- pub exception_handlers: ThinSlice<ExceptionHandler>,
/// The functions the bytecode creates, which NewFunction and NewClass refer to by index.
shared_function_data: ThinSlice<Gc<SharedFunctionInstanceData>>,
/// The name of the function the executable is the body of, given when the function is first compiled. Empty for
/// other code.
name: FlyStringSlot,
- /// Sorted by bytecode offset: where in the source code the instructions from each offset on came from.
- pub source_map: ThinSlice<SourceMapEntry>,
- /// The names of the local variables, then the names of the arguments.
- variable_names: ThinSlice<Utf16FlyString>,
- /// One for each of the local variables.
- pub local_variable_metadata: ThinSlice<LocalVariableMetadata>,
pub source_code: Option<Rc<SourceCode>>,
}
@@ -1338,13 +1236,6 @@ pub struct LocalVariableScopeRange {
pub end: Position,
}
-/// Executable::LocalVariableMetadata
-#[derive(Clone, Copy)]
-pub struct LocalVariableMetadata {
- pub is_mutable: bool,
- pub scope_range: Option<LocalVariableScopeRange>,
-}
-
#[derive(Default)]
struct DebuggerBreakpointSite {
breakpoint_ids: Vec<BreakpointID>,
@@ -1352,33 +1243,6 @@ struct DebuggerBreakpointSite {
const _: () = assert!(core::mem::offset_of!(Executable, head) == 0);
-/// The cache counts an executable's bytecode refers to.
-pub struct ExecutableCacheCounts {
- pub property_lookup_caches: u32,
- pub global_variable_caches: u32,
- pub environment_coordinate_caches: u32,
- pub environment_shape_caches: u32,
-}
-
-/// What an executable is made of, as the frontend compiled it or a bytecode cache blob holds it.
-struct ExecutableParts {
- bytecode: ExecutableBytecode,
- number_of_registers: u32,
- number_of_arguments: u32,
- is_strict: bool,
- cache_counts: FrontendExecutableCacheCounts,
- identifier_table: Vec<Utf16FlyString>,
- property_key_table: Vec<Utf16FlyString>,
- string_table: Vec<Utf16FlyString>,
- constants: Vec<ConstantValue>,
- exception_handlers: Vec<ExceptionHandler>,
- source_map: Vec<SourceMapEntry>,
- local_variables: Vec<LocalVariable>,
- argument_variable_names: Vec<Utf16FlyString>,
- length_identifier: Option<u32>,
- class_blueprints: Vec<PendingClassBlueprint>,
-}
-
impl Executable {
pub fn property_lookup_cache(&self, index: usize) -> &PropertyLookupCache {
&self.head.property_lookup_caches[index]
@@ -1409,19 +1273,15 @@ impl Executable {
}
pub fn get_identifier(&self, index: IdentifierTableIndex) -> &Utf16FlyString {
- &self.identifier_table[index.0 as usize]
+ &self.code.identifier_table[index.0 as usize]
}
pub fn get_property_key(&self, index: PropertyKeyTableIndex) -> &PropertyKey {
&self.property_keys[index.0 as usize]
}
- pub fn set_property_key_table(&mut self, property_key_table: Vec<ak::Utf16FlyString>) {
- self.property_keys = property_key_table.into_iter().map(PropertyKey::from).collect();
- }
-
pub fn get_string(&self, index: StringTableIndex) -> &Utf16FlyString {
- &self.string_table[index.0 as usize]
+ &self.code.string_table[index.0 as usize]
}
/// Forgets the cells the inline caches remember that died in this collection.
@@ -1451,31 +1311,25 @@ impl Executable {
}
}
- #[allow(clippy::too_many_arguments)]
- pub fn new_with_bytecode(
- bytecode: ExecutableBytecode,
- number_of_registers: u32,
- number_of_locals: u32,
- number_of_arguments: u32,
- constants: ThinSlice<Value>,
- cache_counts: &ExecutableCacheCounts,
- is_strict_mode: bool,
- _defer_gc: &DeferGc<'_>,
- ) -> Self {
- let property_lookup_caches: ThinSlice<PropertyLookupCache> = (0..cache_counts.property_lookup_caches)
+ /// An executable of `code`, with empty caches. `code` is the only thing that keeps the bytecode alive, and it lives
+ /// for as long as the executable, which is what makes the address of the bytecode good to hand out.
+ fn new_with_code(code: Arc<ExecutableData>, constants: ThinSlice<Value>, _defer_gc: &DeferGc<'_>) -> Self {
+ let cache_counts = &code.cache_counts;
+ let property_lookup_caches: ThinSlice<PropertyLookupCache> = (0..cache_counts.property_lookup)
.map(|_| PropertyLookupCache::new())
.collect();
- let global_variable_caches: ThinSlice<GlobalVariableCache> = (0..cache_counts.global_variable_caches)
+ let global_variable_caches: ThinSlice<GlobalVariableCache> = (0..cache_counts.global_variable)
.map(|_| GlobalVariableCache::default())
.collect();
let environment_coordinate_caches: ThinSlice<Cell<EnvironmentCoordinate>> = (0..cache_counts
- .environment_coordinate_caches)
+ .environment_coordinate)
.map(|_| Cell::new(EnvironmentCoordinate::invalid()))
.collect();
- let environment_shape_caches = (0..cache_counts.environment_shape_caches)
+ let environment_shape_caches = (0..cache_counts.environment_shape)
.map(|_| NullableMember::null())
.collect();
- let registers_and_locals_count = number_of_registers + number_of_locals;
+ let number_of_locals = u32::try_from(code.local_variable_metadata.len()).expect("local count fits in u32");
+ let registers_and_locals_count = code.number_of_registers + number_of_locals;
let constant_count = u32::try_from(constants.len()).expect("constant count fits in u32");
let head = ExecutableHead {
registers_and_locals_count: Cell::new(registers_and_locals_count),
@@ -1484,7 +1338,7 @@ impl Executable {
// The VM picks the table when it registers the executable.
dispatch_table_index: Cell::new(InterpreterTier::Plain as u8),
tier_up_budget: Cell::new(i32::MAX),
- bytecode_data: Cell::new(bytecode.as_slice().as_ptr()),
+ bytecode_data: Cell::new(code.bytecode.as_ptr()),
jit_entry_slot: Cell::new(0),
jit_compile_state: Cell::new(0),
feedback: ExecutableFeedbackHead::empty(),
@@ -1494,60 +1348,50 @@ impl Executable {
// The interpreter only reads the caches, which slow paths update through their cells.
environment_coordinate_caches,
};
+ let object_shape_caches = (0..cache_counts.object_shape)
+ .map(|_| ObjectShapeCache::default())
+ .collect();
+ let feedback_slot_counts = FeedbackSlotCounts {
+ arith: cache_counts.arith_feedback,
+ value: cache_counts.value_feedback,
+ call: cache_counts.call_feedback,
+ keyed: cache_counts.keyed_feedback,
+ };
Self {
head,
- bytecode,
environment_shape_caches,
- object_shape_caches: ThinSlice::empty(),
- feedback_slot_counts: FeedbackSlotCounts::default(),
+ object_shape_caches,
+ feedback_slot_counts,
feedback: OnceCell::new(),
jit: OnceCell::new(),
rare_data: OnceCell::new(),
- number_of_registers,
- number_of_arguments,
- length_identifier: None,
+ number_of_registers: code.number_of_registers,
+ number_of_arguments: code.number_of_arguments,
+ length_identifier: code
+ .length_identifier
+ .map(|index| core::num::NonZeroU32::new(index.0 + 1).expect("the index plus one is not zero")),
interpreter_tier: Cell::new(InterpreterTier::Plain),
has_dumped_feedback: Cell::new(false),
- is_strict_mode,
- identifier_table: ThinSlice::empty(),
- property_keys: ThinSlice::empty(),
- string_table: ThinSlice::empty(),
- exception_handlers: ThinSlice::empty(),
+ is_strict_mode: code.is_strict,
+ property_keys: code.property_key_table.iter().cloned().map(PropertyKey::from).collect(),
shared_function_data: ThinSlice::empty(),
name: FlyStringSlot::new(None),
- source_map: ThinSlice::empty(),
- variable_names: ThinSlice::empty(),
- local_variable_metadata: ThinSlice::empty(),
source_code: None,
+ code,
}
}
- /// Gives the executable the object literal shape caches and for-in key snapshot caches its bytecode refers to.
- pub fn allocate_object_caches(&mut self, object_shape_caches: u32, object_property_iterator_caches: u32) {
- self.object_shape_caches = (0..object_shape_caches).map(|_| ObjectShapeCache::default()).collect();
- if object_property_iterator_caches != 0 {
- self.rare_data_mut().object_property_iterator_caches = (0..object_property_iterator_caches)
- .map(|_| ObjectPropertyIteratorCache { data: Cell::new(None) })
- .collect();
- }
- }
-
- /// Creates the executable for what the frontend compiled from code it does not know the source of.
- pub fn create(vm: &Vm, data: ExecutableData) -> Gc<Executable> {
- Self::create_with_source_code(vm, data, None)
- }
-
- /// Creates the executable for what the frontend compiled from `source_code`, with the functions and classes it
- /// declares.
+ /// Links what the frontend compiled from `source_code` into a new executable, with the functions and classes it
+ /// declares and caches of its own. `data` stays as it is, so it can be linked again, into any realm.
pub fn create_with_source_code(
vm: &Vm,
- mut data: ExecutableData,
+ data: Arc<ExecutableData>,
source_code: Option<&Rc<SourceCode>>,
) -> Gc<Executable> {
// The shared function data stays rooted until the executable that holds it is allocated.
let rooted_shared_function_data = MarkedVec::with_capacity(vm, data.shared_function_data.len());
let is_strict = data.is_strict;
- for pending in &mut data.shared_function_data {
+ for pending in &data.shared_function_data {
rooted_shared_function_data.push(SharedFunctionInstanceData::create_from_pending_shared_function_data(
vm,
pending,
@@ -1556,85 +1400,10 @@ impl Executable {
));
}
- let parts = ExecutableParts {
- bytecode: ExecutableBytecode::owned(data.bytecode.into()),
- number_of_registers: data.number_of_registers,
- number_of_arguments: data.number_of_arguments,
- is_strict: data.is_strict,
- cache_counts: data.cache_counts,
- identifier_table: data.identifier_table,
- property_key_table: data.property_key_table,
- string_table: data.string_table,
- constants: data.constants,
- exception_handlers: data.exception_handlers,
- source_map: data.source_map,
- local_variables: data.local_variables,
- argument_variable_names: data.argument_variable_names,
- length_identifier: data.length_identifier.map(|index| index.0),
- class_blueprints: data.class_blueprints,
- };
- Self::assemble(vm, parts, &rooted_shared_function_data, source_code, None)
- }
-
- /// Creates the executable of a record of a bytecode cache blob that passed validation, whose bytecode runs in
- /// place in the blob. `rooted_shared_function_data` holds the functions the bytecode creates, made from the
- /// record's function records in their order. An executable this one replaces in a running program hands its
- /// inline caches over. Returns `None` if the record turns out to be malformed.
- pub fn create_from_bytecode_cache(
- vm: &Vm,
- record: &DecodedExecutableRecord,
- rooted_shared_function_data: &MarkedVec<'_, Gc<SharedFunctionInstanceData>>,
- source_code: &Rc<SourceCode>,
- replaced_executable: Option<Gc<Executable>>,
- ) -> Option<Gc<Executable>> {
- let parts = ExecutableParts {
- bytecode: ExecutableBytecode::in_bytecode_cache_blob(record.bytecode().clone()),
- number_of_registers: record.number_of_registers(),
- number_of_arguments: record.number_of_arguments(),
- is_strict: record.is_strict(),
- cache_counts: record.cache_counts(),
- identifier_table: record.identifiers()?,
- property_key_table: record.property_keys()?,
- string_table: record.strings()?,
- constants: record.constant_values()?,
- exception_handlers: record.exception_handler_entries()?,
- source_map: record.source_map_entries()?,
- local_variables: record.locals()?,
- argument_variable_names: record.argument_names()?,
- length_identifier: record.length_identifier(),
- class_blueprints: record.classes()?,
- };
- Some(Self::assemble(
- vm,
- parts,
- rooted_shared_function_data,
- Some(source_code),
- replaced_executable,
- ))
- }
-
- fn assemble(
- vm: &Vm,
- parts: ExecutableParts,
- rooted_shared_function_data: &MarkedVec<'_, Gc<SharedFunctionInstanceData>>,
- source_code: Option<&Rc<SourceCode>>,
- replaced_executable: Option<Gc<Executable>>,
- ) -> Gc<Executable> {
- let executable = vm.heap().allocate(|defer_gc| {
- Self::build(
- vm,
- parts,
- rooted_shared_function_data,
- source_code,
- replaced_executable,
- defer_gc,
- )
- });
+ let executable = vm
+ .heap()
+ .allocate(|defer_gc| Self::build(vm, data, &rooted_shared_function_data, source_code, defer_gc));
vm.register_executable(executable);
- if let Some(replaced_executable) = replaced_executable {
- Self::copy_runtime_caches_from(executable, &replaced_executable);
- Self::take_over_warm_up_from(executable, &replaced_executable);
- }
if let Some(debugger) = vm.debugger() {
debugger.register_executable(vm, executable);
@@ -1645,58 +1414,32 @@ impl Executable {
fn build(
vm: &Vm,
- parts: ExecutableParts,
+ data: Arc<ExecutableData>,
rooted_shared_function_data: &MarkedVec<'_, Gc<SharedFunctionInstanceData>>,
source_code: Option<&Rc<SourceCode>>,
- replaced_executable: Option<Gc<Executable>>,
defer_gc: &DeferGc<'_>,
) -> Executable {
- let class_blueprints: ThinSlice<ClassBlueprint> = parts
+ let class_blueprints: ThinSlice<ClassBlueprint> = data
.class_blueprints
.iter()
.map(|blueprint| ClassBlueprint::create(vm, blueprint, source_code, defer_gc))
.collect();
let shared_function_data: ThinSlice<Gc<SharedFunctionInstanceData>> =
rooted_shared_function_data.values().iter().copied().collect();
- let constants: ThinSlice<Value> = parts
+ let constants: ThinSlice<Value> = data
.constants
.iter()
.map(|constant| constant_value(vm, constant))
.collect();
- // An executable this one replaces shares its template object caches, so that both hand out the same template
- // objects.
- let template_object_caches: ThinSlice<Gc<TemplateObjectCache>> = match replaced_executable {
- Some(replaced_executable)
- if replaced_executable.template_object_caches().len()
- == parts.cache_counts.template_object as usize =>
- {
- replaced_executable.template_object_caches().iter().copied().collect()
- }
- _ => (0..parts.cache_counts.template_object)
- .map(|_| TemplateObjectCache::create(vm))
- .collect(),
- };
- let counts = ExecutableCacheCounts {
- property_lookup_caches: parts.cache_counts.property_lookup,
- global_variable_caches: parts.cache_counts.global_variable,
- environment_coordinate_caches: parts.cache_counts.environment_coordinate,
- environment_shape_caches: parts.cache_counts.environment_shape,
- };
- let number_of_locals = u32::try_from(parts.local_variables.len()).expect("local count fits in u32");
- let mut executable = Self::new_with_bytecode(
- parts.bytecode,
- parts.number_of_registers,
- number_of_locals,
- parts.number_of_arguments,
- constants,
- &counts,
- parts.is_strict,
- defer_gc,
- );
- executable.identifier_table = parts.identifier_table.into();
- executable.set_property_key_table(parts.property_key_table);
- executable.string_table = parts.string_table.into();
- executable.exception_handlers = parts.exception_handlers.into();
+ let template_object_caches: ThinSlice<Gc<TemplateObjectCache>> = (0..data.cache_counts.template_object)
+ .map(|_| TemplateObjectCache::create(vm))
+ .collect();
+ let object_property_iterator_caches = data.cache_counts.object_property_iterator;
+
+ let mut executable = Self::new_with_code(data, constants, defer_gc);
+ if let Some(code) = Arc::get_mut(&mut executable.code) {
+ code.release_link_inputs();
+ }
executable.shared_function_data = shared_function_data;
if !class_blueprints.is_empty() {
executable.rare_data_mut().class_blueprints = class_blueprints;
@@ -1704,43 +1447,11 @@ impl Executable {
if !template_object_caches.is_empty() {
executable.rare_data_mut().template_object_caches = template_object_caches;
}
- executable.allocate_object_caches(
- parts.cache_counts.object_shape,
- parts.cache_counts.object_property_iterator,
- );
- executable.feedback_slot_counts = FeedbackSlotCounts {
- arith: parts.cache_counts.arith_feedback,
- value: parts.cache_counts.value_feedback,
- call: parts.cache_counts.call_feedback,
- keyed: parts.cache_counts.keyed_feedback,
- };
- executable.length_identifier = parts
- .length_identifier
- .map(|index| core::num::NonZeroU32::new(index + 1).expect("the index plus one is not zero"));
- executable.source_map = parts.source_map.into();
- executable.local_variable_metadata = parts
- .local_variables
- .iter()
- .map(|local_variable| LocalVariableMetadata {
- is_mutable: local_variable.is_mutable,
- scope_range: local_variable.scope_range.map(|range| LocalVariableScopeRange {
- start: Position {
- line: range.start.line,
- column: range.start.column,
- },
- end: Position {
- line: range.end.line,
- column: range.end.column,
- },
- }),
- })
- .collect();
- executable.variable_names = parts
- .local_variables
- .into_iter()
- .map(|local_variable| local_variable.name)
- .chain(parts.argument_variable_names)
- .collect();
+ if object_property_iterator_caches != 0 {
+ executable.rare_data_mut().object_property_iterator_caches = (0..object_property_iterator_caches)
+ .map(|_| ObjectPropertyIteratorCache { data: Cell::new(None) })
+ .collect();
+ }
executable.source_code = source_code.cloned();
executable
}
@@ -1769,7 +1480,7 @@ impl Executable {
/// The handler whose range holds the instruction at `offset`.
pub fn exception_handlers_for_offset(&self, offset: u32) -> Option<&ExceptionHandler> {
- self.exception_handlers
+ self.exception_handlers()
.binary_search_by(|handler| {
if offset < handler.start_offset {
core::cmp::Ordering::Greater
@@ -1780,33 +1491,71 @@ impl Executable {
}
})
.ok()
- .map(|index| &self.exception_handlers[index])
+ .map(|index| &self.exception_handlers()[index])
}
pub fn source_range_at(&self, offset: u32) -> Option<SourceRange> {
if offset as usize >= self.bytecode().len() {
return None;
}
- if self.source_map.is_empty() {
+ let source_map = self.source_map();
+ if source_map.is_empty() {
return None;
}
- let entries_at_or_before_offset = self.source_map.partition_point(|entry| entry.bytecode_offset <= offset);
+ let entries_at_or_before_offset = source_map.partition_point(|entry| entry.bytecode_offset <= offset);
if entries_at_or_before_offset == 0 {
return None;
}
- let entry = &self.source_map[entries_at_or_before_offset - 1];
+ let entry = &source_map[entries_at_or_before_offset - 1];
+ let (line, column) = match &self.code.position_source {
+ Some(positions) if entry.column != crate::bytecode::source_map::SourceOffset::NONE.0 => {
+ let position = positions.lines.position(entry.column);
+ (position.line, position.column)
+ }
+ Some(_) => (0, 0),
+ None => (entry.line, entry.column),
+ };
Some(SourceRange {
code: self
.source_code
.clone()
.unwrap_or_else(|| SourceCode::create(ak::Utf16String::default(), ak::Utf16String::default())),
- start: Position {
- line: entry.line,
- column: entry.column,
- },
+ start: Position { line, column },
})
}
+ /// The source around the instruction at `offset`, and where in that it is.
+ fn source_around(&self, offset: u32) -> Option<(Vec<u16>, usize)> {
+ const LONGEST_TEXT: usize = 1024;
+ let positions = self.code.position_source.as_ref()?;
+ let source_map = self.source_map();
+ let entries_at_or_before_offset = source_map.partition_point(|entry| entry.bytecode_offset <= offset);
+ let source_offset = source_map.get(entries_at_or_before_offset.checked_sub(1)?)?.column;
+ if source_offset == crate::bytecode::source_map::SourceOffset::NONE.0 {
+ return None;
+ }
+ let source_offset = source_offset as usize;
+ let view = crate::utf16::Utf16View::of_string(&positions.source);
+ let start = source_offset.saturating_sub(LONGEST_TEXT);
+ let end = (source_offset + LONGEST_TEXT).min(view.length_in_code_units());
+ let units = view.substring_view(start, end - start).code_units().collect();
+ Some((units, source_offset - start))
+ }
+
+ /// The text of what the call or `new` at `offset` calls, for code that left that out of its tables.
+ pub fn callee_text_at(&self, offset: u32) -> Option<ak::Utf16FlyString> {
+ let (units, at) = self.source_around(offset)?;
+ let text = crate::bytecode::reference_text::callee_text(&units, at)?;
+ Some(ak::Utf16FlyString::from_utf16(&text))
+ }
+
+ /// The text of the base of the member access at `offset`, for code that left that out of its tables.
+ pub fn base_text_at(&self, offset: u32) -> Option<ak::Utf16FlyString> {
+ let (units, at) = self.source_around(offset)?;
+ let text = crate::bytecode::reference_text::base_text(&units, at)?;
+ Some(ak::Utf16FlyString::from_utf16(&text))
+ }
+
/// The source range at `program_counter`, or an empty one if the source map has none.
pub fn get_source_range(&self, program_counter: u32) -> SourceRange {
self.source_range_at(program_counter).unwrap_or_else(|| SourceRange {
@@ -1833,12 +1582,54 @@ impl Executable {
.map_or(&[], |rare_data| &rare_data.class_blueprints)
}
+ /// What this executable runs. Executables that link the same code have the same one.
+ pub fn code(&self) -> &Arc<ExecutableData> {
+ &self.code
+ }
+
+ pub fn identifier_table(&self) -> &[Utf16FlyString] {
+ &self.code.identifier_table
+ }
+
+ pub fn string_table(&self) -> &[Utf16FlyString] {
+ &self.code.string_table
+ }
+
+ pub fn exception_handlers(&self) -> &[ExceptionHandler] {
+ &self.code.exception_handlers
+ }
+
+ pub fn source_positions(&self) -> impl Iterator<Item = SourceMapEntry> + '_ {
+ self.code.source_positions()
+ }
+
+ pub fn source_map(&self) -> &[SourceMapEntry] {
+ &self.code.source_map
+ }
+
+ pub fn local_variable_metadata(&self) -> &[LocalVariableMetadata] {
+ &self.code.local_variable_metadata
+ }
+
+ pub fn local_variable_scope_range(&self, index: usize) -> Option<LocalVariableScopeRange> {
+ let position = |position: crate::ast::Position| Position {
+ line: position.line,
+ column: position.column,
+ };
+ self.local_variable_metadata()[index]
+ .scope_range
+ .map(|range| LocalVariableScopeRange {
+ start: position(range.start),
+ end: position(range.end),
+ })
+ }
+
pub fn local_variable_names(&self) -> &[Utf16FlyString] {
- &self.variable_names[..self.local_variable_metadata.len()]
+ &self.code.variable_names[..self.local_variable_metadata().len()]
}
pub fn argument_variable_names(&self) -> &[Utf16FlyString] {
- &self.variable_names[self.local_variable_metadata.len()..]
+ &self.code.variable_names[self.local_variable_metadata().len()..]
}
pub fn length_identifier(&self) -> Option<PropertyKeyTableIndex> {
@@ -1918,103 +1709,7 @@ impl Executable {
}
pub fn bytecode(&self) -> &[u8] {
- self.bytecode.as_slice()
- }
-
- /// Whether the bytecode runs in place in the bytecode cache blob it was materialized from.
- pub fn runs_in_place_in_bytecode_cache_blob(&self) -> bool {
- self.bytecode.is_in_bytecode_cache_blob()
- }
-
- /// Takes over the feedback, the tier and the tier-up budget of `other`, an executable with the same bytecode that
- /// this one replaces, so that a function that warmed up goes on from where it was rather than start over, and
- /// whether the JIT refused it.
- fn take_over_warm_up_from(executable: Gc<Executable>, other: &Executable) {
- executable.take_over_jit_refusal_from(other);
- let Some(other_feedback) = other.feedback() else {
- return;
- };
- if executable.feedback_slot_counts != other.feedback_slot_counts {
- return;
- }
- executable.ensure_feedback().copy_from(other_feedback);
- executable.set_interpreter_tier(other.interpreter_tier());
- executable.head.tier_up_budget.set(other.head.tier_up_budget.get());
- }
-
- /// Executable::copy_runtime_caches_from(): makes `executable` take over what the inline caches of `other`, an
- /// executable compiled from the same code, learned, as installing a bytecode cache into a running program does.
- /// Each kind of cache is only taken over if the two executables have the same number of them. The template object
- /// caches are not copied here: an executable shares those of the one it replaces from its creation.
- /// NB: This takes an executable on the heap because the VM only forgets the dead cells in the caches of executables
- /// it registered. Entries copied into one not registered yet could outlive the cells they point to.
- fn copy_runtime_caches_from(executable: Gc<Executable>, other: &Executable) {
- let this = &*executable;
- if this.head.property_lookup_caches.len() == other.head.property_lookup_caches.len() {
- for (cache, other_cache) in this
- .head
- .property_lookup_caches
- .iter()
- .zip(&other.head.property_lookup_caches)
- {
- cache.copy_from(other_cache);
- }
- }
- if this.head.global_variable_caches.len() == other.head.global_variable_caches.len() {
- for (cache, other_cache) in this
- .head
- .global_variable_caches
- .iter()
- .zip(&other.head.global_variable_caches)
- {
- cache.entry.set(other_cache.entry.get());
- cache
- .environment_serial_number
- .set(other_cache.environment_serial_number.get());
- cache
- .environment_binding_index
- .set(other_cache.environment_binding_index.get());
- cache
- .has_environment_binding_index
- .set(other_cache.has_environment_binding_index.get());
- }
- }
- if this.head.environment_coordinate_caches.len() == other.head.environment_coordinate_caches.len() {
- for (cache, other_cache) in this
- .head
- .environment_coordinate_caches
- .iter()
- .zip(&other.head.environment_coordinate_caches)
- {
- cache.set(other_cache.get());
- }
- }
- if this.object_shape_caches.len() == other.object_shape_caches.len() {
- for (cache, other_cache) in this.object_shape_caches.iter().zip(&other.object_shape_caches) {
- cache.shape.set(other_cache.shape.get());
- cache
- .property_offsets
- .replace(other_cache.property_offsets.borrow().clone());
- }
- }
- if this.object_property_iterator_caches().len() == other.object_property_iterator_caches().len() {
- for (cache, other_cache) in this
- .object_property_iterator_caches()
- .iter()
- .zip(other.object_property_iterator_caches())
- {
- cache.data.set(other_cache.data.get());
- }
- }
- if this.environment_shape_caches.len() == other.environment_shape_caches.len() {
- for (cache, other_cache) in this
- .environment_shape_caches
- .iter()
- .zip(&other.environment_shape_caches)
- {
- cache.set(other_cache.get());
- }
- }
+ &self.code.bytecode
}
pub fn constants(&self) -> &[Value] {
@@ -2148,25 +1843,19 @@ impl Executable {
}
}
-fn first_real_source_map_entry(executable: &Executable) -> Option<&SourceMapEntry> {
- let mut first_entry: Option<&SourceMapEntry> = None;
- for entry in &executable.source_map {
- if entry.line == 0 && entry.column == 0 {
- continue;
- }
- if first_entry.is_none_or(|first_entry| {
- entry.line < first_entry.line || (entry.line == first_entry.line && entry.column < first_entry.column)
- }) {
- first_entry = Some(entry);
- }
- }
- first_entry
+/// The line and the column that the first position of the code has.
+fn first_real_source_position(executable: &Executable) -> Option<(u32, u32)> {
+ executable
+ .source_positions()
+ .map(|entry| (entry.line, entry.column))
+ .filter(|&position| position != (0, 0))
+ .min()
}
fn dump_header(output: &mut Vec<u8>, executable: &Executable) {
const WHITE_BOLD: &str = "\x1b[37;1m";
const RESET: &str = "\x1b[0m";
- let first_source_map_entry = first_real_source_map_entry(executable);
+ let first_source_position = first_real_source_position(executable);
let mut hash: u32 = 2166136261; // FNV-1a offset basis
let update_hash = |hash: &mut u32, value: u32| {
@@ -2187,9 +1876,9 @@ fn dump_header(output: &mut Vec<u8>, executable: &Executable) {
for code_unit in name_view.code_units() {
update_hash_with_code_unit(&mut hash, code_unit);
}
- if let Some(first_source_map_entry) = first_source_map_entry {
- update_hash(&mut hash, first_source_map_entry.line);
- update_hash(&mut hash, first_source_map_entry.column);
+ if let Some((line, column)) = first_source_position {
+ update_hash(&mut hash, line);
+ update_hash(&mut hash, column);
}
update_hash(
&mut hash,
@@ -2201,7 +1890,7 @@ fn dump_header(output: &mut Vec<u8>, executable: &Executable) {
let _ = write!(output, "${hash:08x}{RESET}");
// Show source location if available.
- if let Some(first_source_map_entry) = first_source_map_entry {
+ if let Some((line, column)) = first_source_position {
let filename = executable.source_code.as_ref().map_or(Utf16View::EMPTY, |source_code| {
Utf16View::of_string(source_code.filename())
});
@@ -2221,17 +1910,9 @@ fn dump_header(output: &mut Vec<u8>, executable: &Executable) {
};
output.push(b' ');
filename.append_as_wtf8_to(output);
- let _ = write!(
- output,
- ":{}:{}",
- first_source_map_entry.line, first_source_map_entry.column
- );
+ let _ = write!(output, ":{line}:{column}");
} else {
- let _ = write!(
- output,
- " line {}, column {}",
- first_source_map_entry.line, first_source_map_entry.column
- );
+ let _ = write!(output, " line {line}, column {column}");
}
}
output.push(b'\n');
@@ -2331,12 +2012,12 @@ fn constant_value(vm: &Vm, constant: &ConstantValue) -> Value {
// String constants are interned so that comparisons with them are pointer comparisons. Long ones are
// rarely compared, and not worth hashing.
const MAX_INTERNED_CONSTANT_LENGTH: usize = 256;
- if string.0.len() > MAX_INTERNED_CONSTANT_LENGTH {
- return Value::from_string(PrimitiveString::create(vm, ak::Utf16String::from_utf16(&string.0)));
+ if string.length_in_code_units() > MAX_INTERNED_CONSTANT_LENGTH {
+ return Value::from_string(PrimitiveString::create(vm, string.clone()));
}
Value::from_string(PrimitiveString::create_interned(
vm,
- &ak::Utf16FlyString::from_utf16(&string.0),
+ &Utf16View::of_string(string).to_utf16_fly_string(),
))
}
ConstantValue::BigInt(literal) => Value::from_bigint(BigInt::create(vm, parse_big_int_literal(literal))),
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable_data.rs b/Libraries/LibJS/Rust/src/bytecode/executable_data.rs
index b371d6aab9e..a1be1b852ad 100644
--- a/Libraries/LibJS/Rust/src/bytecode/executable_data.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/executable_data.rs
@@ -6,15 +6,107 @@
//! Compiled bytecode together with everything needed to run it, as owned Rust values.
-use super::basic_block::SourceMapEntry;
-use super::generator::AssembledBytecode;
-use super::generator::ConstantValue;
-use super::generator::ExceptionHandler;
-use super::generator::Generator;
-use super::generator::LocalVariable;
-use super::generator::PendingClassBlueprint;
-use super::generator::PendingSharedFunctionData;
+use std::sync::Arc;
+
+use ak::Utf16String;
+
+use super::constant::AbstractOperationKind;
+use super::constant::WellKnownSymbolKind;
use super::operand::PropertyKeyTableIndex;
+use super::source_map::SourceMapEntry;
+use crate::ast::FunctionId;
+use crate::compile::SharedFunctionDescription;
+
+/// Exception handler range (with byte offsets, post-linking).
+#[derive(Debug, Clone)]
+pub struct ExceptionHandler {
+ pub start_offset: u32,
+ pub end_offset: u32,
+ pub handler_offset: u32,
+ pub catches_exception: bool,
+}
+
+/// A typed constant value stored in the constant pool.
+///
+/// The actual NaN-boxed encoding happens at the FFI boundary when
+/// creating the `Bytecode::Executable`.
+#[derive(Debug, Clone)]
+pub enum ConstantValue {
+ Number(f64),
+ Boolean(bool),
+ Null,
+ Undefined,
+ Empty,
+ String(Utf16String),
+ BigInt(String),
+ /// A VM-specific well-known symbol resolved when the Executable is materialized.
+ WellKnownSymbol(WellKnownSymbolKind),
+ /// A NativeJavaScriptBackedFunction intrinsic resolved when the Executable is materialized.
+ AbstractOperation(AbstractOperationKind),
+}
+
+pub struct PendingSharedFunctionData {
+ /// The function in the tree of the compile job, for as long as that job runs.
+ pub function: FunctionId,
+ pub description: SharedFunctionDescription,
+ pub class_field_initializer_name: Option<(Utf16String, bool)>,
+ pub should_eager_compile: bool,
+ pub precompiled_function: Option<Arc<PrecompiledFunction>>,
+}
+
+/// Metadata computed from scope analysis for a SharedFunctionInstanceData.
+#[derive(Clone)]
+pub struct FunctionSfdMetadata {
+ /// The parameter names if a mapped arguments object goes by them, and empty otherwise.
+ pub parameter_names: Box<[ak::Utf16FlyString]>,
+ pub uses_this: bool,
+ pub this_value_needs_environment_resolution: bool,
+ pub function_environment_needed: bool,
+ /// Whether the code of the function can change the running lexical environment.
+ pub creates_environment: bool,
+ pub function_environment_bindings_count: usize,
+ pub var_environment_bindings_count: usize,
+ pub might_need_arguments: bool,
+ pub contains_eval: bool,
+}
+
+/// GC-free compiled bytecode for a function that top-level code will immediately invoke.
+pub struct PrecompiledFunction {
+ pub executable: Arc<ExecutableData>,
+ pub metadata: FunctionSfdMetadata,
+}
+
+#[derive(Clone, Copy)]
+pub enum PendingLiteralValueKind {
+ None,
+ Number,
+ BooleanTrue,
+ BooleanFalse,
+ Null,
+ String,
+}
+
+pub struct PendingClassElement {
+ pub kind: u8,
+ pub is_static: bool,
+ pub is_private: bool,
+ pub private_identifier: Option<Utf16String>,
+ pub shared_function_data_index: Option<u32>,
+ pub has_initializer: bool,
+ pub literal_value_kind: PendingLiteralValueKind,
+ pub literal_value_number: f64,
+ pub literal_value_string: Option<Utf16String>,
+}
+
+pub struct PendingClassBlueprint {
+ pub name: Option<Utf16String>,
+ pub source_text_offset: usize,
+ pub source_text_length: usize,
+ pub constructor_sfd_index: u32,
+ pub has_super_class: bool,
+ pub has_name: bool,
+ pub elements: Vec<PendingClassElement>,
+}
/// How many inline cache and feedback slots of each kind the bytecode indexes into.
#[derive(Clone, Copy)]
@@ -32,74 +124,79 @@ pub struct ExecutableCacheCounts {
pub keyed_feedback: u32,
}
-/// One compiled script, module or function body.
+/// Executable::LocalVariableMetadata
+#[derive(Clone, Copy)]
+pub struct LocalVariableMetadata {
+ pub is_mutable: bool,
+ /// The part of the source code in which the local variable is in scope.
+ pub scope_range: Option<crate::ast::SourceRange>,
+}
+
+/// One compiled script, module or function body: everything about it that does not depend on where it runs. Nothing
+/// here changes once it is compiled, so any number of [`Executable`]s can link it, each with caches, constants and
+/// functions of its own, and they all run the same bytecode.
///
/// Nested functions are compiled lazily: unless an entry of
-/// `shared_function_data` was precompiled, it keeps the AST payload that its
-/// bytecode is generated from when it is first called.
+/// `shared_function_data` was precompiled, it describes the function that gets
+/// parsed and compiled when it is first called.
+///
+/// [`Executable`]: super::executable::Executable
pub struct ExecutableData {
- pub bytecode: Vec<u8>,
- pub exception_handlers: Vec<ExceptionHandler>,
- pub source_map: Vec<SourceMapEntry>,
- pub basic_block_start_offsets: Vec<usize>,
+ pub bytecode: Box<[u8]>,
+ /// Sorted by start offset, and not overlapping.
+ pub exception_handlers: Box<[ExceptionHandler]>,
+ /// Sorted by bytecode offset: where in the source code the instructions from each offset on came from.
+ pub source_map: Box<[SourceMapEntry]>,
pub number_of_registers: u32,
pub number_of_arguments: u32,
pub is_strict: bool,
- pub this_value_needs_environment_resolution: bool,
pub cache_counts: ExecutableCacheCounts,
- pub identifier_table: Vec<ak::Utf16FlyString>,
- pub property_key_table: Vec<ak::Utf16FlyString>,
- pub string_table: Vec<ak::Utf16FlyString>,
- pub constants: Vec<ConstantValue>,
- pub local_variables: Vec<LocalVariable>,
- pub argument_variable_names: Vec<ak::Utf16FlyString>,
+ pub identifier_table: Box<[ak::Utf16FlyString]>,
+ pub string_table: Box<[ak::Utf16FlyString]>,
+ /// The names of the local variables, then the names of the arguments.
+ pub variable_names: Box<[ak::Utf16FlyString]>,
+ /// One for each of the local variables.
+ pub local_variable_metadata: Box<[LocalVariableMetadata]>,
pub length_identifier: Option<PropertyKeyTableIndex>,
- pub shared_function_data: Vec<PendingSharedFunctionData>,
- pub class_blueprints: Vec<PendingClassBlueprint>,
+ /// What linking reads, and nothing after it (see [`ExecutableData::release_link_inputs()`]).
+ pub property_key_table: Box<[ak::Utf16FlyString]>,
+ pub constants: Box<[ConstantValue]>,
+ pub shared_function_data: Box<[PendingSharedFunctionData]>,
+ pub class_blueprints: Box<[PendingClassBlueprint]>,
+ /// What turns the source offsets of a source map that has them into lines and columns.
+ pub position_source: Option<Arc<crate::parser::SourcePositions>>,
}
impl ExecutableData {
- pub fn new(generator: Generator, assembled: AssembledBytecode) -> Self {
- let arena = generator.arena;
- let shared_function_data = generator
- .shared_function_data
- .into_iter()
- .map(|mut shared_function_data| {
- shared_function_data.arena.get_or_insert_with(|| arena.clone());
- shared_function_data
- })
- .collect();
- Self {
- bytecode: assembled.bytecode,
- exception_handlers: assembled.exception_handlers,
- source_map: assembled.source_map,
- basic_block_start_offsets: assembled.basic_block_start_offsets,
- number_of_registers: assembled.number_of_registers,
- number_of_arguments: assembled.number_of_arguments,
- is_strict: generator.strict,
- this_value_needs_environment_resolution: generator.this_value_needs_environment_resolution,
- cache_counts: ExecutableCacheCounts {
- property_lookup: generator.next_property_lookup_cache,
- global_variable: generator.next_global_variable_cache,
- environment_coordinate: generator.next_environment_coordinate_cache,
- template_object: generator.next_template_object_cache,
- object_shape: generator.next_object_shape_cache,
- object_property_iterator: generator.next_object_property_iterator_cache,
- environment_shape: generator.next_environment_shape_cache,
- arith_feedback: generator.next_arith_feedback,
- value_feedback: generator.next_value_feedback,
- call_feedback: generator.next_call_feedback,
- keyed_feedback: generator.next_keyed_feedback,
+ /// The entries of the source map, with the lines and columns that they stand for. Code that goes by offsets of the
+ /// source leaves working those out until something asks.
+ pub fn source_positions(&self) -> impl Iterator<Item = crate::bytecode::source_map::SourceMapEntry> + '_ {
+ use crate::bytecode::source_map::SourceMapEntry;
+ use crate::bytecode::source_map::SourceOffset;
+ self.source_map.iter().map(|entry| match &self.position_source {
+ Some(_) if entry.column == SourceOffset::NONE.0 => SourceMapEntry {
+ bytecode_offset: entry.bytecode_offset,
+ line: 0,
+ column: 0,
},
- identifier_table: generator.identifier_table,
- property_key_table: generator.property_key_table,
- string_table: generator.string_table,
- constants: generator.constants,
- local_variables: generator.local_variables,
- argument_variable_names: generator.argument_variable_names,
- length_identifier: generator.length_identifier,
- shared_function_data,
- class_blueprints: generator.class_blueprints,
- }
+ Some(positions) => {
+ let position = positions.lines.position(entry.column);
+ SourceMapEntry {
+ bytecode_offset: entry.bytecode_offset,
+ line: position.line,
+ column: position.column,
+ }
+ }
+ None => *entry,
+ })
+ }
+
+ /// Frees what only linking reads, for an executable that is the last to hold this code, so that code nothing can
+ /// link again costs no more than what running it reads.
+ pub fn release_link_inputs(&mut self) {
+ self.property_key_table = Box::default();
+ self.constants = Box::default();
+ self.shared_function_data = Box::default();
+ self.class_blueprints = Box::default();
}
}
diff --git a/Libraries/LibJS/Rust/src/bytecode/feedback.rs b/Libraries/LibJS/Rust/src/bytecode/feedback.rs
index aedca8cdce8..48f4f0bff3e 100644
--- a/Libraries/LibJS/Rust/src/bytecode/feedback.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/feedback.rs
@@ -78,18 +78,6 @@ impl ExecutableFeedback {
unsafe { ak::slice_from_raw_parts(storage.data().add(offset).cast::<T>(), count as usize) }
}
- /// Takes over what `other`, the feedback of an executable with the same bytecode, observed.
- pub fn copy_from(&self, other: &ExecutableFeedback) {
- assert!(self.counts == other.counts, "the feedback has the same slots");
- if let (Some(storage), Some(other_storage)) = (&self.storage, &other.storage) {
- // SAFETY: Both storages hold `layout.size` bytes laid out for the same counts, and are distinct.
- unsafe { core::ptr::copy_nonoverlapping(other_storage.data(), storage.data(), self.layout.size) };
- }
- for (value, other_value) in self.value.iter().zip(&other.value) {
- value.set(other_value.get());
- }
- }
-
pub fn arith(&self) -> &[Cell<u8>] {
self.array(0, self.counts.arith)
}
diff --git a/Libraries/LibJS/Rust/src/bytecode/instruction.rs b/Libraries/LibJS/Rust/src/bytecode/instruction.rs
index 1f3c810995e..bd4394cf70f 100644
--- a/Libraries/LibJS/Rust/src/bytecode/instruction.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/instruction.rs
@@ -15,7 +15,7 @@ include!(concat!(env!("OUT_DIR"), "/instruction_generated.rs"));
#[cfg(test)]
mod tests {
use super::*;
- use crate::bytecode::generator::ConstantValue;
+ use crate::bytecode::executable_data::ConstantValue;
#[test]
fn selects_declarative_int32_specializations() {
diff --git a/Libraries/LibJS/Rust/src/bytecode/mod.rs b/Libraries/LibJS/Rust/src/bytecode/mod.rs
index b0486812ee5..9748969870d 100644
--- a/Libraries/LibJS/Rust/src/bytecode/mod.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/mod.rs
@@ -13,9 +13,8 @@
//!
//! - `operand` -- Register, Operand, Label, and table index types
//! - `instruction` -- Instruction enum (generated from interpreter.flap by build.rs)
-//! - `basic_block` -- BasicBlock: list of instructions with control flow metadata
-//! - `generator` -- Generator: manages registers, constants, tables, and assembly
-//! - `codegen` -- AST-walking code that emits instructions via the Generator
+//! - `source_map` -- Where in the source code instructions come from
+//! - `codegen` -- Generates bytecode from the columns of the syntax tree
//! - `constant` -- VM-dependent constants codegen refers to by kind
//! - `executable_data` -- ExecutableData: a compiled body and everything needed to run it
//!
@@ -26,15 +25,14 @@
//! - `executable` -- Executable: the cell that holds bytecode and its caches
//! - `feedback` -- What the profiling interpreter observes for the optimizing JIT, per executable
//! - `property_access` -- Property lookups through the inline caches
-//! - `class_blueprint`, `bytecode_cache` -- Classes and bytecode cache blobs as the runtime keeps them
+//! - `class_blueprint` -- Classes as the runtime keeps them
-pub mod basic_block;
-#[cfg(not(test))]
-pub mod bytecode_cache;
#[cfg(not(test))]
pub mod class_blueprint;
+#[path = "codegen/mod.rs"]
pub mod codegen;
pub mod constant;
+pub mod constant_fold;
#[cfg(not(test))]
pub mod dump;
pub mod encoded_value;
@@ -45,13 +43,13 @@ pub mod executable;
pub mod executable_data;
#[cfg(not(test))]
pub mod feedback;
-pub mod generator;
pub mod instruction;
mod native_disassembler;
pub mod operand;
#[cfg(not(test))]
pub mod property_access;
-pub mod validator;
+pub mod reference_text;
+pub mod source_map;
/// The view of an instruction in `op`, which lays out the instruction of its opcode in the bytecode.
///
@@ -72,8 +70,8 @@ pub fn instruction_at<Op: BytecodeOp>(executable: &executable::Executable, pc: u
let bytes = &executable.bytecode()[pc as usize..];
assert_eq!(bytes[0], Op::OPCODE);
assert!(size_of::<Op>() <= bytes.len() && bytes.as_ptr().addr().is_multiple_of(align_of::<Op>()));
- // SAFETY: Executables only hold validated bytecode, so an instruction of this opcode, with the layout of Op and
- // valid fields, starts at pc.
+ // SAFETY: Executables only hold bytecode the generator encoded, so an instruction of this opcode, with the layout
+ // of Op and valid fields, starts at pc.
let instruction = unsafe { &*bytes.as_ptr().cast::<Op>() };
assert!(instruction.length() as usize <= bytes.len());
instruction
diff --git a/Libraries/LibJS/Rust/src/bytecode/operand.rs b/Libraries/LibJS/Rust/src/bytecode/operand.rs
index 4972e1f9d82..09911264c2e 100644
--- a/Libraries/LibJS/Rust/src/bytecode/operand.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/operand.rs
@@ -4,6 +4,29 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+/// Why the length of the encoded instruction at some offset cannot be told.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum InstructionLengthError {
+ UnknownOpcode,
+ TruncatedInstruction,
+ InvalidLength,
+}
+
+#[inline]
+pub fn read_u16(bytes: &[u8], at: usize) -> u16 {
+ u16::from_ne_bytes(bytes[at..at + 2].try_into().unwrap())
+}
+
+#[inline]
+pub fn read_u32(bytes: &[u8], at: usize) -> u32 {
+ u32::from_ne_bytes(bytes[at..at + 4].try_into().unwrap())
+}
+
+#[inline]
+pub fn read_u64(bytes: &[u8], at: usize) -> u64 {
+ u64::from_ne_bytes(bytes[at..at + 8].try_into().unwrap())
+}
+
/// A bytecode register index.
///
/// Reserved registers:
@@ -73,6 +96,10 @@ impl Operand {
!self.is_invalid() && self.operand_type() == OperandType::Local
}
+ pub fn is_argument(self) -> bool {
+ !self.is_invalid() && self.operand_type() == OperandType::Argument
+ }
+
pub fn is_constant(self) -> bool {
!self.is_invalid() && self.operand_type() == OperandType::Constant
}
@@ -107,7 +134,7 @@ impl Operand {
/// Offset the index by the given amount, stripping the type tag and
/// leaving a flat index into the combined
/// [registers | locals | constants | arguments] array.
- /// Used during operand rewriting in the assembler.
+ /// Used when the operands of finished code get their final indices.
pub fn offset_index_by(&mut self, offset: u32) {
self.0 &= Self::INDEX_MASK;
self.0 = self.0.checked_add(offset).expect("operand index overflow");
@@ -127,14 +154,10 @@ pub enum OperandType {
/// During compilation, holds a basic block index. After linking,
/// holds the final byte offset in the flat bytecode stream.
/// Stored as a single `u32`.
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Label(pub u32);
-impl Label {
- pub fn basic_block_index(self) -> usize {
- self.0 as usize
- }
-}
+impl Label {}
/// Index into the string table.
#[derive(Debug, Clone, Copy)]
diff --git a/Libraries/LibJS/Rust/src/compile.rs b/Libraries/LibJS/Rust/src/compile.rs
index 116862090fe..81e1b7aad7b 100644
--- a/Libraries/LibJS/Rust/src/compile.rs
+++ b/Libraries/LibJS/Rust/src/compile.rs
@@ -14,30 +14,46 @@
//! Nothing here needs the VM, so a runtime can also parse and compile on
//! another thread with [`compile_parsed_program_off_thread()`] and finish the
//! script or module on its main thread.
+//!
+//! A syntax tree only lives as long as the compile job that needs it. All that
+//! a function that has not run yet holds on to is a [`FunctionPayload`], and it
+//! gets parsed and compiled on its own by [`compile_function()`].
use crate::ast;
+use crate::ast::FunctionId;
+use crate::ast::ProgramType;
+use crate::ast::Sequence;
use crate::ast::StatementKind;
+use crate::ast::SyntaxTree;
use crate::ast_dump;
use crate::bytecode;
use crate::bytecode::executable_data::ExecutableData;
-use crate::bytecode::generator::PendingSharedFunctionData;
+use crate::bytecode::executable_data::PendingSharedFunctionData;
+use crate::parser::EnclosingCode;
+use crate::parser::FunctionRow;
+use crate::parser::OutOfStack;
use crate::parser::ParseError;
-use crate::parser::Parser;
-use crate::parser::ProgramType;
-use crate::u32_from_usize;
+use crate::parser::ParseOptions;
+use crate::parser::ScriptData;
+use crate::parser::check_syntax;
+use crate::parser::parse_to_tree;
+use crate::utf16::Utf16View;
+use ak::Utf16String;
use std::collections::HashSet;
+use std::sync::Arc;
-// Compile-time assertion: what parse and compile produce travels from a worker
-// thread to the main thread, so it must be `Send`. After the StringId and
-// ScopeId arena migrations the AST itself contains no `Rc`/`Cell`/`RefCell`
-// values, so this is naturally satisfied without `unsafe impl Send`.
+// Compile-time assertion: what parse and compile produce travels from a worker thread to the main thread.
const _: fn() = || {
fn assert_send<T: Send>() {}
+ fn assert_send_and_sync<T: Send + Sync>() {}
assert_send::<ParsedProgram>();
assert_send::<CompiledProgram>();
assert_send::<CompiledScript>();
assert_send::<CompiledModule>();
- assert_send::<bytecode::generator::PrecompiledFunction>();
+ assert_send_and_sync::<bytecode::executable_data::PrecompiledFunction>();
+ assert_send_and_sync::<ExecutableData>();
+ assert_send_and_sync::<SyntaxTree>();
+ assert_send_and_sync::<ScriptData>();
};
// =============================================================================
@@ -47,18 +63,33 @@ const _: fn() = || {
/// A parsed program (script or module) that can be compiled later.
/// Contains no GC references, so it can safely be transferred between threads.
pub struct ParsedProgram {
- pub(crate) program: ast::Statement,
- pub(crate) function_table: ast::FunctionTable,
- pub(crate) arena: std::sync::Arc<ast::AstArena>,
- pub(crate) scope_ref: ast::ScopeId,
+ /// The tree, unless the program has errors.
+ pub(crate) tree: Option<Arc<SyntaxTree>>,
pub(crate) program_type: ast::ProgramType,
pub(crate) is_strict_mode: bool,
pub(crate) has_top_level_await: bool,
pub(crate) errors: Vec<ParseError>,
pub(crate) ast_dump: Option<String>,
+ options: ParseOptions,
}
impl ParsedProgram {
+ fn from_tree(tree: SyntaxTree, options: ParseOptions) -> Self {
+ Self {
+ program_type: tree.program_type(),
+ is_strict_mode: tree.is_strict_mode(),
+ has_top_level_await: tree.has_top_level_await(),
+ tree: Some(Arc::new(tree)),
+ errors: Vec::new(),
+ ast_dump: None,
+ options,
+ }
+ }
+
+ pub(crate) fn tree(&self) -> &Arc<SyntaxTree> {
+ self.tree.as_ref().expect("a program without errors has a tree")
+ }
+
pub fn has_errors(&self) -> bool {
!self.errors.is_empty()
}
@@ -79,30 +110,24 @@ impl ParsedProgram {
self.has_top_level_await
}
- /// The textual AST dump, generated on first use.
+ /// The textual AST dump of the whole program, which parses it again to get the tree of everything, generated on
+ /// first use.
pub fn ast_dump(&mut self) -> &str {
- self.ast_dump
- .get_or_insert_with(|| ast_dump::dump_program_to_string(&self.program, &self.function_table, &self.arena))
- }
-
- /// A copy of a program without errors that compiles independently of this one, such as for the bytecode cache
- /// while this one runs. The immutable arena is shared, and each copy owns its functions.
- ///
- /// # Panics
- /// Panics if the program has errors.
- pub fn clone_for_separate_compilation(&self) -> ParsedProgram {
- assert!(self.errors.is_empty(), "only a program without errors can be copied");
- ParsedProgram {
- program: self.program.clone(),
- function_table: self.function_table.clone(),
- arena: self.arena.clone(),
- scope_ref: self.scope_ref,
- program_type: self.program_type,
- is_strict_mode: self.is_strict_mode,
- has_top_level_await: self.has_top_level_await,
- errors: Vec::new(),
- ast_dump: None,
- }
+ self.ast_dump.get_or_insert_with(|| {
+ let source = &self
+ .tree
+ .as_ref()
+ .expect("the program has a tree")
+ .script
+ .positions
+ .source;
+ let mut options = self.options;
+ options.keep_whole_tree = true;
+ let tree = parse_to_tree(source, &options)
+ .ok()
+ .expect("a program without errors parses the same way again");
+ ast_dump::dump_program_to_string(&Arc::new(tree))
+ })
}
}
@@ -112,140 +137,61 @@ impl ParsedProgram {
/// so check [`ParsedProgram::has_errors()`] before compiling it. Lines are
/// counted from `initial_line_number`, except that a module always starts at
/// line 1 or later.
-pub fn parse(source: &[u16], program_type: ProgramType, initial_line_number: usize) -> ParsedProgram {
+pub fn parse(source: &ak::Utf16String, program_type: ProgramType, initial_line_number: usize) -> ParsedProgram {
let initial_line_number = if program_type == ProgramType::Module && initial_line_number == 0 {
1
} else {
initial_line_number
};
- let mut parser = Parser::new_with_line_offset(source, program_type, u32_from_usize(initial_line_number));
-
- let program = parser.parse_program(false);
-
- // Collect errors from both parser and scope collector.
- let mut errors = parser.take_errors();
- if errors.is_empty() {
- errors = parser.scope_collector.drain_errors();
- }
-
- if errors.is_empty() {
- parser.scope_collector.analyze(
- false,
- &mut parser.arena.identifiers,
- &parser.arena.strings,
- &mut parser.arena.scopes,
- );
- }
-
- let (scope_ref, is_strict, has_tla) = if errors.is_empty()
- && let StatementKind::Program(ref data) = program.inner
- {
- (data.scope, data.is_strict_mode, data.has_top_level_await)
- } else {
- (parser.arena.scopes.insert(ast::ScopeData::default()), false, false)
- };
-
- ParsedProgram {
- program,
- function_table: std::mem::take(&mut parser.function_table),
- arena: std::sync::Arc::new(std::mem::take(&mut parser.arena)),
- scope_ref,
- program_type,
- is_strict_mode: is_strict,
- has_top_level_await: has_tla,
- errors,
- ast_dump: None,
+ let mut options = ParseOptions::new(program_type);
+ options.initial_line_number = crate::u32_from_usize(initial_line_number);
+ match parse_to_tree(source, &options) {
+ Ok(tree) => ParsedProgram::from_tree(tree, options),
+ Err(errors) => ParsedProgram {
+ tree: None,
+ program_type,
+ is_strict_mode: false,
+ has_top_level_await: false,
+ errors,
+ ast_dump: None,
+ options,
+ },
}
}
+/// A script or module compiled to bytecode, with what its record needs from its code. The syntax tree is gone by now, so
+/// a compiled program holds no more of its source than the functions that have yet to compile need.
pub struct CompiledProgram {
- /// Its function table holds the functions that codegen left for declaration instantiation.
- pub(crate) parsed: ParsedProgram,
- pub(crate) bytecode: CompiledProgramBytecode,
- pub(crate) declaration_functions: Vec<PendingSharedFunctionData>,
- pub(crate) source_len: usize,
- function_precompile_mode: FunctionPrecompileMode,
-}
-
-pub(crate) enum CompiledProgramBytecode {
- Program(ExecutableData),
- AsyncModule(ExecutableData),
-}
-
-/// Convert scope local variables to generator LocalVariable format.
-fn convert_local_variables(scope: &ast::ScopeData) -> Vec<bytecode::generator::LocalVariable> {
- scope
- .local_variables
- .iter()
- .map(|lv| bytecode::generator::LocalVariable {
- name: ak::Utf16FlyString::from_utf16(&lv.name),
- is_lexically_declared: lv.kind == ast::LocalVarKind::LetOrConst,
- is_initialized_during_declaration_instantiation: false,
- is_mutable: lv.is_mutable,
- scope_range: lv.scope_range,
- })
- .collect()
+ program_type: ProgramType,
+ has_top_level_await: bool,
+ executable: Arc<ExecutableData>,
+ declarations: CompiledProgramDeclarations,
}
-/// Create a Generator configured for program-level compilation.
-pub(crate) fn new_program_generator(strict: bool, source_len: usize) -> bytecode::generator::Generator {
- let mut generator = bytecode::generator::Generator::new();
- generator.strict = strict;
- generator.must_propagate_completion = true;
- generator.source_len = source_len;
- generator
+enum CompiledProgramDeclarations {
+ Script(Arc<ScriptDeclarations>),
+ Module(Arc<ModuleDeclarations>),
}
-/// Shared codegen pipeline: local variable setup → bytecode generation → assembly.
-///
-/// This deliberately stops before `create_executable()`, because executable materialization creates GC-managed objects
-/// and resolves VM-specific constants. Keeping that work separate lets WebContent perform the expensive AST-to-bytecode
-/// pass on a worker thread while preserving all main-thread ownership rules for VM and heap data.
-pub(crate) fn compile_program_body_to_bytecode(
- generator: &mut bytecode::generator::Generator,
- program: &ast::Statement,
- scope_id: ast::ScopeId,
-) -> bytecode::generator::AssembledBytecode {
- let arena_clone = generator.arena.clone();
- generator.local_variables = convert_local_variables(&arena_clone.scopes[scope_id]);
- if let StatementKind::Program(data) = &program.inner
- && data.program_type == ProgramType::Module
- {
- generator.enclosing_environment_scope =
- Some(module_environment_scope(&arena_clone.scopes[scope_id], &arena_clone));
- }
-
- let entry_block = generator.make_block();
- generator.switch_to_basic_block(entry_block);
- generator.emit(bytecode::instruction::Instruction::Enter {});
- generator.capture_saved_lexical_environment();
-
- let result = bytecode::codegen::generate_statement(program, generator, None);
-
- if !generator.is_current_block_terminated()
- && let Some(value) = result
- {
- generator.emit(bytecode::instruction::Instruction::End { value: value.operand() });
- }
- // If result is None, the assembler will add End(undefined) as a fallthrough for unterminated blocks.
-
- generator.assemble()
+/// The scope of the program of `tree`.
+fn program_scope(tree: &SyntaxTree) -> ast::Scope<'_> {
+ let StatementKind::Program(data) = tree.program().kind() else {
+ unreachable!("the root of a tree is a program");
+ };
+ data.scope
}
/// A compiled script and what GlobalDeclarationInstantiation needs to run it.
pub struct CompiledScript {
- pub executable: ExecutableData,
- pub declarations: ScriptDeclarations,
+ pub executable: Arc<ExecutableData>,
+ pub declarations: Arc<ScriptDeclarations>,
}
/// Compile a script that parsed without errors.
///
-/// `source_len` is the length of the source code in UTF-16 code units, which
-/// the source ranges of the script's functions must fit in.
-///
/// # Panics
/// Panics if `parsed` is a module or has errors.
-pub fn compile_script(mut parsed: ParsedProgram, source_len: usize) -> CompiledScript {
+pub fn compile_script(parsed: ParsedProgram) -> CompiledScript {
assert!(
parsed.program_type == ProgramType::Script,
"compile_script() needs a script, not a module"
@@ -255,18 +201,17 @@ pub fn compile_script(mut parsed: ParsedProgram, source_len: usize) -> CompiledS
"compile_script() needs a script without parse errors"
);
- let mut generator = new_program_generator(parsed.is_strict_mode, source_len);
- generator.function_table = std::mem::take(&mut parsed.function_table);
- generator.arena = parsed.arena.clone();
- let assembled = compile_program_body_to_bytecode(&mut generator, &parsed.program, parsed.scope_ref);
- let mut function_table = std::mem::take(&mut generator.function_table);
- let executable = ExecutableData::new(generator, assembled);
-
- let declarations = collect_script_declarations(
- &parsed.arena.scopes[parsed.scope_ref],
- &mut function_table,
- &parsed.arena,
- );
+ let tree = parsed.tree().clone();
+ let executable = Arc::new(compile_program(
+ &tree,
+ ProgramOptions {
+ strict: parsed.is_strict_mode,
+ is_async_module: false,
+ eager_compile_direct_iifes: false,
+ },
+ ));
+
+ let declarations = Arc::new(collect_script_declarations(&tree));
CompiledScript {
executable,
@@ -274,349 +219,130 @@ pub fn compile_script(mut parsed: ParsedProgram, source_len: usize) -> CompiledS
}
}
-/// Which of the functions nested in the code being compiled get their bytecode right away, rather than when they are
-/// first called.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum FunctionPrecompileMode {
- /// Only those that codegen expects to run right away, such as immediately invoked function expressions.
- EagerOnly,
- /// All of them, which the bytecode cache and the breakpoint positions of a source need.
- All,
-}
-
-fn precompile_functions(generator: &mut bytecode::generator::Generator, mode: FunctionPrecompileMode) {
- for pending in &mut generator.shared_function_data {
- if pending.precompiled_function.is_some() {
- continue;
- }
- if matches!(mode, FunctionPrecompileMode::EagerOnly) && !pending.should_eager_compile {
- continue;
- }
-
- let function_data = pending
- .function_data
- .take()
- .expect("pending eager function data was already materialized");
- let subtable = pending
- .subtable
- .take()
- .expect("pending eager function subtable was already materialized");
- let arena = pending.arena.clone().unwrap_or_else(|| generator.arena.clone());
- let payload = ast::FunctionPayload {
- data: *function_data,
- function_table: subtable,
- arena: arena.clone(),
- enclosing_environment_scope: pending.enclosing_environment_scope.clone(),
- };
- let (function_data, precompiled) = compile_function_payload_to_bytecode(
- payload,
- generator.source_len,
- generator.builtin_abstract_operations_enabled,
- arena,
- mode,
- );
-
- pending.function_data = Some(function_data);
- // The precompiled executable owns any nested lazy function payloads. Keep
- // an empty payload here only until materialization creates the SFD; it is
- // immediately cleared after the precompiled executable is attached.
- pending.subtable = Some(ast::FunctionTable::new());
- pending.precompiled_function = Some(precompiled);
+/// The lowest address that compiling a program on this thread may take the stack to. A program has no VM to ask, as it
+/// can compile on any thread, but it may run as deep as what the code of a function may.
+fn stack_limit_of_this_thread() -> usize {
+ match crate::parser::vm_stack_limit_of_this_thread() {
+ Some(limit) => limit.saturating_add(STACK_FOR_SMALL_WALKS),
+ None => crate::parser::stack_limit_for_budget(crate::parser::base::DEFAULT_STACK_BUDGET),
}
}
-fn precompile_declaration_functions(
- program_type: ast::ProgramType,
- scope_id: ast::ScopeId,
- generator: &mut bytecode::generator::Generator,
- mode: FunctionPrecompileMode,
-) -> Vec<PendingSharedFunctionData> {
- if mode != FunctionPrecompileMode::All {
- return Vec::new();
- }
-
- match program_type {
- ast::ProgramType::Script => precompile_script_declaration_functions(scope_id, generator, mode),
- ast::ProgramType::Module => precompile_module_declaration_functions(scope_id, generator, mode),
- }
+/// What the kinds of programs differ in, as far as generating their code goes.
+#[derive(Clone, Copy)]
+struct ProgramOptions {
+ strict: bool,
+ /// Whether the program is a module with top-level await, which runs like an async function.
+ is_async_module: bool,
+ eager_compile_direct_iifes: bool,
}
-fn precompile_script_declaration_functions(
- scope_id: ast::ScopeId,
- generator: &mut bytecode::generator::Generator,
- mode: FunctionPrecompileMode,
-) -> Vec<PendingSharedFunctionData> {
- let arena = generator.arena.clone();
- let scope = &arena.scopes[scope_id];
- let mut last_position: std::collections::HashMap<ast::StringId, usize> = std::collections::HashMap::new();
- for (index, child) in scope.children.iter().enumerate() {
- if let Some(function) = child.inner.function_declaration_for_labelled_item()
- && let Some(name) = function.name
- {
- last_position.insert(arena.identifiers[name].name, index);
- }
- }
-
- let mut declaration_functions = Vec::new();
- for (index, child) in scope.children.iter().enumerate() {
- if let Some(function) = child.inner.function_declaration_for_labelled_item()
- && let Some(name) = function.name
- && last_position.get(&arena.identifiers[name].name).copied() == Some(index)
- {
- declaration_functions.push(precompile_declaration_function(
- function.function_id,
- None,
- None,
- generator,
- mode,
- ));
- }
- }
-
- declaration_functions
-}
-
-fn precompile_module_declaration_functions(
- scope_id: ast::ScopeId,
- generator: &mut bytecode::generator::Generator,
- mode: FunctionPrecompileMode,
-) -> Vec<PendingSharedFunctionData> {
- use ast::StatementKind;
-
- let arena = generator.arena.clone();
- let scope = &arena.scopes[scope_id];
- let default_name: ast::Utf16String = utf16!("*default*").into();
- let module_environment_scope = module_environment_scope(scope, &arena);
- let mut declaration_functions = Vec::new();
- for child in &scope.children {
- let (declaration, is_exported) = match &child.inner {
- StatementKind::Export(export_data) => {
- if let Some(ref statement) = export_data.statement {
- (&statement.inner, true)
- } else {
- continue;
- }
- }
- other => (other, false),
- };
-
- if let StatementKind::FunctionDeclaration(function) = declaration {
- let is_default = is_exported
- && function
- .name
- .is_some_and(|name| arena.name_slice(name) == default_name.as_slice());
- let name_override = if is_default {
- Some(utf16!("default").into())
- } else {
- None
- };
- declaration_functions.push(precompile_declaration_function(
- function.function_id,
- name_override,
- Some(module_environment_scope.clone()),
- generator,
- mode,
- ));
- }
- }
-
- declaration_functions
-}
-
-fn precompile_declaration_function(
- function_id: ast::FunctionId,
- name_override: Option<ast::Utf16String>,
- enclosing_environment_scope: Option<std::sync::Arc<bytecode::generator::EnclosingEnvironmentScope>>,
- generator: &mut bytecode::generator::Generator,
- mode: FunctionPrecompileMode,
-) -> PendingSharedFunctionData {
- let function_data = generator.function_table.take(function_id);
- let arena = generator.arena.clone();
- let subtable = generator
- .function_table
- .extract_reachable(&function_data, &arena.scopes);
- let payload = ast::FunctionPayload {
- data: *function_data,
- function_table: subtable,
- arena: arena.clone(),
- enclosing_environment_scope: enclosing_environment_scope.clone(),
+/// Generates the code of the program of `tree`.
+fn compile_program(tree: &Arc<SyntaxTree>, options: ProgramOptions) -> ExecutableData {
+ let is_module = options.is_async_module || tree.program_type() == ProgramType::Module;
+ let input = bytecode::codegen::ProgramInput {
+ tree,
+ strict: options.strict,
+ is_async_module: options.is_async_module,
+ eager_compile_direct_iifes: options.eager_compile_direct_iifes,
+ enclosing_environment_scope: is_module.then(|| module_environment_scope(&program_scope(tree))),
+ stack_limit: stack_limit_of_this_thread(),
};
- let (function_data, precompiled_function) = compile_function_payload_to_bytecode(
- payload,
- generator.source_len,
- generator.builtin_abstract_operations_enabled,
- arena.clone(),
- mode,
- );
-
- PendingSharedFunctionData {
- function_data: Some(function_data),
- subtable: Some(ast::FunctionTable::new()),
- arena: Some(arena),
- name_override,
- class_field_initializer_name: None,
- should_eager_compile: false,
- precompiled_function: Some(precompiled_function),
- enclosing_environment_scope,
- }
+ bytecode::codegen::compile_program(&input)
+ .unwrap_or_else(|_| bytecode::codegen::compile_program_too_deep_to_generate(tree))
}
-/// Compiles a script or module that parsed without errors from `source_len` code units, which needs no VM and so can
-/// run on any thread.
-///
-/// A program compiled with [`FunctionPrecompileMode::EagerOnly`] is meant to run: the main thread finishes it with
-/// [`CompiledProgram::into_script()`] or [`CompiledProgram::into_module()`]. One compiled with
-/// [`FunctionPrecompileMode::All`] is meant for the bytecode cache and for breakpoint positions.
+/// Compiles a script or module that parsed without errors, which needs no VM and so can run on any thread. The main thread
+/// finishes it with [`CompiledProgram::into_script()`] or [`CompiledProgram::into_module()`].
///
/// # Panics
/// Panics if `parsed` has errors.
-pub fn compile_parsed_program_off_thread(
- mut parsed: ParsedProgram,
- source_len: usize,
- function_precompile_mode: FunctionPrecompileMode,
-) -> CompiledProgram {
+pub fn compile_parsed_program_off_thread(parsed: ParsedProgram) -> CompiledProgram {
assert!(
!parsed.has_errors(),
"compile_parsed_program_off_thread() needs a program without parse errors"
);
- let arena_arc = parsed.arena.clone();
- let (bytecode, declaration_functions) = if parsed.has_top_level_await {
- let mut generator = new_module_async_generator(source_len, std::mem::take(&mut parsed.function_table));
- generator.arena = arena_arc;
- generator.eager_compile_direct_iifes = true;
- let assembled = compile_module_as_async_to_bytecode(&parsed.program, parsed.scope_ref, &mut generator);
- let declaration_functions = precompile_declaration_functions(
- parsed.program_type,
- parsed.scope_ref,
- &mut generator,
- function_precompile_mode,
- );
- precompile_functions(&mut generator, function_precompile_mode);
- parsed.function_table = std::mem::take(&mut generator.function_table);
- (
- CompiledProgramBytecode::AsyncModule(ExecutableData::new(generator, assembled)),
- declaration_functions,
- )
- } else {
- let mut generator = new_program_generator(parsed.is_strict_mode, source_len);
- generator.arena = arena_arc;
- generator.eager_compile_direct_iifes = true;
- generator.function_table = std::mem::take(&mut parsed.function_table);
- let assembled = compile_program_body_to_bytecode(&mut generator, &parsed.program, parsed.scope_ref);
- let declaration_functions = precompile_declaration_functions(
- parsed.program_type,
- parsed.scope_ref,
- &mut generator,
- function_precompile_mode,
- );
- precompile_functions(&mut generator, function_precompile_mode);
- parsed.function_table = std::mem::take(&mut generator.function_table);
- (
- CompiledProgramBytecode::Program(ExecutableData::new(generator, assembled)),
- declaration_functions,
- )
+ let tree = parsed.tree().clone();
+ let executable = Arc::new(compile_program(
+ &tree,
+ ProgramOptions {
+ strict: parsed.has_top_level_await || parsed.is_strict_mode,
+ is_async_module: parsed.has_top_level_await,
+ eager_compile_direct_iifes: true,
+ },
+ ));
+ let declarations = match parsed.program_type {
+ ProgramType::Script => CompiledProgramDeclarations::Script(Arc::new(collect_script_declarations(&tree))),
+ ProgramType::Module => CompiledProgramDeclarations::Module(Arc::new(collect_module_declarations(&tree))),
};
+ tree.script.index.prepare_for_reparsing();
+
CompiledProgram {
- parsed,
- bytecode,
- declaration_functions,
- source_len,
- function_precompile_mode,
+ program_type: parsed.program_type,
+ has_top_level_await: parsed.has_top_level_await,
+ executable,
+ declarations,
}
}
impl CompiledProgram {
pub fn program_type(&self) -> ProgramType {
- self.parsed.program_type
+ self.program_type
}
pub fn has_top_level_await(&self) -> bool {
- self.parsed.has_top_level_await
- }
-
- pub fn function_precompile_mode(&self) -> FunctionPrecompileMode {
- self.function_precompile_mode
+ self.has_top_level_await
}
- /// Finishes a script compiled with [`FunctionPrecompileMode::EagerOnly`] into what [`compile_script()`] returns.
+ /// Finishes a script into what [`compile_script()`] returns.
///
/// # Panics
- /// Panics if the program is a module or was compiled with [`FunctionPrecompileMode::All`].
+ /// Panics if the program is a module.
pub fn into_script(self) -> CompiledScript {
- assert!(
- self.parsed.program_type == ProgramType::Script,
- "into_script() needs a script, not a module"
- );
- assert!(
- self.function_precompile_mode == FunctionPrecompileMode::EagerOnly,
- "into_script() needs a script compiled to run, not one compiled for the bytecode cache"
- );
- let CompiledProgram {
- mut parsed, bytecode, ..
- } = self;
- let CompiledProgramBytecode::Program(executable) = bytecode else {
- unreachable!("only a module with top-level await compiles to an async function body");
+ let CompiledProgramDeclarations::Script(declarations) = self.declarations else {
+ panic!("into_script() needs a script, not a module");
};
- let declarations = collect_script_declarations(
- &parsed.arena.scopes[parsed.scope_ref],
- &mut parsed.function_table,
- &parsed.arena,
- );
CompiledScript {
- executable,
+ executable: self.executable,
declarations,
}
}
- /// Finishes a module compiled with [`FunctionPrecompileMode::EagerOnly`] into what [`compile_module()`] returns.
+ /// Finishes a module into what [`compile_module()`] returns.
///
/// # Panics
- /// Panics if the program is a script or was compiled with [`FunctionPrecompileMode::All`].
+ /// Panics if the program is a script.
pub fn into_module(self) -> CompiledModule {
- assert!(
- self.parsed.program_type == ProgramType::Module,
- "into_module() needs a module, not a script"
- );
- assert!(
- self.function_precompile_mode == FunctionPrecompileMode::EagerOnly,
- "into_module() needs a module compiled to run, not one compiled for the bytecode cache"
- );
- let CompiledProgram {
- mut parsed, bytecode, ..
- } = self;
- let declarations = collect_module_declarations(
- &parsed.arena.scopes[parsed.scope_ref],
- parsed.has_top_level_await,
- &mut parsed.function_table,
- &parsed.arena,
- );
- let (CompiledProgramBytecode::Program(executable) | CompiledProgramBytecode::AsyncModule(executable)) =
- bytecode;
+ let CompiledProgramDeclarations::Module(declarations) = self.declarations else {
+ panic!("into_module() needs a module, not a script");
+ };
CompiledModule {
- executable,
+ executable: self.executable,
declarations,
}
}
}
/// Returns the name of the binding that holds the value of `export default <expression>`, if the module has one.
-pub(crate) fn module_default_export_binding_name(scope: &ast::ScopeData) -> Option<&ast::Utf16String> {
- use ast::StatementKind;
-
+pub(crate) fn module_default_export_binding_name(scope: &ast::Scope) -> Option<Utf16String> {
for child in &scope.children {
- let StatementKind::Export(ref export_data) = child.inner else {
+ let StatementKind::Export(export_data) = child.kind() else {
continue;
};
- if !export_data.is_default_export || export_data.entries.len() != 1 {
+ if !export_data.is_default_export {
+ continue;
+ }
+ let entries = export_data.entries();
+ if entries.len() != 1 {
continue;
}
// If the default export is not a declaration (function/class/etc.),
// its binding name is the local_or_import_name.
- let is_declaration = export_data.statement.as_ref().is_some_and(|s| {
+ let is_declaration = export_data.statement.as_ref().is_some_and(|statement| {
matches!(
- s.inner,
+ statement.kind(),
StatementKind::FunctionDeclaration(_) | StatementKind::ClassDeclaration(_)
)
});
@@ -624,18 +350,18 @@ pub(crate) fn module_default_export_binding_name(scope: &ast::ScopeData) -> Opti
continue;
}
- let entry = &export_data.entries[0];
+ let entry = &entries[0];
let is_specific_import_export = scope.children.iter().any(|child| {
- let StatementKind::Import(ref import_data) = child.inner else {
+ let StatementKind::Import(import_data) = child.kind() else {
return false;
};
- import_data.entries.iter().any(|import_entry| {
+ import_data.entries().iter().any(|import_entry| {
entry.local_or_import_name.as_ref() == Some(&import_entry.local_name)
&& import_entry.import_name.is_some()
})
});
if !is_specific_import_export {
- return entry.local_or_import_name.as_ref();
+ return entry.local_or_import_name.clone();
}
}
None
@@ -643,23 +369,21 @@ pub(crate) fn module_default_export_binding_name(scope: &ast::ScopeData) -> Opti
/// Returns the names of a module's own bindings, in the order that `SourceTextModule::initialize_environment()`
/// creates them in the module environment.
-fn module_environment_binding_names(scope: &ast::ScopeData, arena: &ast::AstArena) -> Vec<ak::Utf16FlyString> {
- use ast::StatementKind;
-
+fn module_environment_binding_names(scope: &ast::Scope) -> Vec<ak::Utf16FlyString> {
let mut names = Vec::new();
let mut var_names = HashSet::new();
for child in &scope.children {
- collect_module_var_names(&child.inner, arena, &mut |name| {
- if var_names.insert(name.to_vec()) {
- names.push(ak::Utf16FlyString::from_utf16(name));
+ collect_module_var_names(&child, &mut |name| {
+ if var_names.insert(Utf16String::from(name)) {
+ names.push(name.to_utf16_fly_string());
}
});
}
for child in &scope.children {
- let declaration = match &child.inner {
- StatementKind::Export(export_data) => match &export_data.statement {
- Some(statement) => &statement.inner,
+ let declaration = match child.kind() {
+ StatementKind::Export(export_data) => match export_data.statement {
+ Some(statement) => statement.kind(),
None => continue,
},
other => other,
@@ -668,25 +392,25 @@ fn module_environment_binding_names(scope: &ast::ScopeData, arena: &ast::AstAren
match declaration {
StatementKind::FunctionDeclaration(function) => {
if let Some(name) = function.name {
- names.push(ak::Utf16FlyString::from_utf16(arena.name_slice(name)));
+ names.push(name.text().to_utf16_fly_string());
}
}
StatementKind::ClassDeclaration(class_data) => {
if let Some(name) = class_data.name {
- names.push(ak::Utf16FlyString::from_utf16(arena.name_slice(name)));
+ names.push(name.text().to_utf16_fly_string());
}
}
- StatementKind::VariableDeclaration(vd) if vd.kind != ast::DeclarationKind::Var => {
- for declaration in &vd.declarations {
- for_each_bound_name(&declaration.target, arena, &mut |name| {
- names.push(ak::Utf16FlyString::from_utf16(name));
+ StatementKind::VariableDeclaration(declaration) if declaration.kind != ast::DeclarationKind::Var => {
+ for declarator in &declaration.declarations {
+ for_each_bound_name(&declarator.target, &mut |name| {
+ names.push(name.to_utf16_fly_string());
});
}
}
- StatementKind::UsingDeclaration(declarations) => {
- for declaration in &declarations.declarations {
- for_each_bound_name(&declaration.target, arena, &mut |name| {
- names.push(ak::Utf16FlyString::from_utf16(name));
+ StatementKind::UsingDeclaration(declaration) => {
+ for declarator in &declaration.declarations {
+ for_each_bound_name(&declarator.target, &mut |name| {
+ names.push(name.to_utf16_fly_string());
});
}
}
@@ -695,132 +419,64 @@ fn module_environment_binding_names(scope: &ast::ScopeData, arena: &ast::AstAren
}
if let Some(name) = module_default_export_binding_name(scope) {
- names.push(ak::Utf16FlyString::from_utf16(name.as_slice()));
+ names.push(Utf16View::of_string(&name).to_utf16_fly_string());
}
names
}
/// Returns the local names of a module's import entries, in the order of `SourceTextModule`'s import entries.
-fn module_import_names(scope: &ast::ScopeData) -> Vec<ak::Utf16FlyString> {
+fn module_import_names(scope: &ast::Scope) -> Vec<ak::Utf16FlyString> {
let mut names = Vec::new();
for child in &scope.children {
- if let StatementKind::Import(ref import_data) = child.inner {
- for entry in &import_data.entries {
- names.push(ak::Utf16FlyString::from_utf16(entry.local_name.as_slice()));
+ if let StatementKind::Import(import_data) = child.kind() {
+ for entry in import_data.entries() {
+ names.push(Utf16View::of_string(&entry.local_name).to_utf16_fly_string());
}
}
}
names
}
-pub(crate) fn module_environment_scope(
- scope: &ast::ScopeData,
- arena: &ast::AstArena,
-) -> std::sync::Arc<bytecode::generator::EnclosingEnvironmentScope> {
- bytecode::generator::EnclosingEnvironmentScope::for_module_environment(
- module_environment_binding_names(scope, arena),
+pub(crate) fn module_environment_scope(scope: &ast::Scope) -> Arc<bytecode::codegen::EnclosingEnvironmentScope> {
+ bytecode::codegen::EnclosingEnvironmentScope::for_module_environment(
+ module_environment_binding_names(scope),
module_import_names(scope),
)
}
/// Recursively collect var declared names for module scope.
-pub(crate) fn collect_module_var_names(
- statement: &ast::StatementKind,
- arena: &ast::AstArena,
- f: &mut dyn FnMut(&[u16]),
-) {
- match statement {
- ast::StatementKind::VariableDeclaration(vd) if vd.kind == ast::DeclarationKind::Var => {
- for declaration in &vd.declarations {
- for_each_bound_name(&declaration.target, arena, f);
+pub(crate) fn collect_module_var_names(statement: &ast::Statement, f: &mut dyn FnMut(Utf16View<'_>)) {
+ match statement.kind() {
+ StatementKind::VariableDeclaration(declaration) if declaration.kind == ast::DeclarationKind::Var => {
+ for declarator in &declaration.declarations {
+ for_each_bound_name(&declarator.target, f);
}
}
- ast::StatementKind::Export(export_data) => {
- if let Some(ref stmt) = export_data.statement {
- collect_module_var_names(&stmt.inner, arena, f);
+ StatementKind::Export(export_data) => {
+ if let Some(statement) = export_data.statement {
+ collect_module_var_names(&statement, f);
}
}
_ => {
- for_each_child_statement(statement, arena, &mut |child| {
- collect_module_var_names(child, arena, f);
+ for_each_child_statement(statement, &mut |child| {
+ collect_module_var_names(child, f);
});
}
}
}
-/// Compile a module body as an async function (for TLA modules).
-///
-/// Emits async-function wrapping (a final Yield, which completes it) around
-/// the module body statements.
-pub(crate) fn new_module_async_generator(
- source_len: usize,
- function_table: ast::FunctionTable,
-) -> bytecode::generator::Generator {
- let mut generator = bytecode::generator::Generator::new();
- generator.strict = true;
- generator.function_table = function_table;
- generator.source_len = source_len;
- generator.enclosing_function_kind = ast::FunctionKind::Async;
- generator
-}
-
-pub(crate) fn compile_module_as_async_to_bytecode(
- program: &ast::Statement,
- scope_id: ast::ScopeId,
- generator: &mut bytecode::generator::Generator,
-) -> bytecode::generator::AssembledBytecode {
- use bytecode::instruction::Instruction;
-
- let arena_clone = generator.arena.clone();
- let scope = &arena_clone.scopes[scope_id];
-
- // Extract local variables from the program scope so the executable has the correct registers_and_locals_count.
- // Without this, locals are not saved across await suspension points, causing them to become undefined.
- generator.local_variables = convert_local_variables(scope);
- generator.enclosing_environment_scope = Some(module_environment_scope(scope, &arena_clone));
-
- let entry_block = generator.make_block();
- generator.switch_to_basic_block(entry_block);
- generator.emit(Instruction::Enter {});
-
- // NB: Like an async function's, the module body runs in the call until it first awaits, without an initial Yield
- // (see AsyncFunctionDriverWrapper::start()).
- generator.capture_saved_lexical_environment_with_coordinates(true);
-
- // Generate module body statements.
- let _result = bytecode::codegen::generate_statement(program, generator, None);
-
- // Async function end: emit final Yield (no continuation = done).
- if !generator.is_current_block_terminated() {
- let undef = generator.add_constant_undefined();
- generator.emit(Instruction::Yield {
- continuation_label: None,
- value: undef.operand(),
- });
- }
-
- // Terminate all unterminated blocks with Yield.
- generator.terminate_unterminated_blocks_with_yield();
-
- generator.assemble()
-}
-
/// Recursively collect var-declared names from a statement and all nested
/// statements, excluding function/class bodies (which create new var scopes).
-pub(crate) fn collect_var_names_recursive(
- statement: &ast::StatementKind,
- arena: &ast::AstArena,
- push_name: &mut dyn FnMut(&[u16]),
-) {
- match statement {
- ast::StatementKind::VariableDeclaration(vd) if vd.kind == ast::DeclarationKind::Var => {
- for declaration in &vd.declarations {
- for_each_bound_name(&declaration.target, arena, push_name);
+pub(crate) fn collect_var_names_recursive(statement: &ast::Statement, push_name: &mut dyn FnMut(Utf16View<'_>)) {
+ match statement.kind() {
+ StatementKind::VariableDeclaration(declaration) if declaration.kind == ast::DeclarationKind::Var => {
+ for declarator in &declaration.declarations {
+ for_each_bound_name(&declarator.target, push_name);
}
}
_ => {
- for_each_child_statement(statement, arena, &mut |child| {
- collect_var_names_recursive(child, arena, push_name);
+ for_each_child_statement(statement, &mut |child| {
+ collect_var_names_recursive(child, push_name);
});
}
}
@@ -828,94 +484,84 @@ pub(crate) fn collect_var_names_recursive(
/// Visit each child statement of a statement, excluding function/class bodies
/// (which create new var scopes). This enables recursive var-declaration walking.
-fn for_each_child_statement(
- statement: &ast::StatementKind,
- arena: &ast::AstArena,
- f: &mut dyn FnMut(&ast::StatementKind),
-) {
- use ast::StatementKind;
-
- match statement {
+fn for_each_child_statement(statement: &ast::Statement, f: &mut dyn FnMut(&ast::Statement)) {
+ match statement.kind() {
StatementKind::Block(scope) => {
- for child in &arena.scopes[*scope].children {
- f(&child.inner);
+ for child in &scope.children {
+ f(&child);
}
}
StatementKind::If(data) => {
- f(&data.consequent.inner);
- if let Some(alt) = &data.alternate {
- f(&alt.inner);
+ f(&data.consequent);
+ if let Some(alternate) = &data.alternate {
+ f(alternate);
}
}
StatementKind::While(data) => {
- f(&data.body.inner);
+ f(&data.body);
}
StatementKind::DoWhile(data) => {
- f(&data.body.inner);
+ f(&data.body);
}
StatementKind::With(data) => {
- f(&data.body.inner);
+ f(&data.body);
}
StatementKind::For(data) => {
- if let Some(ast::ForInit::Declaration(decl)) = &data.init {
- f(&decl.inner);
+ if let Some(ast::ForInit::Declaration(declaration)) = &data.init {
+ f(declaration);
}
- f(&data.body.inner);
+ f(&data.body);
}
StatementKind::ForInOf(data) => {
if let ast::ForInOfLhs::Declaration(declaration) = &data.lhs {
- f(&declaration.inner);
+ f(declaration);
}
- f(&data.body.inner);
+ f(&data.body);
}
StatementKind::Switch(data) => {
for case in &data.cases {
- for child in &arena.scopes[case.scope].children {
- f(&child.inner);
+ for child in &case.scope.children {
+ f(&child);
}
}
}
StatementKind::Try(data) => {
- f(&data.block.inner);
- if let Some(ref handler) = data.handler {
- f(&handler.body.inner);
+ f(&data.block);
+ if let Some(handler) = &data.handler {
+ f(&handler.body);
}
- if let Some(ref finalizer) = data.finalizer {
- f(&finalizer.inner);
+ if let Some(finalizer) = &data.finalizer {
+ f(finalizer);
}
}
StatementKind::Labelled(data) => {
- f(&data.item.inner);
+ f(&data.item);
}
// Don't recurse into function/class bodies (new var scopes)
_ => {}
}
}
-pub(crate) fn for_each_bound_name(
- target: &ast::VariableDeclaratorTarget,
- arena: &ast::AstArena,
- f: &mut dyn FnMut(&[u16]),
-) {
+pub(crate) fn for_each_bound_name(target: &ast::VariableDeclaratorTarget, f: &mut dyn FnMut(Utf16View<'_>)) {
match target {
- ast::VariableDeclaratorTarget::Identifier(id) => f(arena.name_slice(*id)),
+ ast::VariableDeclaratorTarget::Identifier(identifier) => f(identifier.text()),
ast::VariableDeclaratorTarget::BindingPattern(pattern) => {
- for_each_bound_name_in_pattern(pattern, arena, f);
+ for_each_bound_name_in_pattern(pattern, f);
}
}
}
-fn for_each_bound_name_in_pattern(pattern: &ast::BindingPattern, arena: &ast::AstArena, f: &mut dyn FnMut(&[u16])) {
+fn for_each_bound_name_in_pattern(pattern: &ast::BindingPattern, f: &mut dyn FnMut(Utf16View<'_>)) {
for entry in &pattern.entries {
match &entry.alias {
None => {
- if let Some(ast::BindingEntryName::Identifier(id)) = &entry.name {
- f(arena.name_slice(*id));
+ if let Some(ast::BindingEntryName::Identifier(identifier)) = &entry.name {
+ f(identifier.text());
}
}
- Some(ast::BindingEntryAlias::Identifier(id)) => f(arena.name_slice(*id)),
+ Some(ast::BindingEntryAlias::Identifier(identifier)) => f(identifier.text()),
Some(ast::BindingEntryAlias::BindingPattern(inner)) => {
- for_each_bound_name_in_pattern(inner, arena, f);
+ for_each_bound_name_in_pattern(inner, f);
}
Some(ast::BindingEntryAlias::MemberExpression(_)) => {}
}
@@ -938,77 +584,41 @@ pub struct EvalContext {
/// The code of an eval, parsed and analyzed without errors.
pub struct ParsedEval {
- pub(crate) program: ast::Statement,
- pub(crate) function_table: ast::FunctionTable,
- pub(crate) arena: std::sync::Arc<ast::AstArena>,
- pub(crate) scope_id: ast::ScopeId,
- pub(crate) is_strict: bool,
- pub(crate) eval_referenced_private_names: Vec<ast::Utf16String>,
+ pub(crate) tree: Arc<SyntaxTree>,
}
/// Parses the code of an eval, or returns its syntax errors and then its early errors.
-pub fn parse_eval(source: &[u16], context: EvalContext) -> Result<ParsedEval, Vec<ParseError>> {
- let mut parser = Parser::new(source, ProgramType::Script);
- parser.initiated_by_eval = true;
- parser.in_eval_function_context = context.in_eval_function_context;
- parser.flags.allow_super_property_lookup = context.allow_super_property_lookup;
- parser.flags.allow_super_constructor_call = context.allow_super_constructor_call;
- parser.flags.in_class_field_initializer = context.in_class_field_initializer;
-
- let program = parser.parse_program(context.starts_in_strict_mode);
-
- if parser.has_errors() {
- return Err(parser.take_errors());
- }
- if parser.scope_collector.has_errors() {
- return Err(parser.scope_collector.drain_errors());
- }
-
- let eval_referenced_private_names = parser.eval_referenced_private_names().to_vec();
-
- parser.scope_collector.analyze(
- true,
- &mut parser.arena.identifiers,
- &parser.arena.strings,
- &mut parser.arena.scopes,
- );
-
- let StatementKind::Program(ref data) = program.inner else {
- unreachable!("the parser produces a program");
- };
- let (scope_id, is_strict) = (data.scope, data.is_strict_mode);
-
+pub fn parse_eval(source: &ak::Utf16String, context: EvalContext) -> Result<ParsedEval, Vec<ParseError>> {
+ let mut options = ParseOptions::new(ProgramType::Script);
+ options.starts_in_strict_mode = context.starts_in_strict_mode;
+ options.initiated_by_eval = true;
+ options.in_eval_function_context = context.in_eval_function_context;
+ options.allow_super_property_lookup = context.allow_super_property_lookup;
+ options.allow_super_constructor_call = context.allow_super_constructor_call;
+ options.in_class_field_initializer = context.in_class_field_initializer;
Ok(ParsedEval {
- program,
- function_table: std::mem::take(&mut parser.function_table),
- arena: std::sync::Arc::new(std::mem::take(&mut parser.arena)),
- scope_id,
- is_strict,
- eval_referenced_private_names,
+ tree: Arc::new(parse_to_tree(source, &options)?),
})
}
/// An eval compiled to bytecode, with what EvalDeclarationInstantiation needs from it.
pub struct CompiledEval {
- pub executable: ExecutableData,
+ pub executable: Arc<ExecutableData>,
pub declarations: EvalDeclarations,
}
-/// Compiles the code of an eval parsed from `source_len` code units.
-pub fn compile_eval(mut parsed: ParsedEval, source_len: usize) -> CompiledEval {
- let mut generator = new_program_generator(parsed.is_strict, source_len);
- generator.function_table = std::mem::take(&mut parsed.function_table);
- generator.arena = parsed.arena.clone();
- let assembled = compile_program_body_to_bytecode(&mut generator, &parsed.program, parsed.scope_id);
- let mut function_table = std::mem::take(&mut generator.function_table);
- let executable = ExecutableData::new(generator, assembled);
- let declarations = collect_eval_declarations(
- &parsed.arena.scopes[parsed.scope_id],
- parsed.is_strict,
- &mut function_table,
- &parsed.arena,
- parsed.eval_referenced_private_names,
- );
+/// Compiles the code of an eval.
+pub fn compile_eval(parsed: ParsedEval) -> CompiledEval {
+ let tree = parsed.tree;
+ let executable = Arc::new(compile_program(
+ &tree,
+ ProgramOptions {
+ strict: tree.is_strict_mode(),
+ is_async_module: false,
+ eager_compile_direct_iifes: false,
+ },
+ ));
+ let declarations = collect_eval_declarations(&tree);
CompiledEval {
executable,
declarations,
@@ -1021,16 +631,16 @@ pub fn compile_eval(mut parsed: ParsedEval, source_len: usize) -> CompiledEval {
/// An ImportEntry Record of a module: `import_name` is None for a namespace import.
pub struct ModuleImportEntry {
- pub import_name: Option<ast::Utf16String>,
- pub local_name: ast::Utf16String,
+ pub import_name: Option<Utf16String>,
+ pub local_name: Utf16String,
pub module_request: ast::ModuleRequest,
}
/// An ExportEntry Record of a module.
pub struct ModuleExportEntry {
pub kind: ast::ExportEntryKind,
- pub export_name: Option<ast::Utf16String>,
- pub local_or_import_name: Option<ast::Utf16String>,
+ pub export_name: Option<Utf16String>,
+ pub local_or_import_name: Option<Utf16String>,
pub module_request: Option<ast::ModuleRequest>,
}
@@ -1038,14 +648,12 @@ pub struct ModuleExportEntry {
pub struct ModuleFunctionToInitialize {
pub description: SharedFunctionDescription,
/// The name the module binds the function under.
- pub name: ast::Utf16String,
- /// Whether this is an anonymous default export, whose function is named "default".
- pub is_anonymous_default_export: bool,
+ pub name: Utf16String,
}
/// A lexical declaration of a module; `function_index` refers to the function it is initialized with.
pub struct ModuleLexicalBinding {
- pub name: ast::Utf16String,
+ pub name: Utf16String,
pub is_constant: bool,
pub function_index: Option<usize>,
}
@@ -1055,31 +663,26 @@ pub struct ModuleLexicalBinding {
pub struct ModuleDeclarations {
pub has_top_level_await: bool,
pub import_entries: Vec<ModuleImportEntry>,
- pub default_export_binding_name: Option<ast::Utf16String>,
+ pub default_export_binding_name: Option<Utf16String>,
pub local_export_entries: Vec<ModuleExportEntry>,
pub indirect_export_entries: Vec<ModuleExportEntry>,
pub star_export_entries: Vec<ModuleExportEntry>,
- pub var_names: Vec<ast::Utf16String>,
+ pub var_names: Vec<Utf16String>,
pub functions_to_initialize: Vec<ModuleFunctionToInitialize>,
pub lexical_bindings: Vec<ModuleLexicalBinding>,
/// In source order.
pub requested_modules: Vec<ast::ModuleRequest>,
}
-/// Collects what ParseModule records from a module's top-level scope, taking the functions to initialize out of
-/// `function_table`.
-pub fn collect_module_declarations(
- scope: &ast::ScopeData,
- has_top_level_await: bool,
- function_table: &mut ast::FunctionTable,
- arena: &std::sync::Arc<ast::AstArena>,
-) -> ModuleDeclarations {
+/// Collects what ParseModule records from a module's top-level scope.
+pub fn collect_module_declarations(tree: &Arc<SyntaxTree>) -> ModuleDeclarations {
use ast::ExportEntryKind;
+ let scope = &program_scope(tree);
let mut declarations = ModuleDeclarations {
- has_top_level_await,
+ has_top_level_await: tree.has_top_level_await(),
import_entries: Vec::new(),
- default_export_binding_name: module_default_export_binding_name(scope).cloned(),
+ default_export_binding_name: module_default_export_binding_name(scope),
local_export_entries: Vec::new(),
indirect_export_entries: Vec::new(),
star_export_entries: Vec::new(),
@@ -1090,12 +693,13 @@ pub fn collect_module_declarations(
};
for child in &scope.children {
- if let StatementKind::Import(ref import_data) = child.inner {
- for entry in &import_data.entries {
+ if let StatementKind::Import(import_data) = child.kind() {
+ let module_request = import_data.module_request();
+ for entry in import_data.entries() {
declarations.import_entries.push(ModuleImportEntry {
- import_name: entry.import_name.clone(),
- local_name: entry.local_name.clone(),
- module_request: import_data.module_request.clone(),
+ import_name: entry.import_name,
+ local_name: entry.local_name,
+ module_request: module_request.clone(),
});
}
}
@@ -1103,14 +707,15 @@ pub fn collect_module_declarations(
// ParseModule steps 9-10.
for child in &scope.children {
- let StatementKind::Export(ref export_data) = child.inner else {
+ let StatementKind::Export(export_data) = child.kind() else {
continue;
};
- for entry in &export_data.entries {
+ let export_module_request = export_data.module_request();
+ for entry in &export_data.entries() {
if entry.kind == ExportEntryKind::EmptyNamedExport {
break;
}
- let Some(ref module_request) = export_data.module_request else {
+ let Some(ref module_request) = export_module_request else {
let matching_import = declarations
.import_entries
.iter()
@@ -1158,61 +763,60 @@ pub fn collect_module_declarations(
}
for child in &scope.children {
- collect_module_var_names(&child.inner, arena, &mut |name| {
- declarations.var_names.push(name.to_vec().into());
+ collect_module_var_names(&child, &mut |name| {
+ declarations.var_names.push(name.into());
});
}
- let default_name: ast::Utf16String = utf16!("*default*").into();
- let module_environment_scope = module_environment_scope(scope, arena);
+ let module_environment_scope = module_environment_scope(scope);
+ let enclosing_code = EnclosingCode::of_program(tree);
for child in &scope.children {
- let (declaration, is_exported) = match &child.inner {
+ let (declaration, is_exported) = match child.kind() {
StatementKind::Export(export_data) => match export_data.statement {
- Some(ref statement) => (&statement.inner, true),
+ Some(statement) => (statement.kind(), true),
None => continue,
},
other => (other, false),
};
match declaration {
StatementKind::FunctionDeclaration(function_declaration) => {
- let is_anonymous_default_export = is_exported
- && function_declaration
- .name
- .is_some_and(|name| arena.name_of(name).as_slice() == default_name.as_slice());
- let function_data = function_table.take(function_declaration.function_id);
- let subtable = function_table.extract_reachable(&function_data, &arena.scopes);
- let description = describe_shared_function(
- function_data,
- subtable,
+ let is_anonymous_default_export =
+ is_exported && function_declaration.name.is_some_and(|name| name.text() == "*default*");
+ let mut description = describe_shared_function(
+ tree,
+ function_declaration.function_id,
true,
None,
- arena.clone(),
Some(module_environment_scope.clone()),
+ &enclosing_code,
);
// The binding name from the AST, e.g. "*default*" for an anonymous default export.
- let Some(binding_name) = function_declaration.name.map(|name| arena.name_of(name).clone()) else {
+ let Some(binding_name) = function_declaration.name.map(|name| Utf16String::from(name.text())) else {
continue;
};
let name = if is_anonymous_default_export {
- utf16!("default").into()
+ Utf16String::from_utf16(utf16!("default"))
} else {
binding_name.clone()
};
+ // NB: The shared data of an anonymous default export takes the name the module binds it under, from
+ // which the function's name is all that follows.
+ if is_anonymous_default_export {
+ description.name = Utf16View::of_string(&name).to_utf16_fly_string();
+ }
declarations.lexical_bindings.push(ModuleLexicalBinding {
name: binding_name,
is_constant: false,
function_index: Some(declarations.functions_to_initialize.len()),
});
- declarations.functions_to_initialize.push(ModuleFunctionToInitialize {
- description,
- name,
- is_anonymous_default_export,
- });
+ declarations
+ .functions_to_initialize
+ .push(ModuleFunctionToInitialize { description, name });
}
StatementKind::ClassDeclaration(class_data) => {
if let Some(name) = class_data.name {
declarations.lexical_bindings.push(ModuleLexicalBinding {
- name: arena.name_of(name).clone(),
+ name: name.text().into(),
is_constant: false,
function_index: None,
});
@@ -1223,9 +827,9 @@ pub fn collect_module_declarations(
{
let is_constant = variable_declaration.kind == ast::DeclarationKind::Const;
for declarator in &variable_declaration.declarations {
- for_each_bound_name(&declarator.target, arena, &mut |name| {
+ for_each_bound_name(&declarator.target, &mut |name| {
declarations.lexical_bindings.push(ModuleLexicalBinding {
- name: name.to_vec().into(),
+ name: name.into(),
is_constant,
function_index: None,
});
@@ -1234,9 +838,9 @@ pub fn collect_module_declarations(
}
StatementKind::UsingDeclaration(using_declarations) => {
for declarator in &using_declarations.declarations {
- for_each_bound_name(&declarator.target, arena, &mut |name| {
+ for_each_bound_name(&declarator.target, &mut |name| {
declarations.lexical_bindings.push(ModuleLexicalBinding {
- name: name.to_vec().into(),
+ name: name.into(),
is_constant: true,
function_index: None,
});
@@ -1247,15 +851,15 @@ pub fn collect_module_declarations(
}
}
- let mut requested_modules: Vec<(u32, &ast::ModuleRequest)> = Vec::new();
+ let mut requested_modules: Vec<(u32, ast::ModuleRequest)> = Vec::new();
for child in &scope.children {
- match &child.inner {
+ match child.kind() {
StatementKind::Import(import_data) => {
- requested_modules.push((child.range.start.offset, &import_data.module_request));
+ requested_modules.push((child.range().start.offset, import_data.module_request()));
}
StatementKind::Export(export_data) => {
- if let Some(ref module_request) = export_data.module_request {
- requested_modules.push((child.range.start.offset, module_request));
+ if let Some(module_request) = export_data.module_request() {
+ requested_modules.push((child.range().start.offset, module_request));
}
}
_ => {}
@@ -1264,7 +868,7 @@ pub fn collect_module_declarations(
requested_modules.sort_by_key(|(source_offset, _)| *source_offset);
declarations.requested_modules = requested_modules
.into_iter()
- .map(|(_, module_request)| module_request.clone())
+ .map(|(_, module_request)| module_request)
.collect();
declarations
@@ -1273,35 +877,26 @@ pub fn collect_module_declarations(
/// A module compiled to bytecode, with what its Source Text Module Record needs.
pub struct CompiledModule {
/// The module body; for a module with top-level await, the body of an async function.
- pub executable: ExecutableData,
- pub declarations: ModuleDeclarations,
+ pub executable: Arc<ExecutableData>,
+ pub declarations: Arc<ModuleDeclarations>,
}
-/// Compiles a module the caller parsed without errors from `source_len` code units.
-pub fn compile_module(mut parsed: ParsedProgram, source_len: usize) -> CompiledModule {
+/// Compiles a module the caller parsed without errors.
+pub fn compile_module(parsed: ParsedProgram) -> CompiledModule {
assert!(
parsed.program_type == ProgramType::Module && !parsed.has_errors(),
"compile_module() needs a module without parse errors"
);
- let declarations = collect_module_declarations(
- &parsed.arena.scopes[parsed.scope_ref],
- parsed.has_top_level_await,
- &mut parsed.function_table,
- &parsed.arena,
- );
- let function_table = std::mem::take(&mut parsed.function_table);
- let executable = if parsed.has_top_level_await {
- let mut generator = new_module_async_generator(source_len, function_table);
- generator.arena = parsed.arena.clone();
- let assembled = compile_module_as_async_to_bytecode(&parsed.program, parsed.scope_ref, &mut generator);
- ExecutableData::new(generator, assembled)
- } else {
- let mut generator = new_program_generator(true, source_len);
- generator.function_table = function_table;
- generator.arena = parsed.arena.clone();
- let assembled = compile_program_body_to_bytecode(&mut generator, &parsed.program, parsed.scope_ref);
- ExecutableData::new(generator, assembled)
- };
+ let tree = parsed.tree().clone();
+ let declarations = Arc::new(collect_module_declarations(&tree));
+ let executable = Arc::new(compile_program(
+ &tree,
+ ProgramOptions {
+ strict: true,
+ is_async_module: parsed.has_top_level_await,
+ eager_compile_direct_iifes: false,
+ },
+ ));
CompiledModule {
executable,
declarations,
@@ -1315,9 +910,7 @@ pub fn compile_module(mut parsed: ParsedProgram, source_len: usize) -> CompiledM
/// The source of a function that CreateDynamicFunction (new Function() and its relatives) builds, parsed and analyzed
/// without errors.
pub struct ParsedDynamicFunction {
- pub(crate) program: ast::Statement,
- pub(crate) function_table: ast::FunctionTable,
- pub(crate) arena: ast::AstArena,
+ pub(crate) tree: Arc<SyntaxTree>,
}
// 20.2.1.1.1 CreateDynamicFunction ( constructor, newTarget, kind, parameterArgs, bodyArg ), https://tc39.es/ecma262/#sec-createdynamicfunction
@@ -1325,14 +918,14 @@ pub struct ParsedDynamicFunction {
/// expression made of them, or returns the first errors one of these steps reports. `body_source` is the body as the
/// caller wraps it in newlines.
pub fn parse_dynamic_function(
- full_source: &[u16],
+ full_source: &ak::Utf16String,
parameters_source: &[u16],
body_source: &[u16],
kind: ast::FunctionKind,
) -> Result<ParsedDynamicFunction, Vec<ParseError>> {
// Lex the parameters on their own first, so that lexer errors such as an unterminated comment have positions in
// the parameter string.
- let mut lexer = crate::lexer::Lexer::new(parameters_source, 1, 0);
+ let mut lexer = crate::lexer::Lexer::new(Utf16View::Utf16(parameters_source), 1, 0);
loop {
let token = lexer.next();
if token.token_type == crate::token::TokenType::Eof {
@@ -1360,75 +953,40 @@ pub fn parse_dynamic_function(
});
parameters_check.extend_from_slice(parameters_source);
parameters_check.extend_from_slice(utf16!("\n) {}"));
- let mut parser = Parser::new(&parameters_check, ProgramType::Script);
- parser.parse_program(false);
- take_parser_errors(&mut parser)?;
+ check_syntax(
+ &ak::Utf16String::from_utf16(&parameters_check),
+ &ParseOptions::new(ProgramType::Script),
+ )?;
// Check the body on its own as a script with the flags of a function body of the kind.
- let mut parser = Parser::new(body_source, ProgramType::Script);
- parser.flags.in_function_context = true;
- parser.flags.new_target_is_valid = true;
- if matches!(kind, ast::FunctionKind::Async | ast::FunctionKind::AsyncGenerator) {
- parser.flags.await_expression_is_valid = true;
- }
- if matches!(kind, ast::FunctionKind::Generator | ast::FunctionKind::AsyncGenerator) {
- parser.flags.in_generator_function_context = true;
- }
- parser.parse_program(false);
- take_parser_errors(&mut parser)?;
-
- let mut parser = Parser::new(full_source, ProgramType::Script);
- let program = parser.parse_program(false);
- take_parser_errors(&mut parser)?;
+ let mut options = ParseOptions::new(ProgramType::Script);
+ options.function_body = Some(kind);
+ check_syntax(&ak::Utf16String::from_utf16(body_source), &options)?;
// The function is parsed as a function expression, so it has no Program scope whose globals its identifiers
// could bind to.
- parser.scope_collector.analyze_as_dynamic_function(
- &mut parser.arena.identifiers,
- &parser.arena.strings,
- &mut parser.arena.scopes,
- );
- if parser.scope_collector.has_errors() {
- return Err(parser.scope_collector.drain_errors());
- }
-
+ let mut options = ParseOptions::new(ProgramType::Script);
+ options.suppress_globals = true;
Ok(ParsedDynamicFunction {
- program,
- function_table: std::mem::take(&mut parser.function_table),
- arena: std::mem::take(&mut parser.arena),
+ tree: Arc::new(parse_to_tree(full_source, &options)?),
})
}
-/// The parser's syntax errors, or else the early errors its scope collector found while parsing.
-fn take_parser_errors(parser: &mut Parser) -> Result<(), Vec<ParseError>> {
- if parser.has_errors() {
- return Err(parser.take_errors());
- }
- if parser.scope_collector.has_errors() {
- return Err(parser.scope_collector.drain_errors());
- }
- Ok(())
-}
-
impl ParsedDynamicFunction {
/// Describes the function the source defines.
- pub fn into_description(mut self) -> Result<SharedFunctionDescription, Vec<ParseError>> {
+ pub fn into_description(self) -> Result<SharedFunctionDescription, Vec<ParseError>> {
// The program is a single ExpressionStatement wrapping a FunctionExpression.
- let function_id = if let StatementKind::Program(ref data) = self.program.inner {
- self.arena.scopes[data.scope]
- .children
- .iter()
- .find_map(|child| match &child.inner {
- StatementKind::FunctionDeclaration(function_declaration) => Some(function_declaration.function_id),
- StatementKind::Expression(expression) => match &expression.inner {
- ast::ExpressionKind::Function(function_id) => Some(*function_id),
- _ => None,
- },
+ let function_id = program_scope(&self.tree)
+ .children
+ .iter()
+ .find_map(|child| match child.kind() {
+ StatementKind::FunctionDeclaration(function_declaration) => Some(function_declaration.function_id),
+ StatementKind::Expression(expression) => match expression.kind() {
+ ast::ExpressionKind::Function(function_id) => Some(function_id),
_ => None,
- })
- } else {
- None
- };
+ },
+ _ => None,
+ });
let Some(function_id) = function_id else {
return Err(vec![ParseError {
message: "Failed to parse dynamic function".to_string(),
@@ -1437,20 +995,14 @@ impl ParsedDynamicFunction {
}]);
};
- let function_data = self.function_table.take(function_id);
-
- let is_strict = function_data.is_strict_mode;
- let subtable = self
- .function_table
- .extract_reachable(&function_data, &self.arena.scopes);
- let arena = std::sync::Arc::new(self.arena);
+ let is_strict = self.tree.function(function_id).is_strict_mode;
Ok(describe_shared_function(
- function_data,
- subtable,
+ &self.tree,
+ function_id,
is_strict,
None,
- arena,
None,
+ &EnclosingCode::of_program(&self.tree),
))
}
}
@@ -1461,65 +1013,37 @@ impl ParsedDynamicFunction {
/// Parses a file of builtin functions written in JavaScript, which is strict code, and runs scope analysis on it.
/// Builtin files ship with the engine, so a syntax error in one stops the process.
-pub fn parse_builtin_file(source: &[u16]) -> ParsedProgram {
- let mut parser = Parser::new(source, ProgramType::Script);
- let program = parser.parse_program(true);
-
- if parser.has_errors() {
- let errors: Vec<String> = parser
- .errors()
- .iter()
- .map(|e| format!("{}:{}: {}", e.line, e.column, e.message))
- .collect();
- panic!("Parse errors in builtin file: {}", errors.join("; "));
- }
-
- parser.scope_collector.analyze(
- false,
- &mut parser.arena.identifiers,
- &parser.arena.strings,
- &mut parser.arena.scopes,
- );
-
- let StatementKind::Program(ref data) = program.inner else {
- unreachable!("parse_program() returns a Program");
- };
- let scope_ref = data.scope;
-
- ParsedProgram {
- program,
- function_table: std::mem::take(&mut parser.function_table),
- arena: std::sync::Arc::new(std::mem::take(&mut parser.arena)),
- scope_ref,
- program_type: ProgramType::Script,
- is_strict_mode: true,
- has_top_level_await: false,
- errors: Vec::new(),
- ast_dump: None,
+pub fn parse_builtin_file(source: &ak::Utf16String) -> ParsedProgram {
+ let mut options = ParseOptions::new(ProgramType::Script);
+ options.starts_in_strict_mode = true;
+ match parse_to_tree(source, &options) {
+ Ok(tree) => ParsedProgram::from_tree(tree, options),
+ Err(errors) => {
+ let errors: Vec<String> = errors
+ .iter()
+ .map(|error| format!("{}:{}: {}", error.line, error.column, error.message))
+ .collect();
+ panic!("Parse errors in builtin file: {}", errors.join("; "));
+ }
}
}
-/// Describes the named functions that a parsed builtin file declares at its top level, in source order, taking their
-/// ASTs out of the program.
+/// Describes the named functions that a parsed builtin file declares at its top level, in source order.
pub fn describe_builtin_file_functions(parsed: &ParsedProgram) -> Vec<SharedFunctionDescription> {
- let arena = parsed.arena.clone();
- let scope = &arena.scopes[parsed.scope_ref];
- // Every caller creates functions of its own from the same parse, so take them from a copy of its function table.
- let mut function_table = parsed.function_table.clone();
+ let tree = parsed.tree();
+ let enclosing_code = EnclosingCode::of_program(tree);
let mut descriptions = Vec::new();
- for child in &scope.children {
- if let StatementKind::FunctionDeclaration(ref function_declaration) = child.inner
+ for child in &program_scope(tree).children {
+ if let StatementKind::FunctionDeclaration(function_declaration) = child.kind()
&& function_declaration.name.is_some()
{
- let function_data = function_table.take(function_declaration.function_id);
- let subtable = function_table.extract_reachable(&function_data, &arena.scopes);
descriptions.push(describe_shared_function(
- function_data,
- subtable,
+ tree,
+ function_declaration.function_id,
true,
None,
- arena.clone(),
None,
+ &enclosing_code,
));
}
}
@@ -1530,131 +1054,176 @@ pub fn describe_builtin_file_functions(parsed: &ParsedProgram) -> Vec<SharedFunc
// Shared function data
// =============================================================================
-/// What a runtime needs to create a SharedFunctionInstanceData for one function, taken from the frontend's AST of it.
-/// The AST travels along in `payload`, which compile_function() turns into bytecode when the function is first called.
+/// What a function that has not run yet compiles from: the data of its source, its row there, and what it can not find
+/// out on its own, which is what the code around it made of the environment and of the names it closes over.
+pub struct FunctionPayload {
+ pub script: Arc<ScriptData>,
+ pub row: FunctionRow,
+ /// The environment the function closes over, as laid out by the generators of its enclosing functions.
+ pub enclosing_environment_scope: Option<Arc<bytecode::codegen::EnclosingEnvironmentScope>>,
+ pub enclosing_code: Arc<EnclosingCode>,
+}
+
+/// What a runtime needs to create a SharedFunctionInstanceData for one function, none of which takes the function's own
+/// tree to know. `payload` is what compile_function() turns into bytecode when the function is first called.
pub struct SharedFunctionDescription {
/// Empty for an anonymous function.
- pub name: Vec<u16>,
+ pub name: ak::Utf16FlyString,
pub function_kind: ast::FunctionKind,
pub function_length: i32,
pub formal_parameter_count: u32,
pub strict: bool,
pub is_arrow: bool,
pub has_simple_parameter_list: bool,
- /// The parameter names if the parameter list is simple, and empty otherwise.
- pub parameter_names: Vec<ak::Utf16FlyString>,
pub source_text_offset: usize,
pub source_text_length: usize,
pub uses_this: bool,
pub uses_this_from_environment: bool,
- pub payload: Box<ast::FunctionPayload>,
+ pub payload: Arc<FunctionPayload>,
}
-/// Describes a function whose AST the caller took out of a function table, together with the functions nested in it.
-#[allow(clippy::boxed_local)] // Callers produce Box<FunctionData>; unboxing would copy a large struct.
+/// Describes a function of `tree`, whose code does not have to be in the tree.
pub fn describe_shared_function(
- function_data: Box<ast::FunctionData>,
- subtable: ast::FunctionTable,
+ tree: &SyntaxTree,
+ function: FunctionId,
is_strict: bool,
- name_override: Option<&[u16]>,
- arena: std::sync::Arc<ast::AstArena>,
- enclosing_environment_scope: Option<std::sync::Arc<bytecode::generator::EnclosingEnvironmentScope>>,
+ name_override: Option<ak::Utf16FlyString>,
+ enclosing_environment_scope: Option<Arc<bytecode::codegen::EnclosingEnvironmentScope>>,
+ enclosing_code: &Arc<EnclosingCode>,
) -> SharedFunctionDescription {
- use ast::FunctionParameterBinding;
-
+ let function_data = tree.function(function);
let source_start = function_data.source_text_start as usize;
let source_end = function_data.source_text_end as usize;
let name = if let Some(name) = name_override {
- name.to_vec()
- } else if let Some(name_ident) = function_data.name {
- arena.name_slice(name_ident).to_vec()
- } else {
- Vec::new()
- };
-
- let has_simple_parameter_list = function_data.parameters.iter().all(|p| {
- !p.is_rest && p.default_value.is_none() && matches!(p.binding, FunctionParameterBinding::Identifier(_))
- });
-
- let parameter_names: Vec<ak::Utf16FlyString> = if has_simple_parameter_list {
- function_data
- .parameters
- .iter()
- .map(|p| {
- if let FunctionParameterBinding::Identifier(id) = p.binding {
- ak::Utf16FlyString::from_utf16(arena.name_slice(id))
- } else {
- unreachable!("has_simple_parameter_list guarantees all bindings are identifiers")
- }
- })
- .collect()
+ name
+ } else if let Some(name) = function_data.name {
+ name.text().to_utf16_fly_string()
} else {
- Vec::new()
+ ak::Utf16FlyString::default()
};
SharedFunctionDescription {
name,
function_kind: function_data.kind,
function_length: function_data.function_length,
- formal_parameter_count: u32_from_usize(function_data.parameters.len()),
+ formal_parameter_count: function_data.parameter_count,
strict: function_data.is_strict_mode || is_strict,
is_arrow: function_data.is_arrow_function,
- has_simple_parameter_list,
- parameter_names,
+ has_simple_parameter_list: function_data.has_simple_parameter_list,
source_text_offset: source_start,
source_text_length: source_end - source_start,
uses_this: function_data.parsing_insights.uses_this,
uses_this_from_environment: function_data.parsing_insights.uses_this_from_environment,
- payload: Box::new(ast::FunctionPayload {
- data: *function_data,
- function_table: subtable,
- arena,
+ payload: Arc::new(FunctionPayload {
+ script: tree.script.clone(),
+ row: tree.function_row(function),
enclosing_environment_scope,
+ enclosing_code: enclosing_code.clone(),
}),
}
}
+/// Describes the function at `row`, whose name the caller knows, from what the first parse left.
+pub(crate) fn pending_function_of_row(
+ script: &Arc<crate::parser::ScriptData>,
+ row: u32,
+ name: Option<ak::Utf16FlyString>,
+ enclosing_environment_scope: Option<Arc<bytecode::codegen::EnclosingEnvironmentScope>>,
+ enclosing_code: &Arc<EnclosingCode>,
+) -> PendingSharedFunctionData {
+ use crate::parser::columns::function_flag;
+ let index = &script.index;
+ let at = row as usize;
+ let flags = index.flags[at];
+ let (start, end) = (index.start[at] as usize, index.end[at] as usize);
+ PendingSharedFunctionData {
+ function: FunctionId::function(0),
+ description: SharedFunctionDescription {
+ name: name.unwrap_or_default(),
+ function_kind: ast::FunctionKind::from_async_generator(
+ flags & function_flag::ASYNC != 0,
+ flags & function_flag::GENERATOR != 0,
+ ),
+ function_length: i32::try_from(index.length[at]).expect("a function has a sane number of parameters"),
+ formal_parameter_count: index.parameter_count[at],
+ strict: flags & function_flag::STRICT != 0,
+ is_arrow: flags & function_flag::ARROW != 0,
+ has_simple_parameter_list: flags & function_flag::SIMPLE_PARAMETERS != 0,
+ source_text_offset: start,
+ source_text_length: end - start,
+ uses_this: flags & function_flag::INSIGHT_USES_THIS != 0,
+ uses_this_from_environment: flags & function_flag::INSIGHT_THIS_FROM_ENVIRONMENT != 0,
+ payload: Arc::new(FunctionPayload {
+ script: script.clone(),
+ row: crate::parser::FunctionRow(row),
+ enclosing_environment_scope,
+ enclosing_code: enclosing_code.clone(),
+ }),
+ },
+ class_field_initializer_name: None,
+ should_eager_compile: false,
+ precompiled_function: None,
+ }
+}
+
impl PendingSharedFunctionData {
- /// Describes this function of an executable whose code is strict if `is_strict`, taking its AST. The precompiled
- /// body and the class field initializer name stay here for the caller to take as well.
- pub fn take_description(&mut self, is_strict: bool) -> SharedFunctionDescription {
- let function_data = self
- .function_data
- .take()
- .expect("pending shared function data was already materialized");
- let subtable = self
- .subtable
- .take()
- .expect("pending shared function data subtable was already materialized");
- let arena = self
- .arena
- .clone()
- .expect("executable data records the AST arena of every pending function");
- describe_shared_function(
- function_data,
- subtable,
- is_strict,
- self.name_override.as_ref().map(|name| name.as_slice()),
- arena,
- self.enclosing_environment_scope.clone(),
- )
+ /// Describes a function of `tree` that an executable creates.
+ pub fn new(
+ tree: &SyntaxTree,
+ function: FunctionId,
+ name_override: Option<ak::Utf16FlyString>,
+ enclosing_environment_scope: Option<Arc<bytecode::codegen::EnclosingEnvironmentScope>>,
+ enclosing_code: &Arc<EnclosingCode>,
+ ) -> Self {
+ let description = describe_shared_function(
+ tree,
+ function,
+ false,
+ name_override,
+ enclosing_environment_scope,
+ enclosing_code,
+ );
+ Self {
+ function,
+ description,
+ class_field_initializer_name: None,
+ should_eager_compile: false,
+ precompiled_function: None,
+ }
+ }
+
+ /// The environment that the function closes over.
+ pub fn enclosing_environment_scope(&self) -> Option<Arc<bytecode::codegen::EnclosingEnvironmentScope>> {
+ self.description.payload.enclosing_environment_scope.clone()
+ }
+
+ /// Whether this function is strict as part of an executable whose code is strict if `is_strict`.
+ pub fn is_strict_in(&self, is_strict: bool) -> bool {
+ self.description.strict || is_strict
}
}
-/// Compiles the body of a described function, along with the functions nested in it that `mode` asks for. Like
-/// [`compile_parsed_program_off_thread()`], it needs no VM and so can run on any thread.
-#[allow(clippy::boxed_local)] // Runtimes keep the payload boxed until the first call; unboxing would copy it.
+/// What parsing, resolving and generating code leave of the stack for what does not watch it: the small helpers that
+/// walk a binding pattern or the like, which nest no deeper than the parser allows.
+const STACK_FOR_SMALL_WALKS: usize = 1 << 20;
+
+/// Parses the function of `payload` on its own and compiles its body. Like [`compile_parsed_program_off_thread()`], it
+/// needs no VM and so can run on any thread. `stack_limit` is the lowest address that the stack may reach on the way.
pub fn compile_function(
- payload: Box<ast::FunctionPayload>,
- source_len: usize,
+ payload: &FunctionPayload,
builtin_abstract_operations_enabled: bool,
- mode: FunctionPrecompileMode,
-) -> Box<bytecode::generator::PrecompiledFunction> {
- let arena = payload.arena.clone();
- let (_function_data, precompiled) =
- compile_function_payload_to_bytecode(*payload, source_len, builtin_abstract_operations_enabled, arena, mode);
- precompiled
+ stack_limit: usize,
+) -> Result<bytecode::executable_data::PrecompiledFunction, OutOfStack> {
+ let stack_limit = stack_limit.saturating_add(STACK_FOR_SMALL_WALKS);
+ bytecode::codegen::compile_function(
+ &payload.script,
+ payload.row,
+ payload.enclosing_environment_scope.clone(),
+ &payload.enclosing_code,
+ builtin_abstract_operations_enabled,
+ stack_limit,
+ )
}
// =============================================================================
@@ -1663,25 +1232,25 @@ pub fn compile_function(
/// A function declaration that declaration instantiation creates a function object for.
pub struct FunctionToInitialize {
- pub name: ast::Utf16String,
+ pub name: Utf16String,
pub shared_function_data: PendingSharedFunctionData,
}
/// A `let`, `const`, `using` or `class` binding that declaration instantiation creates.
pub struct LexicalBinding {
- pub name: ast::Utf16String,
+ pub name: Utf16String,
pub is_constant: bool,
}
/// The names and functions that GlobalDeclarationInstantiation needs from a script.
/// https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
pub struct ScriptDeclarations {
- pub lexical_names: Vec<ast::Utf16String>,
- pub var_names: Vec<ast::Utf16String>,
+ pub lexical_names: Vec<Utf16String>,
+ pub var_names: Vec<Utf16String>,
/// The last declaration of each function name, in source order.
pub functions_to_initialize: Vec<FunctionToInitialize>,
- pub var_scoped_names: Vec<ast::Utf16String>,
- pub annex_b_candidate_names: Vec<ast::Utf16String>,
+ pub var_scoped_names: Vec<Utf16String>,
+ pub annex_b_candidate_names: Vec<Utf16String>,
pub lexical_bindings: Vec<LexicalBinding>,
}
@@ -1689,48 +1258,45 @@ pub struct ScriptDeclarations {
/// https://tc39.es/ecma262/#sec-evaldeclarationinstantiation
pub struct EvalDeclarations {
pub is_strict: bool,
- pub var_names: Vec<ast::Utf16String>,
+ pub var_names: Vec<Utf16String>,
/// The last declaration of each function name, in source order.
pub functions_to_initialize: Vec<FunctionToInitialize>,
- pub var_scoped_names: Vec<ast::Utf16String>,
- pub annex_b_candidate_names: Vec<ast::Utf16String>,
+ pub var_scoped_names: Vec<Utf16String>,
+ pub annex_b_candidate_names: Vec<Utf16String>,
pub lexical_bindings: Vec<LexicalBinding>,
- pub private_names: Vec<ast::Utf16String>,
+ pub private_names: Vec<Utf16String>,
}
-/// Collect what GlobalDeclarationInstantiation needs from a script's top-level scope, taking the functions to
-/// initialize out of `function_table`.
-pub fn collect_script_declarations(
- scope: &ast::ScopeData,
- function_table: &mut ast::FunctionTable,
- arena: &std::sync::Arc<ast::AstArena>,
-) -> ScriptDeclarations {
+/// Collect what GlobalDeclarationInstantiation needs from a script's top-level scope.
+pub fn collect_script_declarations(tree: &Arc<SyntaxTree>) -> ScriptDeclarations {
use ast::DeclarationKind;
+ let scope = program_scope(tree);
+
// Lexical names (let/const/using/class at top level) — script-only step.
let mut lexical_names = Vec::new();
for child in &scope.children {
- match &child.inner {
- StatementKind::VariableDeclaration(vd) if vd.kind != DeclarationKind::Var => {
- for declaration in &vd.declarations {
- for_each_bound_name(&declaration.target, arena, &mut |name| lexical_names.push(name.into()));
+ match child.kind() {
+ StatementKind::VariableDeclaration(declaration) if declaration.kind != DeclarationKind::Var => {
+ for declarator in &declaration.declarations {
+ for_each_bound_name(&declarator.target, &mut |name| lexical_names.push(name.into()));
}
}
- StatementKind::UsingDeclaration(declarations) => {
- for declaration in &declarations.declarations {
- for_each_bound_name(&declaration.target, arena, &mut |name| lexical_names.push(name.into()));
+ StatementKind::UsingDeclaration(declaration) => {
+ for declarator in &declaration.declarations {
+ for_each_bound_name(&declarator.target, &mut |name| lexical_names.push(name.into()));
}
}
StatementKind::ClassDeclaration(class_data) => {
if let Some(name) = class_data.name {
- lexical_names.push(arena.name_of(name).clone());
+ lexical_names.push(name.text().into());
}
}
_ => {}
}
}
- let declarations = collect_var_scoped_declarations(scope, function_table, arena);
+ let declarations = collect_var_scoped_declarations(tree);
ScriptDeclarations {
lexical_names,
var_names: declarations.var_names,
@@ -1741,32 +1307,25 @@ pub fn collect_script_declarations(
}
}
-/// Collect what EvalDeclarationInstantiation needs from an eval script's top-level scope, taking the functions to
-/// initialize out of `function_table`.
-pub fn collect_eval_declarations(
- scope: &ast::ScopeData,
- is_strict: bool,
- function_table: &mut ast::FunctionTable,
- arena: &std::sync::Arc<ast::AstArena>,
- referenced_private_names: Vec<ast::Utf16String>,
-) -> EvalDeclarations {
- let declarations = collect_var_scoped_declarations(scope, function_table, arena);
+/// Collect what EvalDeclarationInstantiation needs from an eval script's top-level scope.
+pub fn collect_eval_declarations(tree: &Arc<SyntaxTree>) -> EvalDeclarations {
+ let declarations = collect_var_scoped_declarations(tree);
EvalDeclarations {
- is_strict,
+ is_strict: tree.is_strict_mode(),
var_names: declarations.var_names,
functions_to_initialize: declarations.functions_to_initialize,
var_scoped_names: declarations.var_scoped_names,
annex_b_candidate_names: declarations.annex_b_candidate_names,
lexical_bindings: declarations.lexical_bindings,
- private_names: referenced_private_names,
+ private_names: tree.eval_referenced_private_names(),
}
}
struct VarScopedDeclarations {
- var_names: Vec<ast::Utf16String>,
+ var_names: Vec<Utf16String>,
functions_to_initialize: Vec<FunctionToInitialize>,
- var_scoped_names: Vec<ast::Utf16String>,
- annex_b_candidate_names: Vec<ast::Utf16String>,
+ var_scoped_names: Vec<Utf16String>,
+ annex_b_candidate_names: Vec<Utf16String>,
lexical_bindings: Vec<LexicalBinding>,
}
@@ -1774,55 +1333,49 @@ struct VarScopedDeclarations {
/// initializations, var-scoped names, annex B names, and lexical bindings.
///
/// Shared by both script and eval declaration instantiation.
-fn collect_var_scoped_declarations(
- scope: &ast::ScopeData,
- function_table: &mut ast::FunctionTable,
- arena: &std::sync::Arc<ast::AstArena>,
-) -> VarScopedDeclarations {
+fn collect_var_scoped_declarations(tree: &Arc<SyntaxTree>) -> VarScopedDeclarations {
use ast::DeclarationKind;
+ let scope = program_scope(tree);
+
// Var names (var declarations at any nesting level + top-level function declarations)
let mut var_names = Vec::new();
for child in &scope.children {
- collect_var_names_recursive(&child.inner, arena, &mut |name| var_names.push(name.into()));
- if let Some(fd) = child.inner.function_declaration_for_labelled_item()
- && let Some(name_ident) = fd.name
+ collect_var_names_recursive(&child, &mut |name| var_names.push(name.into()));
+ if let Some(function) = child.function_declaration_for_labelled_item()
+ && let Some(name) = function.name
{
- var_names.push(arena.name_of(name_ident).clone());
+ var_names.push(name.text().into());
}
}
// Functions to initialize: keep the last declaration with each name
// (ECMAScript hoisting semantics), but emit them in source order. Two
- // forward passes; StringId keys keep the inserts to a u32 compare.
- let mut last_position: std::collections::HashMap<ast::StringId, usize> = std::collections::HashMap::new();
- for (i, child) in scope.children.iter().enumerate() {
- if let Some(fd) = child.inner.function_declaration_for_labelled_item()
- && let Some(name_ident) = fd.name
+ // forward passes; name keys keep the inserts to a u32 compare.
+ let mut last_position: std::collections::HashMap<ast::Name, usize> = std::collections::HashMap::new();
+ for (index, child) in scope.children.iter().enumerate() {
+ if let Some(function) = child.function_declaration_for_labelled_item()
+ && let Some(name) = function.name
{
- last_position.insert(arena.identifiers[name_ident].name, i);
+ last_position.insert(name.name, index);
}
}
+ let enclosing_code = EnclosingCode::of_program(tree);
let mut functions_to_initialize = Vec::new();
- for (i, child) in scope.children.iter().enumerate() {
- if let Some(fd) = child.inner.function_declaration_for_labelled_item()
- && let Some(name_ident) = fd.name
- && last_position.get(&arena.identifiers[name_ident].name).copied() == Some(i)
+ for (index, child) in scope.children.iter().enumerate() {
+ if let Some(function) = child.function_declaration_for_labelled_item()
+ && let Some(name) = function.name
+ && last_position.get(&name.name).copied() == Some(index)
{
- let function_data = function_table.take(fd.function_id);
- let subtable = function_table.extract_reachable(&function_data, &arena.scopes);
functions_to_initialize.push(FunctionToInitialize {
- name: arena.name_of(name_ident).clone(),
- shared_function_data: PendingSharedFunctionData {
- function_data: Some(function_data),
- subtable: Some(subtable),
- arena: Some(arena.clone()),
- name_override: None,
- class_field_initializer_name: None,
- should_eager_compile: false,
- precompiled_function: None,
- enclosing_environment_scope: None,
- },
+ name: name.text().into(),
+ shared_function_data: PendingSharedFunctionData::new(
+ tree,
+ function.function_id,
+ None,
+ None,
+ &enclosing_code,
+ ),
});
}
}
@@ -1830,16 +1383,16 @@ fn collect_var_scoped_declarations(
// Var-scoped names (var VariableDeclaration names, excluding function declarations)
let mut var_scoped_names = Vec::new();
for child in &scope.children {
- collect_var_names_recursive(&child.inner, arena, &mut |name| var_scoped_names.push(name.into()));
+ collect_var_names_recursive(&child, &mut |name| var_scoped_names.push(name.into()));
}
let mut lexical_bindings = Vec::new();
for child in &scope.children {
- match &child.inner {
- StatementKind::VariableDeclaration(vd) if vd.kind != DeclarationKind::Var => {
- let is_constant = vd.kind == DeclarationKind::Const;
- for declaration in &vd.declarations {
- for_each_bound_name(&declaration.target, arena, &mut |name| {
+ match child.kind() {
+ StatementKind::VariableDeclaration(declaration) if declaration.kind != DeclarationKind::Var => {
+ let is_constant = declaration.kind == DeclarationKind::Const;
+ for declarator in &declaration.declarations {
+ for_each_bound_name(&declarator.target, &mut |name| {
lexical_bindings.push(LexicalBinding {
name: name.into(),
is_constant,
@@ -1847,9 +1400,9 @@ fn collect_var_scoped_declarations(
});
}
}
- StatementKind::UsingDeclaration(declarations) => {
- for declaration in &declarations.declarations {
- for_each_bound_name(&declaration.target, arena, &mut |name| {
+ StatementKind::UsingDeclaration(declaration) => {
+ for declarator in &declaration.declarations {
+ for_each_bound_name(&declarator.target, &mut |name| {
lexical_bindings.push(LexicalBinding {
name: name.into(),
is_constant: true,
@@ -1860,7 +1413,7 @@ fn collect_var_scoped_declarations(
StatementKind::ClassDeclaration(class_data) => {
if let Some(name) = class_data.name {
lexical_bindings.push(LexicalBinding {
- name: arena.name_of(name).clone(),
+ name: name.text().into(),
is_constant: false,
});
}
@@ -1873,438 +1426,108 @@ fn collect_var_scoped_declarations(
var_names,
functions_to_initialize,
var_scoped_names,
- annex_b_candidate_names: scope.annexb_function_names.clone(),
+ annex_b_candidate_names: scope
+ .annexb_function_names()
+ .iter()
+ .map(|&name| tree.name_text(name).into())
+ .collect(),
lexical_bindings,
}
}
-pub(crate) fn compile_function_payload_to_bytecode(
- payload: ast::FunctionPayload,
- source_len: usize,
- builtin_abstract_operations_enabled: bool,
- arena: std::sync::Arc<ast::AstArena>,
- precompile_mode: FunctionPrecompileMode,
-) -> (Box<ast::FunctionData>, Box<bytecode::generator::PrecompiledFunction>) {
- let function_data = Box::new(payload.data);
- let enclosing_environment_scope = payload.enclosing_environment_scope;
-
- let body_scope: Option<ast::ScopeId> = match &function_data.body.inner {
- StatementKind::FunctionBody { scope, .. } => Some(*scope),
- StatementKind::Block(scope) => Some(*scope),
- _ => None,
- };
-
- // Compute SFD metadata before codegen so the generator can optimize
- // direct `this` access when it does not need environment resolution.
- let sfd_metadata = compute_sfd_metadata(&function_data, &arena);
-
- let mut generator = bytecode::generator::Generator::new();
- generator.arena = arena;
- generator.strict = function_data.is_strict_mode;
- generator.contains_direct_call_to_eval_in_non_strict_mode =
- function_data.parsing_insights.contains_direct_call_to_eval && !function_data.is_strict_mode;
- generator.enclosing_environment_scope = enclosing_environment_scope;
- generator.this_value_needs_environment_resolution = sfd_metadata.this_value_needs_environment_resolution;
- generator.builtin_abstract_operations_enabled = builtin_abstract_operations_enabled;
- generator.function_table = payload.function_table;
- generator.source_len = source_len;
- generator.enclosing_function_kind = function_data.kind;
- generator.argument_variable_names = function_data
- .parameters
- .iter()
- .map(|parameter| match parameter.binding {
- ast::FunctionParameterBinding::Identifier(identifier)
- if generator.arena.identifiers[identifier].local_type == Some(ast::LocalType::Argument) =>
- {
- ak::Utf16FlyString::from_utf16(generator.arena.name_slice(identifier))
- }
- ast::FunctionParameterBinding::BindingPattern(_) => ak::Utf16FlyString::default(),
- _ => ak::Utf16FlyString::default(),
- })
- .collect();
-
- if let Some(scope_id) = body_scope {
- let arena_clone = generator.arena.clone();
- generator.local_variables = convert_local_variables(&arena_clone.scopes[scope_id]);
- }
-
- let entry_block = generator.make_block();
- generator.switch_to_basic_block(entry_block);
- generator.emit(bytecode::instruction::Instruction::Enter {});
-
- // NB: Async (non-generator) functions run FunctionDeclarationInstantiation and their body in the call until they
- // first await, and have no initial Yield. The call rejects their promise if that throws (see
- // AsyncFunctionDriverWrapper::start()).
-
- generator.capture_saved_lexical_environment_with_coordinates(sfd_metadata.function_environment_needed);
-
- if let Some(scope_id) = body_scope {
- let arena_clone = generator.arena.clone();
- bytecode::codegen::emit_function_declaration_instantiation(
- &mut generator,
- &function_data,
- &arena_clone.scopes[scope_id],
- sfd_metadata.var_environment_bindings_count,
- );
- }
-
- // https://tc39.es/ecma262/#sec-generatorstart
- // For generator functions (including async generators), emit the initial Yield
- // AFTER FDI. Parameter evaluation happens synchronously before the generator starts.
- if generator.is_in_generator_function() {
- let start_block = generator.make_block();
- let undef = generator.add_constant_undefined();
- generator.emit(bytecode::instruction::Instruction::Yield {
- continuation_label: Some(start_block),
- value: undef.operand(),
- });
- generator.switch_to_basic_block(start_block);
- }
-
- let result = bytecode::codegen::generate_statement(&function_data.body, &mut generator, None);
-
- if !generator.is_current_block_terminated() {
- if generator.is_in_generator_or_async_function() {
- // Generator/async functions end with Yield (no continuation = done).
- let undef = generator.add_constant_undefined();
- generator.emit(bytecode::instruction::Instruction::Yield {
- continuation_label: None,
- value: undef.operand(),
- });
- } else if let Some(value) = result {
- generator.emit(bytecode::instruction::Instruction::End { value: value.operand() });
- }
- // If result is None, the assembler will add End(undefined) as a
- // fallthrough for unterminated blocks.
- }
-
- // For generator/async functions, terminate all unterminated blocks with Yield.
- if generator.is_in_generator_or_async_function() {
- generator.terminate_unterminated_blocks_with_yield();
- }
-
- precompile_functions(&mut generator, precompile_mode);
-
- let assembled = generator.assemble();
-
- (
- function_data,
- Box::new(bytecode::generator::PrecompiledFunction {
- executable: ExecutableData::new(generator, assembled),
- metadata: sfd_metadata,
- }),
- )
-}
-
// =============================================================================
// SFD metadata computation (ECMA-262 section 10.2.11)
// =============================================================================
-/// Intermediate scope analysis data extracted from the function body scope.
-struct BodyScopeInfo {
- uses_this: bool,
- contains_eval: bool,
- uses_this_from_env: bool,
- might_need_arguments: bool,
- has_function_named_arguments: bool,
- has_lexically_declared_arguments: bool,
- non_local_var_count: usize,
- non_local_var_count_for_parameter_expressions: usize,
- var_names: Vec<ast::Utf16String>,
- annexb_function_names: Vec<ast::Utf16String>,
- has_arguments_object_local: bool,
-}
-
-/// Compute FDI runtime metadata for the SharedFunctionInstanceData of a
-/// function (ECMA-262 §10.2.11).
-fn compute_sfd_metadata(
- function_data: &ast::FunctionData,
- arena: &ast::AstArena,
-) -> bytecode::generator::FunctionSfdMetadata {
- let body_scope: Option<ast::ScopeId> = match &function_data.body.inner {
- ast::StatementKind::FunctionBody { scope, .. } => Some(*scope),
- _ => None,
- };
-
- let strict = function_data.is_strict_mode;
- let is_arrow = function_data.is_arrow_function;
-
- // Extract all scope analysis data in one borrow.
- let bsi = if let Some(scope_id) = body_scope {
- let sd = &arena.scopes[scope_id];
- let fsd = sd.function_scope_data.as_ref();
- BodyScopeInfo {
- uses_this: sd.uses_this || function_data.parsing_insights.uses_this,
- contains_eval: sd.contains_direct_call_to_eval,
- uses_this_from_env: sd.uses_this_from_environment
- || function_data.parsing_insights.uses_this_from_environment,
- might_need_arguments: function_data.parsing_insights.might_need_arguments_object,
- has_function_named_arguments: fsd.is_some_and(|f| f.has_function_named_arguments),
- has_lexically_declared_arguments: fsd.is_some_and(|f| f.has_lexically_declared_arguments),
- non_local_var_count: fsd.map_or(0, |f| f.non_local_var_count),
- non_local_var_count_for_parameter_expressions: fsd
- .map_or(0, |f| f.non_local_var_count_for_parameter_expressions),
- var_names: fsd.map(|f| &f.var_names).cloned().unwrap_or_default(),
- annexb_function_names: sd.annexb_function_names.clone(),
- has_arguments_object_local: sd
- .local_variables
- .iter()
- .any(|lv| lv.kind == ast::LocalVarKind::ArgumentsObject),
- }
- } else {
- BodyScopeInfo {
- uses_this: function_data.parsing_insights.uses_this,
- contains_eval: function_data.parsing_insights.contains_direct_call_to_eval,
- uses_this_from_env: function_data.parsing_insights.uses_this_from_environment,
- might_need_arguments: function_data.parsing_insights.might_need_arguments_object,
- has_function_named_arguments: false,
- has_lexically_declared_arguments: false,
- non_local_var_count: 0,
- non_local_var_count_for_parameter_expressions: 0,
- var_names: Vec::new(),
- annexb_function_names: Vec::new(),
- has_arguments_object_local: false,
- }
- };
-
- // §10.2.11 step 4: check for parameter expressions.
- let has_parameter_expressions = function_data.parameters.iter().any(|p| {
- p.default_value.is_some()
- || matches!(
- p.binding,
- ast::FunctionParameterBinding::BindingPattern(ref pat) if pat.contains_expression()
- )
- });
-
- // §10.2.11 steps 5-8: count non-local unique parameter names.
- let mut parameter_names: HashSet<ast::Utf16String> = HashSet::new();
- let mut parameters_in_environment: usize = 0;
- for parameter in &function_data.parameters {
- match &parameter.binding {
- ast::FunctionParameterBinding::Identifier(id) => {
- let ident = &arena.identifiers[*id];
- if parameter_names.insert(arena.strings[ident.name].clone()) && !ident.is_local() {
- parameters_in_environment += 1;
- }
- }
- ast::FunctionParameterBinding::BindingPattern(pattern) => {
- for_each_binding_pattern_identifier(pattern, arena, &mut |ident| {
- if parameter_names.insert(arena.strings[ident.name].clone()) && !ident.is_local() {
- parameters_in_environment += 1;
- }
- });
- }
- }
- }
-
- // §10.2.11 steps 15-18: determine if arguments object is needed.
- // We trust either the parser's conservative "might need arguments" flag
- // (set when we consume an `arguments` or `eval` Identifier as a free
- // reference) OR scope analysis having allocated an ArgumentsObject local
- // for `arguments`. The latter catches references created without going
- // through consume(), e.g. shorthand `{ arguments }` in an object literal.
- // Skip the local-driven path when a function named `arguments` shadows
- // it; in that case the local belongs to the function declaration, not
- // a real arguments-object reference.
- let arguments_object_referenced =
- bsi.might_need_arguments || (bsi.has_arguments_object_local && !bsi.has_function_named_arguments);
- let arguments_object_needed = arguments_object_referenced
- && !is_arrow
- && !parameter_names.contains(utf16!("arguments"))
- && body_scope.is_some()
- && (has_parameter_expressions || !bsi.has_function_named_arguments)
- && (has_parameter_expressions || !bsi.has_lexically_declared_arguments);
-
- // Arguments object needs an environment binding if it's not a local variable.
- let arguments_object_needs_binding = arguments_object_needed && !bsi.has_arguments_object_local;
-
- let mut function_environment_bindings_count: usize = 0;
- let mut var_environment_bindings_count: usize = 0;
- let mut lex_environment_bindings_count: usize = 0;
-
- // §10.2.11 step 19: route parameter bindings.
- // NB: The bytecode gives parameters an environment of their own whenever there are parameter expressions and
- // parameters in the environment, also in strict mode, where nothing can tell. The arguments binding and the
- // lexical declarations of strict code without var declarations in the environment then go there as well, and
- // to the function environment without one. Environments get exactly as many bindings as they are created
- // with room for, so that their shapes get final.
- let has_parameter_environment = has_parameter_expressions && parameters_in_environment > 0;
- let env_is_function_env = !has_parameter_environment;
- if env_is_function_env {
- function_environment_bindings_count += parameters_in_environment;
- }
-
- // §10.2.11 step 22: arguments binding.
- if arguments_object_needs_binding && env_is_function_env {
- function_environment_bindings_count += 1;
- }
-
- if let Some(body_scope) = body_scope
- && has_parameter_expressions
- && strict
- && bsi.non_local_var_count_for_parameter_expressions == 0
- && env_is_function_env
- {
- function_environment_bindings_count += count_non_local_lex_declarations(body_scope, arena);
- }
-
- if let Some(body_scope) = body_scope {
- if !has_parameter_expressions {
- // §10.2.11 step 27: var env shares function env.
- function_environment_bindings_count += bsi.non_local_var_count;
-
- // Annex B: function names hoisted from blocks that aren't already vars.
- if !strict {
- for name in &bsi.annexb_function_names {
- if !bsi.var_names.contains(name) {
- function_environment_bindings_count += 1;
- }
- }
- }
-
- // §10.2.11 step 30: lexical environment.
- let non_local_lex_count = count_non_local_lex_declarations(body_scope, arena);
- if strict {
- // Lex env == var env == function env.
- function_environment_bindings_count += non_local_lex_count;
- } else {
- let can_elide = !bsi.contains_eval && non_local_lex_count == 0;
- if !can_elide {
- lex_environment_bindings_count += non_local_lex_count;
- }
- }
- } else {
- // §10.2.11 step 28: separate var environment.
- var_environment_bindings_count += bsi.non_local_var_count_for_parameter_expressions;
-
- if !strict {
- for name in &bsi.annexb_function_names {
- if !bsi.var_names.contains(name) {
- var_environment_bindings_count += 1;
- }
- }
- }
-
- let non_local_lex_count = count_non_local_lex_declarations(body_scope, arena);
- if strict {
- // Lex env == var env.
- var_environment_bindings_count += non_local_lex_count;
- } else {
- let can_elide = !bsi.contains_eval && non_local_lex_count == 0;
- if !can_elide {
- lex_environment_bindings_count += non_local_lex_count;
- }
- }
- }
- }
+#[cfg(test)]
+mod tests {
+ use super::*;
- let this_value_needs_environment_resolution = bsi.uses_this_from_env;
- let function_environment_needed = arguments_object_needs_binding
- || (strict && has_parameter_environment)
- || function_environment_bindings_count > 0
- || var_environment_bindings_count > 0
- || lex_environment_bindings_count > 0
- || (!is_arrow && bsi.uses_this_from_env)
- || bsi.contains_eval;
-
- bytecode::generator::FunctionSfdMetadata {
- uses_this: bsi.uses_this,
- this_value_needs_environment_resolution,
- function_environment_needed,
- function_environment_bindings_count,
- var_environment_bindings_count,
- might_need_arguments: bsi.might_need_arguments,
- contains_eval: bsi.contains_eval,
+ fn compile(source: &str) -> CompiledProgram {
+ compile_parsed_program_off_thread(parse(&Utf16String::from_utf8(source), ProgramType::Script, 1))
}
-}
-/// Count non-local lexically-declared identifiers in a function body scope.
-/// Returns the count (used for environment sizing in the function_environment_needed
-/// computation).
-fn count_non_local_lex_declarations(scope_id: ast::ScopeId, arena: &ast::AstArena) -> usize {
- let sd = &arena.scopes[scope_id];
- let mut count = 0;
- for child in &sd.children {
- match &child.inner {
- ast::StatementKind::VariableDeclaration(vd) => {
- use crate::parser::DeclarationKind;
- if vd.kind == DeclarationKind::Let || vd.kind == DeclarationKind::Const {
- for declaration in &vd.declarations {
- count_non_local_names_in_target(&declaration.target, &mut count, arena);
- }
- }
- }
- ast::StatementKind::UsingDeclaration(declarations) => {
- for declaration in &declarations.declarations {
- count_non_local_names_in_target(&declaration.target, &mut count, arena);
- }
- }
- ast::StatementKind::ClassDeclaration(class_data) => {
- if let Some(name_ident) = class_data.name
- && !arena.identifiers[name_ident].is_local()
- {
- count += 1;
- }
- }
- _ => {}
- }
+ fn precompiled_functions(source: &str) -> Vec<bool> {
+ compile(source)
+ .executable
+ .shared_function_data
+ .iter()
+ .map(|function| function.precompiled_function.is_some())
+ .collect()
}
- count
-}
-fn count_non_local_names_in_target(target: &ast::VariableDeclaratorTarget, count: &mut usize, arena: &ast::AstArena) {
- match target {
- ast::VariableDeclaratorTarget::Identifier(id) => {
- if !arena.identifiers[*id].is_local() {
- *count += 1;
- }
- }
- ast::VariableDeclaratorTarget::BindingPattern(pattern) => {
- count_non_local_names_in_binding_pattern(pattern, count, arena);
+ #[test]
+ fn functions_that_run_right_away_compile_with_the_program() {
+ // NB: The stack of a test is too small for the frames of the parser of a build without optimizations.
+ std::thread::Builder::new()
+ .stack_size(1 << 25)
+ .spawn(functions_that_run_right_away_compile_with_enough_stack)
+ .expect("a thread starts")
+ .join()
+ .expect("the checks pass");
+ }
+
+ fn functions_that_run_right_away_compile_with_enough_stack() {
+ for source in [
+ "(function () {})();",
+ "(function () {}());",
+ "!function () {}();",
+ "((function () {}))();",
+ "(function () {}).call(this);",
+ "(function () {}.call(this));",
+ "((function () {})).call(this);",
+ "!function () {}.call(this);",
+ "(function () {}).apply(this, []);",
+ "(function () {}.apply(this, []));",
+ "(() => {})();",
+ "(x => x)(1);",
+ "((a, b) => {})(1, 2);",
+ "((a = 1) => {})();",
+ "((() => {}))();",
+ "!(() => {})();",
+ "var result = (() => {})();",
+ "(() => {}).call(this);",
+ "(async () => {})();",
+ "(async x => x)();",
+ "(async (a, b) => {})();",
+ "(async function () {})();",
+ ] {
+ assert_eq!(precompiled_functions(source), [true], "{source}");
}
}
-}
-fn count_non_local_names_in_binding_pattern(pattern: &ast::BindingPattern, count: &mut usize, arena: &ast::AstArena) {
- for entry in &pattern.entries {
- match &entry.alias {
- Some(ast::BindingEntryAlias::Identifier(id)) => {
- if !arena.identifiers[*id].is_local() {
- *count += 1;
- }
- }
- Some(ast::BindingEntryAlias::BindingPattern(sub)) => {
- count_non_local_names_in_binding_pattern(sub, count, arena);
- }
- None => {
- if let Some(ast::BindingEntryName::Identifier(id)) = &entry.name
- && !arena.identifiers[*id].is_local()
- {
- *count += 1;
- }
- }
- Some(ast::BindingEntryAlias::MemberExpression(_)) => {}
+ #[test]
+ fn other_functions_wait_for_their_first_call() {
+ for source in [
+ "(function () {});",
+ "(function () {}).bind(this);",
+ "(function () {}).call;",
+ "(function () {})[call](this);",
+ "(function () {}).call.call(this);",
+ "new (function () {})();",
+ "f(function () {});",
+ "var f = function () {};",
+ "f.call(function () {});",
+ "(() => {});",
+ "f(() => {});",
+ "f((a) => {});",
+ "f(x => x);",
+ "f(() => {})();",
+ "var f = () => {};",
+ "[() => {}];",
+ ] {
+ assert_eq!(precompiled_functions(source), [false], "{source}");
}
}
-}
-fn for_each_binding_pattern_identifier(
- pattern: &ast::BindingPattern,
- arena: &ast::AstArena,
- callback: &mut dyn FnMut(&ast::Identifier),
-) {
- for entry in &pattern.entries {
- match &entry.alias {
- Some(ast::BindingEntryAlias::Identifier(id)) => callback(&arena.identifiers[*id]),
- Some(ast::BindingEntryAlias::BindingPattern(sub)) => {
- for_each_binding_pattern_identifier(sub, arena, callback);
- }
- None => {
- if let Some(ast::BindingEntryName::Identifier(id)) = &entry.name {
- callback(&arena.identifiers[*id]);
- }
- }
- Some(ast::BindingEntryAlias::MemberExpression(_)) => {}
- }
+ #[test]
+ fn code_of_an_eval_does_not_keep_its_script_alive() {
+ let parsed = parse_eval(&Utf16String::from_utf8("1 + 1"), EvalContext::default())
+ .ok()
+ .expect("the source parses");
+ let script = Arc::downgrade(&parsed.tree.script);
+ let compiled = compile_eval(parsed);
+ assert!(script.upgrade().is_none());
+ assert!(compiled.executable.position_source.is_some());
}
}
diff --git a/Libraries/LibJS/Rust/src/contrib/test262/262_object.rs b/Libraries/LibJS/Rust/src/contrib/test262/262_object.rs
index b7c1734678b..11ac4688b95 100644
--- a/Libraries/LibJS/Rust/src/contrib/test262/262_object.rs
+++ b/Libraries/LibJS/Rust/src/contrib/test262/262_object.rs
@@ -27,7 +27,6 @@ use crate::runtime::property_attributes::{Attribute, PropertyAttributes};
use crate::runtime::property_key::PropertyKey;
use crate::runtime::realm::Realm;
use crate::script::Script;
-use crate::utf16::Utf16View;
/// The $262 object that test262's INTERPRETING.md describes.
#[repr(C)]
@@ -139,9 +138,7 @@ impl Dollar262Object {
let realm = vm.current_realm().expect("$262.evalScript runs in a realm");
// 3. Let s be ParseScript(sourceText, realm, hostDefined).
- let mut source = Vec::new();
- Utf16View::of_string(&source_text).append_to(&mut source);
- let script_or_error = Script::parse(vm, &source, realm);
+ let script_or_error = Script::parse(vm, &source_text, realm);
// 4. If s is a List of errors, then
let script = match script_or_error {
diff --git a/Libraries/LibJS/Rust/src/debugger.rs b/Libraries/LibJS/Rust/src/debugger.rs
index 5beb63698e7..5431e39cb2c 100644
--- a/Libraries/LibJS/Rust/src/debugger.rs
+++ b/Libraries/LibJS/Rust/src/debugger.rs
@@ -18,8 +18,8 @@ use indexmap::IndexMap;
use libjs_runtime_macros::Trace;
use crate::breakpoint::{Breakpoint, BreakpointID};
-use crate::bytecode::basic_block::SourceMapEntry;
-use crate::bytecode::executable::{Executable, LocalVariableMetadata};
+use crate::bytecode::executable::{Executable, LocalVariableScopeRange};
+use crate::bytecode::source_map::SourceMapEntry;
use crate::gc::foreign::ForeignCellSlot;
use crate::gc::root::MarkedVec;
use crate::gc::sweep::Sweep;
@@ -375,8 +375,8 @@ impl Debugger {
} else {
executable.source_range_at(context.program_counter.get())
};
- let scope_is_active = |metadata: &LocalVariableMetadata| {
- let (Some(scope_range), Some(paused_source_range)) = (metadata.scope_range, &paused_source_range) else {
+ let scope_is_active = |scope_range: Option<LocalVariableScopeRange>| {
+ let (Some(scope_range), Some(paused_source_range)) = (scope_range, &paused_source_range) else {
return true;
};
let position = paused_source_range.start;
@@ -387,15 +387,15 @@ impl Debugger {
if name.is_empty() {
continue;
}
- let metadata = executable.local_variable_metadata[index];
- if !scope_is_active(&metadata) {
+ let scope_range = executable.local_variable_scope_range(index);
+ if !scope_is_active(scope_range) {
continue;
}
if let Some(existing) = binding_locations.get(name)
&& existing.storage == BindingStorage::Local
{
- let Some(scope_range) = metadata.scope_range else {
+ let Some(scope_range) = scope_range else {
continue;
};
if existing
@@ -410,8 +410,8 @@ impl Debugger {
BindingLocation {
storage: BindingStorage::Local,
index,
- is_mutable: metadata.is_mutable,
- scope_start: metadata.scope_range.map(|range| range.start),
+ is_mutable: executable.local_variable_metadata()[index].is_mutable,
+ scope_start: scope_range.map(|range| range.start),
},
);
}
@@ -739,7 +739,7 @@ impl Debugger {
return true;
}
- for entry in &executable.source_map {
+ for entry in executable.source_positions() {
if entry.bytecode_offset > bytecode_offset && entry.line > 0 {
return false;
}
@@ -796,7 +796,7 @@ fn breakpoint_candidate_for_executable(breakpoint: &Breakpoint, executable: &Exe
}
let mut matching_entry: Option<SourceMapEntry> = None;
- for entry in &executable.source_map {
+ for entry in executable.source_positions() {
if entry.line == 0 || entry.line < breakpoint.line {
continue;
}
@@ -807,7 +807,7 @@ fn breakpoint_candidate_for_executable(breakpoint: &Breakpoint, executable: &Exe
entry.line < matching_entry.line
|| (entry.line == matching_entry.line && entry.column < matching_entry.column)
}) {
- matching_entry = Some(*entry);
+ matching_entry = Some(entry);
}
}
matching_entry
diff --git a/Libraries/LibJS/Rust/src/embedding/compile.rs b/Libraries/LibJS/Rust/src/embedding/compile.rs
index aac79c360e2..5e2015e8837 100644
--- a/Libraries/LibJS/Rust/src/embedding/compile.rs
+++ b/Libraries/LibJS/Rust/src/embedding/compile.rs
@@ -11,37 +11,29 @@
//! A JSParsedProgram and a JSCompiledProgram hold nothing of the VM or its heap, so any thread may create, inspect,
//! compile or destroy them, and they may move between threads. Everything that takes a JSVM runs on the VM's thread.
//!
-//! The functions of a script or module that do not run right away compile on their first call. An embedder can have
-//! them compiled on its worker threads before that instead, through JSOffThreadCompilationCallbacks.
+//! The functions of a script or module that do not run right away compile on their first call.
//!
//! Tokenizing source text for syntax highlighting, and finding the positions of a source where a debugger can stop,
//! need no VM either.
use core::ffi::c_void;
-use std::borrow::Cow;
-use std::sync::Arc;
-use crate::ast::{FunctionPayload, ProgramType};
-use crate::bytecode::bytecode_cache::ExecutableBacking;
-use crate::bytecode::executable::Executable;
-use crate::bytecode::generator::PrecompiledFunction;
+use crate::ast::ProgramType;
use crate::compile::{
- CompiledProgram, FunctionPrecompileMode, ParsedProgram, compile_function, compile_module,
- compile_parsed_program_off_thread, compile_script, parse,
+ CompiledProgram, ParsedProgram, compile_module, compile_parsed_program_off_thread, compile_script, parse,
+};
+use crate::embedding::abi_types::{
+ JSOwnedUtf16String, JSRealm, JSSourceCode, JSUtf16View, cell_from_abi, cell_into_abi, owned_utf16_string_from_abi,
+ vm_from_abi,
};
-use crate::embedding::abi_types::{JSRealm, JSSourceCode, JSUtf16View, cell_from_abi, cell_into_abi, vm_from_abi};
use crate::embedding::script::{JSParserErrorSink, JSScript, append_to_parser_error_sink, host_defined_slot_from_abi};
use crate::embedding::source_code::{shared_source_code_from_abi, source_code_into_abi};
-use crate::gc::root::{MarkedVec, Root};
-use crate::interpreter::vm::Vm;
use crate::layout::cell::Gc;
use crate::layout::host_class::{JSModule, JSVM};
use crate::parser_error::ParserError;
use crate::runtime::module::Module;
-use crate::runtime::shared_function_instance_data::SharedFunctionInstanceData;
use crate::runtime::source_text_module::SourceTextModule;
use crate::script::Script;
-use crate::utf16::Utf16View;
/// A program that the frontend parsed, with or without syntax errors, which no VM owns: LibJS's JS::ParsedProgram.
pub struct JSParsedProgram {
@@ -70,45 +62,26 @@ pub fn program_type_from_abi(program_type: JSProgramType) -> ProgramType {
}
}
-/// What the frontend parses from: UTF-16 code units, which a view in the ASCII storage kind is widened to.
-///
-/// # Safety
-///
-/// The view must be valid for `'a`.
-pub unsafe fn code_units_of<'a>(source: JSUtf16View) -> Cow<'a, [u16]> {
- // SAFETY: The caller passes a valid view.
- match unsafe { source.as_view() } {
- Utf16View::Utf16(code_units) => Cow::Borrowed(code_units),
- one_byte @ (Utf16View::Ascii(_) | Utf16View::Latin1(_)) => Cow::Owned(one_byte.code_units().collect()),
- }
-}
-
-/// A parsed program together with the length of the source it was parsed from, which compiling it needs.
-struct ParsedSourceText {
- program: ParsedProgram,
- source_length_in_code_units: usize,
-}
-
-fn parsed_program_into_abi(parsed: ParsedSourceText) -> *mut JSParsedProgram {
+fn parsed_program_into_abi(parsed: ParsedProgram) -> *mut JSParsedProgram {
Box::into_raw(Box::new(parsed)).cast()
}
/// # Safety
///
/// `parsed` must be a parsed program the ABI handed out and that is still alive for `'a`.
-unsafe fn parsed_program_from_abi<'a>(parsed: *const JSParsedProgram) -> &'a ParsedSourceText {
+unsafe fn parsed_program_from_abi<'a>(parsed: *const JSParsedProgram) -> &'a ParsedProgram {
assert!(!parsed.is_null(), "the embedder passes a parsed program");
- // SAFETY: The caller passes a live parsed program, which is a boxed ParsedSourceText.
- unsafe { &*parsed.cast::<ParsedSourceText>() }
+ // SAFETY: The caller passes a live parsed program, which is a boxed ParsedProgram.
+ unsafe { &*parsed.cast::<ParsedProgram>() }
}
/// # Safety
///
/// `parsed` must be a parsed program the ABI handed out, which the caller gives up.
-unsafe fn take_parsed_program_from_abi(parsed: *mut JSParsedProgram) -> ParsedSourceText {
+unsafe fn take_parsed_program_from_abi(parsed: *mut JSParsedProgram) -> ParsedProgram {
assert!(!parsed.is_null(), "the embedder passes a parsed program");
- // SAFETY: The caller gives up a boxed ParsedSourceText.
- *unsafe { Box::from_raw(parsed.cast::<ParsedSourceText>()) }
+ // SAFETY: The caller gives up a boxed ParsedProgram.
+ *unsafe { Box::from_raw(parsed.cast::<ParsedProgram>()) }
}
fn compiled_program_into_abi(compiled: CompiledProgram) -> *mut JSCompiledProgram {
@@ -141,23 +114,21 @@ pub unsafe fn source_text_module_from_abi(module: *mut JSModule) -> Gc<SourceTex
/// ParsedProgram::parse(source_text, type, line_number_offset): parses `source` as a classic script or a module, with
/// its lines counted from `line_number_offset`, except that a module's lines start at 1 or later. The program holds its
-/// syntax errors, if it has any. The caller owns the program. Borrows the view. Any thread may call this.
+/// syntax errors, if it has any. The caller owns the program. Adopts the string, whose storage the program shares from
+/// then on. Any thread may call this.
///
/// # Safety
///
-/// The view must be valid.
+/// `source` must be a raw AK::Utf16String whose reference the caller gives up.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_compile_parse(
- source: JSUtf16View,
+ source: JSOwnedUtf16String,
program_type: JSProgramType,
line_number_offset: usize,
) -> *mut JSParsedProgram {
- // SAFETY: The caller passes a valid view.
- let source = unsafe { code_units_of(source) };
- parsed_program_into_abi(ParsedSourceText {
- program: parse(&source, program_type_from_abi(program_type), line_number_offset),
- source_length_in_code_units: source.len(),
- })
+ // SAFETY: The caller transfers its reference.
+ let source = unsafe { owned_utf16_string_from_abi(source) };
+ parsed_program_into_abi(parse(&source, program_type_from_abi(program_type), line_number_offset))
}
/// ParsedProgram::has_errors(). Any thread may call this.
@@ -168,23 +139,7 @@ pub unsafe extern "C" fn js_compile_parse(
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_compile_parsed_program_has_errors(parsed: *const JSParsedProgram) -> bool {
// SAFETY: The caller passes a live parsed program.
- unsafe { parsed_program_from_abi(parsed) }.program.has_errors()
-}
-
-/// ParsedProgram::clone(): a copy of a program without errors, which compiles independently of it, such as for the
-/// bytecode cache while the original runs. The caller owns the copy. Any thread may call this.
-///
-/// # Safety
-///
-/// `parsed` must be a live parsed program without errors.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn js_compile_parsed_program_clone(parsed: *const JSParsedProgram) -> *mut JSParsedProgram {
- // SAFETY: The caller passes a live parsed program.
- let parsed = unsafe { parsed_program_from_abi(parsed) };
- parsed_program_into_abi(ParsedSourceText {
- program: parsed.program.clone_for_separate_compilation(),
- source_length_in_code_units: parsed.source_length_in_code_units,
- })
+ unsafe { parsed_program_from_abi(parsed) }.has_errors()
}
/// Destroys a parsed program that the caller owns. Null does nothing. Any thread may call this.
@@ -202,9 +157,7 @@ pub unsafe extern "C" fn js_compile_parsed_program_destroy(parsed: *mut JSParsed
/// CompiledProgram::compile(ParsedProgram): compiles a program that parsed without errors, which this consumes. The
/// bytecode covers the top level and the functions it invokes right away; every other function compiles on its first
-/// call, or through js_compile_remaining_functions_of_script_off_thread() and
-/// js_compile_remaining_functions_of_module_off_thread(). The caller owns the compiled program. Any thread may call
-/// this.
+/// call. The caller owns the compiled program. Any thread may call this.
///
/// # Safety
///
@@ -213,32 +166,7 @@ pub unsafe extern "C" fn js_compile_parsed_program_destroy(parsed: *mut JSParsed
pub unsafe extern "C" fn js_compile_parsed_program(parsed: *mut JSParsedProgram) -> *mut JSCompiledProgram {
// SAFETY: The caller gives up a live parsed program.
let parsed = unsafe { take_parsed_program_from_abi(parsed) };
- compiled_program_into_abi(compile_parsed_program_off_thread(
- parsed.program,
- parsed.source_length_in_code_units,
- FunctionPrecompileMode::EagerOnly,
- ))
-}
-
-/// CompiledProgram::compile_all_functions(ParsedProgram): compiles a program that parsed without errors, which this
-/// consumes, with every function it contains, as the bytecode cache needs: the result only feeds
-/// js_bytecode_cache_serialize(), and never becomes a script or module. The caller owns the compiled program. Any thread
-/// may call this.
-///
-/// # Safety
-///
-/// `parsed` must be a live parsed program without errors, which the caller gives up.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn js_compile_parsed_program_with_all_functions(
- parsed: *mut JSParsedProgram,
-) -> *mut JSCompiledProgram {
- // SAFETY: The caller gives up a live parsed program.
- let parsed = unsafe { take_parsed_program_from_abi(parsed) };
- compiled_program_into_abi(compile_parsed_program_off_thread(
- parsed.program,
- parsed.source_length_in_code_units,
- FunctionPrecompileMode::All,
- ))
+ compiled_program_into_abi(compile_parsed_program_off_thread(parsed))
}
/// # Safety
@@ -270,13 +198,13 @@ pub unsafe extern "C" fn js_compile_compiled_program_destroy(compiled: *mut JSCo
///
/// `errors` must be null or a valid sink.
unsafe fn parsed_program_without_errors(
- parsed: ParsedSourceText,
+ parsed: ParsedProgram,
errors: *const JSParserErrorSink,
) -> Option<ParsedProgram> {
- if !parsed.program.has_errors() {
- return Some(parsed.program);
+ if !parsed.has_errors() {
+ return Some(parsed);
}
- let parser_errors = ParserError::all_from_parsed_program(&parsed.program);
+ let parser_errors = ParserError::all_from_parsed_program(&parsed);
drop(parsed);
// SAFETY: The caller passes null or a valid sink.
unsafe { append_to_parser_error_sink(errors, &parser_errors) };
@@ -319,15 +247,13 @@ pub unsafe extern "C" fn js_compile_create_script_from_parsed_program(
let Some(parsed) = (unsafe { parsed_program_without_errors(parsed, errors) }) else {
return core::ptr::null_mut();
};
- let source_length = source_code.length_in_code_units();
cell_into_abi(Script::create(
vm,
realm,
- compile_script(parsed, source_length),
+ compile_script(parsed),
source_code,
&filename,
host_defined,
- ExecutableBacking::Source,
))
}
@@ -367,7 +293,6 @@ pub unsafe extern "C" fn js_compile_create_script_from_compiled_program(
source_code,
&filename,
host_defined,
- ExecutableBacking::HeapBytecode,
))
}
@@ -405,15 +330,13 @@ pub unsafe extern "C" fn js_compile_create_module_from_parsed_program(
let Some(parsed) = (unsafe { parsed_program_without_errors(parsed, errors) }) else {
return core::ptr::null_mut();
};
- let source_length = source_code.length_in_code_units();
module_into_abi(SourceTextModule::create(
vm,
realm,
&filename,
- compile_module(parsed, source_length),
+ compile_module(parsed),
source_code,
host_defined,
- ExecutableBacking::Source,
))
}
@@ -451,7 +374,6 @@ pub unsafe extern "C" fn js_compile_create_module_from_compiled_program(
compiled.into_module(),
source_code,
host_defined,
- ExecutableBacking::HeapBytecode,
))
}
@@ -489,269 +411,6 @@ pub unsafe extern "C" fn js_compile_top_level_source_code_of_module(module: *mut
.unwrap_or(core::ptr::null())
}
-/// Work that the embedder runs once, on the thread that the callback receiving it names: C++ Function<void()>.
-#[repr(C)]
-pub struct JSOffThreadTask {
- pub run: Option<unsafe extern "C" fn(data: *mut c_void)>,
- pub data: *mut c_void,
-}
-
-/// OffThreadCompilationCallbacks: how an embedder runs background compilation work. The runtime copies the struct and
-/// calls the functions with `context` from both threads, so they and the context must work on any thread.
-///
-/// - `submit_work` is called on the VM's thread, and must run the task on a worker thread.
-/// - `post_to_main_thread` is called on a worker thread, and must run the task on the VM's thread.
-/// - `release`, which may be null, is called once, on either thread, when the runtime no longer needs the callbacks.
-///
-/// A callback may also run its task right away when it is already on the task's thread, which is how an embedder
-/// without threads runs the work synchronously. The tasks hold nothing of the VM that a callback must keep alive.
-#[repr(C)]
-pub struct JSOffThreadCompilationCallbacks {
- pub context: *mut c_void,
- pub submit_work: Option<unsafe extern "C" fn(context: *mut c_void, task: JSOffThreadTask)>,
- pub post_to_main_thread: Option<unsafe extern "C" fn(context: *mut c_void, task: JSOffThreadTask)>,
- pub release: Option<unsafe extern "C" fn(context: *mut c_void)>,
-}
-
-/// The embedder's callbacks, which the VM's thread and the worker share: the worker can still be inside
-/// post_to_main_thread() when the VM's thread has run the task it posted.
-struct SharedOffThreadCompilationCallbacks(JSOffThreadCompilationCallbacks);
-
-// SAFETY: The embedder's callbacks work on any thread, as JSOffThreadCompilationCallbacks requires.
-unsafe impl Send for SharedOffThreadCompilationCallbacks {}
-// SAFETY: As above.
-unsafe impl Sync for SharedOffThreadCompilationCallbacks {}
-
-impl SharedOffThreadCompilationCallbacks {
- fn submit_work(&self, run: unsafe extern "C" fn(*mut c_void), data: *mut c_void) {
- let submit_work = self.0.submit_work.expect("the embedder submits work to its workers");
- // SAFETY: The embedder's callback takes tasks with the context it came with.
- unsafe { submit_work(self.0.context, JSOffThreadTask { run: Some(run), data }) };
- }
-
- fn post_to_main_thread(&self, run: unsafe extern "C" fn(*mut c_void), data: *mut c_void) {
- let post_to_main_thread = self
- .0
- .post_to_main_thread
- .expect("the embedder posts tasks to the VM's thread");
- // SAFETY: As above.
- unsafe { post_to_main_thread(self.0.context, JSOffThreadTask { run: Some(run), data }) };
- }
-}
-
-impl Drop for SharedOffThreadCompilationCallbacks {
- fn drop(&mut self) {
- if let Some(release) = self.0.release {
- // SAFETY: The runtime is done with the callbacks, which the embedder releases once.
- unsafe { release(self.0.context) };
- }
- }
-}
-
-/// What the VM's thread keeps while a worker compiles copies of the ASTs of some functions: their shared data, which
-/// stays alive until the compiled functions are installed in it.
-struct LazyFunctionsAwaitingCompilation {
- vm: &'static Vm,
- shared_function_data: Root<'static, Vec<Gc<SharedFunctionInstanceData>>>,
- callbacks: Arc<SharedOffThreadCompilationCallbacks>,
-}
-
-/// What a worker carries without touching it, from the VM's thread and back.
-struct OnlyForTheVmsThread(Box<LazyFunctionsAwaitingCompilation>);
-
-// SAFETY: Only the VM's thread opens what the worker carries.
-unsafe impl Send for OnlyForTheVmsThread {}
-
-/// The task a worker runs.
-#[allow(clippy::vec_box, reason = "the frontend compiles boxed ASTs")]
-struct LazyFunctionCompilation {
- function_asts: Vec<Box<FunctionPayload>>,
- source_length_in_code_units: usize,
- callbacks: Arc<SharedOffThreadCompilationCallbacks>,
- awaiting_compilation: OnlyForTheVmsThread,
-}
-
-/// The task the worker posts back to the VM's thread.
-#[allow(
- clippy::vec_box,
- reason = "the frontend returns boxed functions, which shared function data keeps boxed"
-)]
-struct CompiledLazyFunctions {
- compiled_functions: Vec<Box<PrecompiledFunction>>,
- awaiting_compilation: OnlyForTheVmsThread,
-}
-
-const _: fn() = || {
- fn assert_send<T: Send>() {}
- assert_send::<LazyFunctionCompilation>();
- assert_send::<CompiledLazyFunctions>();
-};
-
-/// Has a worker compile copies of the ASTs of the functions, and installs the results on the VM's thread.
-fn compile_lazy_functions_off_thread(
- vm: &'static Vm,
- shared_function_data: &MarkedVec<'_, Gc<SharedFunctionInstanceData>>,
- function_asts: impl IntoIterator<Item = Box<FunctionPayload>>,
- source_length_in_code_units: usize,
- callbacks: Arc<SharedOffThreadCompilationCallbacks>,
-) {
- let awaiting_compilation = LazyFunctionsAwaitingCompilation {
- vm,
- shared_function_data: Root::new(vm, shared_function_data.to_vec()),
- callbacks: callbacks.clone(),
- };
- let work = Box::new(LazyFunctionCompilation {
- function_asts: function_asts.into_iter().collect(),
- source_length_in_code_units,
- callbacks: callbacks.clone(),
- awaiting_compilation: OnlyForTheVmsThread(Box::new(awaiting_compilation)),
- });
- callbacks.submit_work(compile_lazy_functions_on_a_worker, Box::into_raw(work).cast());
-}
-
-unsafe extern "C" fn compile_lazy_functions_on_a_worker(work: *mut c_void) {
- // SAFETY: The embedder runs each task once, with the data that came with it, which is this boxed work.
- let work = *unsafe { Box::from_raw(work.cast::<LazyFunctionCompilation>()) };
- let compiled_functions = work
- .function_asts
- .into_iter()
- .map(|function_ast| {
- compile_function(
- function_ast,
- work.source_length_in_code_units,
- false,
- FunctionPrecompileMode::All,
- )
- })
- .collect();
- let compiled = Box::new(CompiledLazyFunctions {
- compiled_functions,
- awaiting_compilation: work.awaiting_compilation,
- });
- work.callbacks
- .post_to_main_thread(install_compiled_lazy_functions, Box::into_raw(compiled).cast());
-}
-
-unsafe extern "C" fn install_compiled_lazy_functions(compiled: *mut c_void) {
- // SAFETY: The embedder runs each task once, with the data that came with it, which is this boxed result.
- let compiled = *unsafe { Box::from_raw(compiled.cast::<CompiledLazyFunctions>()) };
- let awaiting_compilation = compiled.awaiting_compilation.0;
- let shared_function_data = awaiting_compilation.shared_function_data.get();
- assert_eq!(shared_function_data.len(), compiled.compiled_functions.len());
- for (&shared_data, compiled_function) in shared_function_data.iter().zip(compiled.compiled_functions) {
- // A function that started running in the meantime compiled on this thread, so the worker compiles the
- // functions it creates instead.
- if let Some(executable) = shared_data.executable() {
- compile_remaining_functions_of_executable_off_thread(
- awaiting_compilation.vm,
- executable,
- awaiting_compilation.callbacks.clone(),
- );
- continue;
- }
- // Installing a bytecode cache may have dropped the AST, and its bytecode with it, while the worker compiled.
- if !shared_data.has_function_ast() {
- continue;
- }
- shared_data.set_precompiled_bytecode_executable(compiled_function);
- }
- drop(awaiting_compilation);
-}
-
-fn compile_remaining_functions_of_executable_off_thread(
- vm: &'static Vm,
- executable: Gc<Executable>,
- callbacks: Arc<SharedOffThreadCompilationCallbacks>,
-) {
- let shared_function_data = MarkedVec::new(vm);
- let function_asts = SharedFunctionInstanceData::uncompiled_functions_of(executable, &shared_function_data);
- if function_asts.is_empty() {
- return;
- }
- // NB: The frontend checks that nested functions lie within the source, which is unknown without a source code.
- let source_length_in_code_units = executable
- .source_code
- .as_ref()
- .map_or(usize::MAX, |source_code| source_code.length_in_code_units());
- compile_lazy_functions_off_thread(
- vm,
- &shared_function_data,
- function_asts,
- source_length_in_code_units,
- callbacks,
- );
-}
-
-/// # Safety
-///
-/// `callbacks` must point to valid callbacks.
-unsafe fn shared_callbacks_from_abi(
- callbacks: *const JSOffThreadCompilationCallbacks,
-) -> Arc<SharedOffThreadCompilationCallbacks> {
- assert!(!callbacks.is_null(), "the embedder passes its callbacks");
- // SAFETY: The caller passes valid callbacks, which the runtime copies.
- let callbacks = unsafe { callbacks.read() };
- Arc::new(SharedOffThreadCompilationCallbacks(callbacks))
-}
-
-/// compile_remaining_functions_off_thread(Script&, source_code, callbacks): has the embedder's workers compile the
-/// functions that the script's top-level code creates and that have not been compiled yet, so that their first calls
-/// do not have to. Functions that start running in the meantime compile on the VM's thread as usual, and the functions
-/// they create are then compiled off thread as well. The compiled functions are installed when the tasks the workers
-/// post run on the VM's thread. The VM must outlive every task. Only the VM's thread may call this.
-///
-/// # Safety
-///
-/// `vm` and `script` must be live, and `callbacks` must point to valid callbacks.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn js_compile_remaining_functions_of_script_off_thread(
- vm: *mut JSVM,
- script: *mut JSScript,
- callbacks: *const JSOffThreadCompilationCallbacks,
-) {
- // SAFETY: The caller passes a live VM and script, and valid callbacks, and the VM outlives the tasks.
- let (vm, script, callbacks) = unsafe {
- (
- vm_from_abi(vm),
- cell_from_abi(script),
- shared_callbacks_from_abi(callbacks),
- )
- };
- compile_remaining_functions_of_executable_off_thread(vm, script.cached_executable(), callbacks);
-}
-
-/// compile_remaining_functions_off_thread(SourceTextModule&, source_code, callbacks): like
-/// js_compile_remaining_functions_of_script_off_thread(), for the functions of a module, whose body is the async
-/// function of a module with top-level await. Only the VM's thread may call this.
-///
-/// # Safety
-///
-/// `vm` and `module` must be live, `module` a Source Text Module Record, and `callbacks` must point to valid
-/// callbacks.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn js_compile_remaining_functions_of_module_off_thread(
- vm: *mut JSVM,
- module: *mut JSModule,
- callbacks: *const JSOffThreadCompilationCallbacks,
-) {
- // SAFETY: The caller passes a live VM and module, and valid callbacks, and the VM outlives the tasks.
- let (vm, module, callbacks) = unsafe {
- (
- vm_from_abi(vm),
- source_text_module_from_abi(module),
- shared_callbacks_from_abi(callbacks),
- )
- };
- let executable = module.cached_executable().or_else(|| {
- module
- .top_level_await_shared_data()
- .and_then(|shared_data| shared_data.executable())
- });
- if let Some(executable) = executable {
- compile_remaining_functions_of_executable_off_thread(vm, executable, callbacks);
- }
-}
-
/// A token of a source text, with the trivia (whitespace and comments) before it, which JS::SyntaxHighlighter reads.
/// token_type and category are the values of JS::TokenType and JS::TokenCategory, and the offsets and lengths count
/// UTF-16 code units.
@@ -808,9 +467,9 @@ const _: () = {
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_compile_tokenize(source: JSUtf16View, tokens: *const JSTokenSink) {
// SAFETY: The caller passes a valid view and sink.
- let (source, tokens) = unsafe { (code_units_of(source), &*tokens) };
+ let (source, tokens) = unsafe { (source.as_view(), &*tokens) };
let append = tokens.append.expect("a token sink has an append function");
- for token in crate::tokenize::tokenize(&source) {
+ for token in crate::tokenize::tokenize(source) {
let token = JSToken {
token_type: token.token_type as u8,
category: token.category as u8,
@@ -856,7 +515,7 @@ pub unsafe extern "C" fn js_compile_breakpoint_positions_for_source(
positions: *const JSPositionSink,
) {
// SAFETY: The caller passes a valid view and sink.
- let (source, sink) = unsafe { (code_units_of(source), &*positions) };
+ let (source, sink) = unsafe { (source.as_view().to_utf16_string(), &*positions) };
let append = sink.append.expect("a position sink has an append function");
let positions: Vec<JSPosition> = crate::breakpoint_positions::breakpoint_positions_for_source(
&source,
diff --git a/Libraries/LibJS/Rust/src/embedding/mod.rs b/Libraries/LibJS/Rust/src/embedding/mod.rs
index 736b6132cf3..d7d2e760de0 100644
--- a/Libraries/LibJS/Rust/src/embedding/mod.rs
+++ b/Libraries/LibJS/Rust/src/embedding/mod.rs
@@ -23,7 +23,6 @@ pub mod abi_types;
pub mod array;
pub mod array_buffer;
pub mod bigint;
-pub mod bytecode_cache;
pub mod collections;
pub mod compile;
pub mod completion;
diff --git a/Libraries/LibJS/Rust/src/embedding/script.rs b/Libraries/LibJS/Rust/src/embedding/script.rs
index 8f1ad2e6a08..c1b30b1a36a 100644
--- a/Libraries/LibJS/Rust/src/embedding/script.rs
+++ b/Libraries/LibJS/Rust/src/embedding/script.rs
@@ -104,7 +104,7 @@ pub unsafe extern "C" fn js_script_parse(
host_defined_slot_from_abi(host_defined),
)
};
- let source: Vec<u16> = source.code_units().collect();
+ let source = source.to_utf16_string();
match Script::parse_with_host_defined(
vm,
&source,
diff --git a/Libraries/LibJS/Rust/src/fast_hash.rs b/Libraries/LibJS/Rust/src/fast_hash.rs
index 4c963fb9a58..6b29f405e34 100644
--- a/Libraries/LibJS/Rust/src/fast_hash.rs
+++ b/Libraries/LibJS/Rust/src/fast_hash.rs
@@ -5,11 +5,10 @@
*/
//! Type aliases that swap the default RandomState (SipHash) for
-//! foldhash's quality variant. Used in parser/scope-collector hot paths
+//! foldhash's quality variant. Used in parser hot paths
//! where keys come from lexer tokens (i.e. attacker-controlled JS
//! source), so we keep formal HashDoS resistance while shedding
//! SipHash's per-byte cost.
pub type HashMap<K, V> = std::collections::HashMap<K, V, foldhash::quality::RandomState>;
pub type HashSet<T> = std::collections::HashSet<T, foldhash::quality::RandomState>;
-pub type IndexMap<K, V> = indexmap::IndexMap<K, V, foldhash::quality::RandomState>;
diff --git a/Libraries/LibJS/Rust/src/host.rs b/Libraries/LibJS/Rust/src/host.rs
index fdf845e0650..eaf7699662f 100644
--- a/Libraries/LibJS/Rust/src/host.rs
+++ b/Libraries/LibJS/Rust/src/host.rs
@@ -11,7 +11,7 @@
use num_bigint::BigInt;
-use crate::ast::Utf16String;
+use ak::Utf16String;
#[cfg(not(test))]
use crate::frontend_host as implementation;
@@ -21,13 +21,13 @@ use crate::test_host as implementation;
/// Convert a JS number to its UTF-16 string representation using the
/// ECMA-262 Number::toString algorithm, which the host implements.
pub fn js_number_to_utf16(value: f64) -> Utf16String {
- Utf16String(implementation::number_to_utf16(value))
+ Utf16String::from_utf16(&implementation::number_to_utf16(value))
}
/// Check a regex pattern+flags with the host's regex engine, so that an invalid
/// one becomes an early error. Returns the error message if it is invalid.
pub fn validate_regex(pattern: &[u16], flags: &[u16]) -> Result<(), Utf16String> {
- implementation::validate_regex(pattern, flags).map_err(|message| Utf16String(message.encode_utf16().collect()))
+ implementation::validate_regex(pattern, flags).map_err(|message| Utf16String::from_utf8(&message))
}
/// StringToNumber(str), which the host implements.
diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/bindings.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/bindings.rs
index 53c1e118703..a980c460d38 100644
--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/bindings.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/bindings.rs
@@ -246,7 +246,7 @@ fn current_executable(vm: &Vm) -> Gc<Executable> {
/// VM::get_identifier(), copied out of the executable's identifier table.
fn get_identifier(vm: &Vm, index: IdentifierTableIndex) -> Utf16FlyString {
- current_executable(vm).identifier_table[index.0 as usize].clone()
+ current_executable(vm).identifier_table()[index.0 as usize].clone()
}
fn strict_of(header: &InstructionHeader) -> Strict {
@@ -508,7 +508,7 @@ fn cached_dynamic_global_variable_value(
let Some(hops) = global_environment_hops(cache.get().get()) else {
return Ok(None);
};
- let identifier = &cache.executable.identifier_table[identifier_index.0 as usize];
+ let identifier = &cache.executable.identifier_table()[identifier_index.0 as usize];
if is_global_environment_at_hops(vm, current_environment, hops, identifier) {
let global_variable_cache = cache.executable.dynamic_global_variable_cache(cache.index);
if let Some(value) = global_variable_value(vm, identifier_index, global_variable_cache, strict)? {
diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs
index ecb19cc7458..49e72e6e94e 100644
--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs
@@ -76,7 +76,7 @@ fn caller_mode_of(strict: Strict) -> CallerMode {
/// Executable::get_string().
fn get_string(vm: &Vm, index: StringTableIndex) -> Utf16FlyString {
- vm.current_executable().string_table[index.0 as usize].clone()
+ vm.current_executable().string_table()[index.0 as usize].clone()
}
/// Value::as_array_exotic_object(): the arguments the bytecode collected into an Array for a call.
@@ -130,13 +130,17 @@ fn internal_construct(
}
/// What FunctionObject::get_stack_frame_info() reports for a call of `function` with `argument_count` arguments.
-fn stack_frame_info_for_call(vm: &Vm, function: Gc<FunctionObject>, argument_count: u32) -> StackFrameInfo {
+fn stack_frame_info_for_call(
+ vm: &Vm,
+ function: Gc<FunctionObject>,
+ argument_count: u32,
+) -> ThrowCompletionOr<StackFrameInfo> {
let mut stack_frame_info = StackFrameInfo {
argument_count,
..Default::default()
};
- function.get_stack_frame_info(vm, &mut stack_frame_info);
- stack_frame_info
+ function.get_stack_frame_info(vm, &mut stack_frame_info)?;
+ Ok(stack_frame_info)
}
fn argument_count_of(count: usize) -> u32 {
@@ -257,6 +261,14 @@ fn throw_type_error_for_asm_callee(
);
}
+ let program_counter = vm.running_execution_context_ref().program_counter.get();
+ if let Some(text) = vm.current_executable().callee_text_at(program_counter) {
+ return vm.throw_completion(
+ ErrorKind::TypeError,
+ ErrorType::IsNotAEvaluatedFrom,
+ &[&callee, &callee_type, &text],
+ );
+ }
vm.throw_completion(ErrorKind::TypeError, ErrorType::IsNotA, &[&callee, &callee_type])
}
@@ -321,7 +333,7 @@ pub(crate) fn execute_asm_call(
let function = callee.as_function();
let argument_count = argument_count_of(arguments.len());
- let stack_frame_info = stack_frame_info_for_call(vm, function, argument_count);
+ let stack_frame_info = stack_frame_info_for_call(vm, function, argument_count)?;
let stack = vm.interpreter_stack();
let stack_mark = stack.top.get();
@@ -436,7 +448,7 @@ fn call_direct_eval_impl(
let function = callee.as_function();
let argument_count = argument_count_of(arguments.len());
- let stack_frame_info = stack_frame_info_for_call(vm, function, argument_count);
+ let stack_frame_info = stack_frame_info_for_call(vm, function, argument_count)?;
let stack = vm.interpreter_stack();
let stack_mark = stack.top.get();
@@ -508,7 +520,7 @@ fn call_with_argument_array_impl(
let argument_array = as_array_exotic_object(arguments);
let argument_array_length = argument_array.indexed_array_like_size();
- let stack_frame_info = stack_frame_info_for_call(vm, function, argument_array_length);
+ let stack_frame_info = stack_frame_info_for_call(vm, function, argument_array_length)?;
let stack = vm.interpreter_stack();
let stack_mark = stack.top.get();
@@ -721,7 +733,7 @@ pub fn super_call_with_argument_array(
};
let argument_array_length = u32::try_from(argument_array_length).expect("the argument count fits in u32");
- let stack_frame_info = stack_frame_info_for_call(vm, function, argument_array_length);
+ let stack_frame_info = asm_try!(vm, pc, stack_frame_info_for_call(vm, function, argument_array_length));
let stack = vm.interpreter_stack();
let stack_mark = stack.top.get();
diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs
index 429cfe27eaa..b9db8b734b8 100644
--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs
@@ -8,8 +8,9 @@
use ak::{Utf16FlyString, Utf16String};
+use crate::bytecode::codegen::DisposableResourceKind;
+use crate::bytecode::codegen::stream::Finally;
use crate::bytecode::executable::StaticPropertyLookupCacheSite;
-use crate::bytecode::generator::{DisposableResourceKind, FinallyContext};
use crate::bytecode::op;
use crate::debugger::PauseReason;
use crate::interpreter::runtime_functions::{SlowPathControl, asm_try, handle_asm_exception};
@@ -664,7 +665,7 @@ pub fn add_disposable_resource(
/// completion if its type is the throw type of a finally context, and a normal one otherwise. The resources are
/// disposed of the same way for every other type.
fn completion_of_scope(completion_type: Value, completion_value: Value) -> Completion {
- if completion_type.is_int32() && completion_type.as_i32() == FinallyContext::THROW {
+ if completion_type.is_int32() && completion_type.as_i32() == Finally::THROW {
Completion::new(CompletionType::Throw, completion_value)
} else {
Completion::normal(Value::UNDEFINED)
diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/property_access.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/property_access.rs
index 56d9732c505..ffce9dfbcd0 100644
--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/property_access.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/property_access.rs
@@ -68,7 +68,10 @@ fn is_non_negative_int32(value: Value) -> bool {
}
fn optional_identifier(vm: &Vm, index: &OptionalIndex<IdentifierTableIndex>) -> Option<Utf16FlyString> {
- let index = index.get()?;
+ let Some(index) = index.get() else {
+ let program_counter = vm.running_execution_context_ref().program_counter.get();
+ return vm.current_executable().base_text_at(program_counter);
+ };
Some(vm.current_executable().get_identifier(index).clone())
}
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rs
index ff8768de042..e26b918c40b 100644
--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs
@@ -852,6 +852,11 @@ impl Vm {
current < self.head.native_stack_limit.get()
}
+ /// The address below which did_reach_stack_space_limit().
+ pub fn native_stack_limit(&self) -> usize {
+ self.head.native_stack_limit.get()
+ }
+
pub fn push_execution_context(&self, context: NonNull<ExecutionContext>) {
// SAFETY: The caller passes a live context.
let context_ref = unsafe { context.as_ref() };
diff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rs
index bb947bd5d6d..3189b7d2622 100644
--- a/Libraries/LibJS/Rust/src/jit/code.rs
+++ b/Libraries/LibJS/Rust/src/jit/code.rs
@@ -511,25 +511,6 @@ impl Executable {
self.head.jit_compile_state.set(state as u8);
}
- /// Whether the executable has JIT code, or a compile on its way, which is tied to the executable.
- pub fn has_jit_code_or_compile(&self) -> bool {
- matches!(
- self.jit_compile_state(),
- CompileState::Queued | CompileState::Installed | CompileState::Discarding
- )
- }
-
- /// Makes the executable never compile, with the tier and the tier-up budget of `other`, if `other` was refused,
- /// as replacing an executable with one of the same bytecode does not change whether it can compile.
- pub fn take_over_jit_refusal_from(&self, other: &Executable) {
- if other.jit_compile_state() != CompileState::Refused {
- return;
- }
- self.set_jit_compile_state(CompileState::Refused);
- self.set_interpreter_tier(other.interpreter_tier());
- self.head.tier_up_budget.set(other.head.tier_up_budget.get());
- }
-
/// The executable's slot in the JIT entry table of `vm`, the VM whose heap the executable lives in, and the table,
/// if it has one.
fn jit_entry_table_slot<'vm>(&self, vm: &'vm Vm) -> Option<(&'vm JitEntryTable, u32)> {
diff --git a/Libraries/LibJS/Rust/src/jit/disabled.rs b/Libraries/LibJS/Rust/src/jit/disabled.rs
index fce35264a76..81f2dc2b975 100644
--- a/Libraries/LibJS/Rust/src/jit/disabled.rs
+++ b/Libraries/LibJS/Rust/src/jit/disabled.rs
@@ -113,12 +113,6 @@ pub mod code {
CompileState::None
}
- pub fn has_jit_code_or_compile(&self) -> bool {
- false
- }
-
- pub fn take_over_jit_refusal_from(&self, _other: &Executable) {}
-
pub fn discard_jit_code(&self, _vm: &Vm) {
unreachable!("no executable has JIT code");
}
diff --git a/Libraries/LibJS/Rust/src/jit/mod.rs b/Libraries/LibJS/Rust/src/jit/mod.rs
index b953a6b3524..adcf559b5b7 100644
--- a/Libraries/LibJS/Rust/src/jit/mod.rs
+++ b/Libraries/LibJS/Rust/src/jit/mod.rs
@@ -477,7 +477,7 @@ pub fn describe_executable(executable: &Executable) -> String {
} else {
name
};
- let Some(entry) = executable.source_map.iter().find(|entry| entry.line != 0) else {
+ let Some(entry) = executable.source_positions().find(|entry| entry.line != 0) else {
return name;
};
let filename = executable.source_code().map_or(String::new(), |source_code| {
diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rs
index cae25cb8848..b67eaf587e2 100644
--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs
+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs
@@ -1029,7 +1029,7 @@ impl SnapshotBuilder<'_> {
},
constants: executable.constants().iter().map(|constant| constant.0).collect(),
exception_handlers: executable
- .exception_handlers
+ .exception_handlers()
.iter()
.map(|handler| ExceptionHandler {
start_offset: handler.start_offset,
@@ -1100,7 +1100,7 @@ impl SnapshotBuilder<'_> {
// NB: Only the compiled function's own code creates bindings by name.
identifiers: if entry.function.is_none() {
executable
- .identifier_table
+ .identifier_table()
.iter()
.map(|identifier| identifier.raw_identity() as u64)
.collect()
diff --git a/Libraries/LibJS/Rust/src/jit/testing.rs b/Libraries/LibJS/Rust/src/jit/testing.rs
index bc4d7c0bd61..c692b10bd8e 100644
--- a/Libraries/LibJS/Rust/src/jit/testing.rs
+++ b/Libraries/LibJS/Rust/src/jit/testing.rs
@@ -103,7 +103,7 @@ fn prepare(vm: &Vm) -> ThrowCompletionOr<Value> {
if !vm.jit.options.collects_feedback() {
return Ok(Value::UNDEFINED);
}
- let executable = function.compiled_executable(vm);
+ let executable = function.compiled_executable(vm)?;
if executable.jit_compile_state() == CompileState::Refused {
return Ok(Value::UNDEFINED);
}
@@ -150,7 +150,7 @@ fn never_compile(vm: &Vm) -> ThrowCompletionOr<Value> {
if !vm.jit.options.collects_feedback() {
return Ok(Value::UNDEFINED);
}
- let executable = function.compiled_executable(vm);
+ let executable = function.compiled_executable(vm)?;
tier_up::wait_for_compile_job(vm, &executable);
if executable.jit_compile_state() == CompileState::Installed {
executable.discard_jit_code(vm);
diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rs
index 68bdc950911..15a142f3bae 100644
--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs
+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs
@@ -518,7 +518,9 @@ pub fn compile_now(vm: &Vm, function: Gc<EcmascriptFunctionObject>) -> bool {
if !vm.jit.options.enabled || vm.debugging_enabled() {
return false;
}
- let executable = function.compiled_executable(vm);
+ let Ok(executable) = function.compiled_executable(vm) else {
+ return false;
+ };
wait_for_compile_job(vm, &executable);
if executable.jit_compile_state() == CompileState::Discarding {
executable.detach_discarded_jit_code_if_unused(vm);
diff --git a/Libraries/LibJS/Rust/src/lexer.rs b/Libraries/LibJS/Rust/src/lexer.rs
index 78f00668df0..250b2968e64 100644
--- a/Libraries/LibJS/Rust/src/lexer.rs
+++ b/Libraries/LibJS/Rust/src/lexer.rs
@@ -34,10 +34,11 @@
//! type, because escaped keywords have different semantics (they can be
//! used as identifiers in some contexts).
-use crate::ast::Utf16String;
use crate::token::Token;
use crate::token::TokenType;
use crate::u32_from_usize;
+use crate::utf16::Utf16View;
+use ak::Utf16String;
/// State for tracking template literal nesting.
#[derive(Clone)]
@@ -46,19 +47,8 @@ struct TemplateState {
open_bracket_count: u32,
}
-/// Saved lexer state for lookahead and backtracking.
-pub(crate) struct SavedLexerState {
- position: usize,
- current_code_unit: u16,
- eof: bool,
- line_number: u32,
- line_column: u32,
- current_token_type: TokenType,
- template_states: Vec<TemplateState>,
-}
-
pub struct Lexer<'a> {
- source: &'a [u16],
+ source: Utf16View<'a>,
/// 1-based index into `source`: always one past `current_code_unit`.
/// Subtract 1 to get the 0-based index of the current code unit.
position: usize,
@@ -68,9 +58,7 @@ pub struct Lexer<'a> {
line_column: u32,
current_token_type: TokenType,
regex_is_in_character_class: bool,
- allow_html_comments: bool,
template_states: Vec<TemplateState>,
- saved_states: Vec<SavedLexerState>,
}
// Unicode constants used by the lexical grammar.
@@ -122,14 +110,15 @@ fn is_utf16_low_surrogate(cu: u16) -> bool {
/// Decode a code point from a UTF-16 slice starting at `pos`.
/// Returns (code_point, number_of_code_units_consumed).
-fn decode_code_point(source: &[u16], pos: usize) -> (u32, usize) {
- if pos >= source.len() {
+fn decode_code_point(source: Utf16View<'_>, pos: usize) -> (u32, usize) {
+ let length = source.length_in_code_units();
+ if pos >= length {
return (0xFFFD, 1);
}
- let cu = source[pos];
- if is_utf16_high_surrogate(cu) && pos + 1 < source.len() && is_utf16_low_surrogate(source[pos + 1]) {
+ let cu = source.code_unit_at(pos);
+ if is_utf16_high_surrogate(cu) && pos + 1 < length && is_utf16_low_surrogate(source.code_unit_at(pos + 1)) {
let hi = cu as u32;
- let lo = source[pos + 1] as u32;
+ let lo = source.code_unit_at(pos + 1) as u32;
let cp = 0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00);
(cp, 2)
} else {
@@ -396,7 +385,7 @@ fn parse_three_char_token(ch0: u16, ch1: u16, ch2: u16) -> TokenType {
}
impl<'a> Lexer<'a> {
- pub fn new(source: &'a [u16], line_number: u32, line_column: u32) -> Self {
+ pub fn new(source: Utf16View<'a>, line_number: u32, line_column: u32) -> Self {
let mut lexer = Lexer {
source,
position: 0,
@@ -406,30 +395,7 @@ impl<'a> Lexer<'a> {
line_column,
current_token_type: TokenType::Eof,
regex_is_in_character_class: false,
- allow_html_comments: true,
- template_states: Vec::new(),
- saved_states: Vec::new(),
- };
- lexer.consume();
- lexer
- }
-
- pub fn new_at_offset(source: &'a [u16], offset: usize, line_number: u32, line_column: u32) -> Self {
- let mut lexer = Lexer {
- source,
- position: offset,
- current_code_unit: 0,
- eof: false,
- line_number,
- // consume() below will bump line_column by one; pre-decrement so
- // the post-consume state has line_column equal to the column of
- // the character at `offset`.
- line_column: line_column.saturating_sub(1),
- current_token_type: TokenType::Eof,
- regex_is_in_character_class: false,
- allow_html_comments: true,
template_states: Vec::new(),
- saved_states: Vec::new(),
};
lexer.consume();
lexer
@@ -445,14 +411,8 @@ impl<'a> Lexer<'a> {
.expect("template_states must not be empty")
}
- // https://tc39.es/ecma262/#sec-html-like-comments
- // HTML-like comments are only recognized in Script (not Module) code.
- pub fn disallow_html_comments(&mut self) {
- self.allow_html_comments = false;
- }
-
fn source_len(&self) -> usize {
- self.source.len()
+ self.source.length_in_code_units()
}
fn consume(&mut self) {
@@ -469,8 +429,9 @@ impl<'a> Lexer<'a> {
}
if self.is_line_terminator() {
- let second_char_of_crlf =
- self.position > 1 && self.source[self.position - 2] == ch(b'\r') && self.current_code_unit == ch(b'\n');
+ let second_char_of_crlf = self.position > 1
+ && self.source.code_unit_at(self.position - 2) == ch(b'\r')
+ && self.current_code_unit == ch(b'\n');
if !second_char_of_crlf {
self.line_number += 1;
@@ -479,7 +440,7 @@ impl<'a> Lexer<'a> {
} else {
if is_utf16_high_surrogate(self.current_code_unit)
&& self.position < self.source_len()
- && is_utf16_low_surrogate(self.source[self.position])
+ && is_utf16_low_surrogate(self.source.code_unit_at(self.position))
{
self.position += 1;
if self.position >= self.source_len() {
@@ -493,7 +454,7 @@ impl<'a> Lexer<'a> {
self.line_column += 1;
}
- self.current_code_unit = self.source[self.position];
+ self.current_code_unit = self.source.code_unit_at(self.position);
self.position += 1;
}
@@ -550,7 +511,7 @@ impl<'a> Lexer<'a> {
if pos >= self.source_len() {
return None;
}
- if self.source[pos] != ch(b'u') {
+ if self.source.code_unit_at(pos) != ch(b'u') {
return None;
}
let pos = pos + 1;
@@ -558,14 +519,14 @@ impl<'a> Lexer<'a> {
return None;
}
- if self.source[pos] == ch(b'{') {
+ if self.source.code_unit_at(pos) == ch(b'{') {
let mut cp: u32 = 0;
let mut i = pos + 1;
if i >= self.source_len() {
return None;
}
- while i < self.source_len() && self.source[i] != ch(b'}') {
- let cu = self.source[i];
+ while i < self.source_len() && self.source.code_unit_at(i) != ch(b'}') {
+ let cu = self.source.code_unit_at(i);
if !is_ascii_hex_digit(cu) {
return None;
}
@@ -575,7 +536,7 @@ impl<'a> Lexer<'a> {
}
i += 1;
}
- if i >= self.source_len() || self.source[i] != ch(b'}') {
+ if i >= self.source_len() || self.source.code_unit_at(i) != ch(b'}') {
return None;
}
let consumed = i + 1 - (self.position - 1);
@@ -586,7 +547,7 @@ impl<'a> Lexer<'a> {
}
let mut cp: u32 = 0;
for i in 0..4 {
- let cu = self.source[pos + i];
+ let cu = self.source.code_unit_at(pos + i);
if !is_ascii_hex_digit(cu) {
return None;
}
@@ -631,9 +592,13 @@ impl<'a> Lexer<'a> {
/// Re-scan the source from `scan_start` (1-based position) to `self.position`
/// and build a decoded identifier value. Only called when escapes are present.
- fn build_identifier_value(&self, scan_start: usize) -> Utf16String {
- let raw = &self.source[scan_start - 1..self.position - 1];
- let mut result = Utf16String(Vec::with_capacity(raw.len()));
+ fn build_identifier_value(&self, scan_start: usize) -> Vec<u16> {
+ let raw: Vec<u16> = self
+ .source
+ .substring_view(scan_start - 1, self.position - scan_start)
+ .code_units()
+ .collect();
+ let mut result = Vec::with_capacity(raw.len());
let mut i = 0;
while i < raw.len() {
if raw[i] == ch(b'\\') {
@@ -650,7 +615,7 @@ impl<'a> Lexer<'a> {
if i < raw.len() {
i += 1; // skip '}'
}
- encode_utf16(cp, &mut result.0);
+ encode_utf16(cp, &mut result);
} else {
let mut cp: u32 = 0;
for _ in 0..4 {
@@ -659,11 +624,11 @@ impl<'a> Lexer<'a> {
i += 1;
}
}
- encode_utf16(cp, &mut result.0);
+ encode_utf16(cp, &mut result);
}
}
} else {
- result.0.push(raw[i]);
+ result.push(raw[i]);
i += 1;
}
}
@@ -716,14 +681,16 @@ impl<'a> Lexer<'a> {
if self.position >= self.source_len() {
return false;
}
- self.current_code_unit == a && self.source[self.position] == b
+ self.current_code_unit == a && self.source.code_unit_at(self.position) == b
}
fn match3(&self, a: u16, b: u16, c: u16) -> bool {
if self.position + 1 >= self.source_len() {
return false;
}
- self.current_code_unit == a && self.source[self.position] == b && self.source[self.position + 1] == c
+ self.current_code_unit == a
+ && self.source.code_unit_at(self.position) == b
+ && self.source.code_unit_at(self.position + 1) == c
}
fn match4(&self, a: u16, b: u16, c: u16, d: u16) -> bool {
@@ -731,16 +698,16 @@ impl<'a> Lexer<'a> {
return false;
}
self.current_code_unit == a
- && self.source[self.position] == b
- && self.source[self.position + 1] == c
- && self.source[self.position + 2] == d
+ && self.source.code_unit_at(self.position) == b
+ && self.source.code_unit_at(self.position + 1) == c
+ && self.source.code_unit_at(self.position + 2) == d
}
fn match_numeric_literal_separator_followed_by(&self, check: fn(u16) -> bool) -> bool {
if self.position >= self.source_len() {
return false;
}
- self.current_code_unit == ch(b'_') && check(self.source[self.position])
+ self.current_code_unit == ch(b'_') && check(self.source.code_unit_at(self.position))
}
// https://tc39.es/ecma262/#sec-comments
@@ -755,8 +722,8 @@ impl<'a> Lexer<'a> {
// HashbangComment :: `#!` SingleLineCommentChars?
fn is_line_comment_start(&self, line_has_token_yet: bool) -> bool {
self.match2(ch(b'/'), ch(b'/'))
- || (self.allow_html_comments && self.match4(ch(b'<'), ch(b'!'), ch(b'-'), ch(b'-')))
- || (self.allow_html_comments && !line_has_token_yet && self.match3(ch(b'-'), ch(b'-'), ch(b'>')))
+ || (self.match4(ch(b'<'), ch(b'!'), ch(b'-'), ch(b'-')))
+ || (!line_has_token_yet && self.match3(ch(b'-'), ch(b'-'), ch(b'>')))
|| (self.match2(ch(b'#'), ch(b'!')) && self.position == 1)
}
@@ -772,7 +739,7 @@ impl<'a> Lexer<'a> {
is_ascii_digit(self.current_code_unit)
|| (self.current_code_unit == ch(b'.')
&& self.position < self.source_len()
- && is_ascii_digit(self.source[self.position]))
+ && is_ascii_digit(self.source.code_unit_at(self.position)))
}
// https://tc39.es/ecma262/#sec-lexical-and-regexp-grammars
@@ -1035,7 +1002,7 @@ impl<'a> Lexer<'a> {
let has_escape = self.scan_identifier_body(len);
if has_escape {
let decoded = self.build_identifier_value(value_start);
- identifier_value = Some(decoded);
+ identifier_value = Some(Utf16String::from_utf16(&decoded));
}
token_type = TokenType::PrivateIdentifier;
} else {
@@ -1056,10 +1023,13 @@ impl<'a> Lexer<'a> {
} else {
token_type = TokenType::Identifier;
}
- identifier_value = Some(decoded);
+ identifier_value = Some(Utf16String::from_utf16(&decoded));
} else {
- let source_slice = &self.source[value_start - 1..self.position - 1];
- if let Some(kw) = keyword_from_str(source_slice) {
+ let keyword = self
+ .source
+ .substring_view(value_start - 1, self.position - value_start)
+ .with_utf16_code_units(keyword_from_str);
+ if let Some(kw) = keyword {
token_type = kw;
} else {
token_type = TokenType::Identifier;
@@ -1144,7 +1114,7 @@ impl<'a> Lexer<'a> {
self.consume();
if self.current_code_unit == ch(b'\r')
&& self.position < self.source_len()
- && self.source[self.position] == ch(b'\n')
+ && self.source.code_unit_at(self.position) == ch(b'\n')
{
self.consume();
}
@@ -1181,8 +1151,8 @@ impl<'a> Lexer<'a> {
if !found_token && self.position + 1 < self.source_len() {
let ch0 = self.current_code_unit;
- let ch1 = self.source[self.position];
- let ch2 = self.source[self.position + 1];
+ let ch1 = self.source.code_unit_at(self.position);
+ let ch2 = self.source.code_unit_at(self.position + 1);
let tt = parse_three_char_token(ch0, ch1, ch2);
if tt != TokenType::Invalid {
found_token = true;
@@ -1195,7 +1165,7 @@ impl<'a> Lexer<'a> {
if !found_token && self.position < self.source_len() {
let ch0 = self.current_code_unit;
- let ch1 = self.source[self.position];
+ let ch1 = self.source.code_unit_at(self.position);
let tt = parse_two_char_token(ch0, ch1);
if tt != TokenType::Invalid {
// https://tc39.es/ecma262/#sec-punctuators
@@ -1203,7 +1173,7 @@ impl<'a> Lexer<'a> {
// This prevents `a?.3:b` from being parsed as optional chaining.
if !(tt == TokenType::QuestionMarkPeriod
&& self.position + 1 < self.source_len()
- && is_ascii_digit(self.source[self.position + 1]))
+ && is_ascii_digit(self.source.code_unit_at(self.position + 1)))
{
found_token = true;
token_type = tt;
@@ -1240,9 +1210,10 @@ impl<'a> Lexer<'a> {
self.current_token_type = token_type;
let trivia_has_line_terminator = if trivia_start > 0 && value_start > trivia_start {
- self.source[trivia_start - 1..value_start - 1]
- .iter()
- .any(|&cu| cu == ch(b'\n') || cu == ch(b'\r') || cu == LINE_SEPARATOR || cu == PARAGRAPH_SEPARATOR)
+ self.source
+ .substring_view(trivia_start - 1, value_start - trivia_start)
+ .code_units()
+ .any(|cu| cu == ch(b'\n') || cu == ch(b'\r') || cu == LINE_SEPARATOR || cu == PARAGRAPH_SEPARATOR)
} else {
false
};
@@ -1261,96 +1232,6 @@ impl<'a> Lexer<'a> {
message: token_message,
}
}
-
- // === State accessors for parser save/restore ===
-
- pub fn position(&self) -> usize {
- self.position
- }
-
- pub fn line_number(&self) -> u32 {
- self.line_number
- }
-
- pub fn line_column(&self) -> u32 {
- self.line_column
- }
-
- pub fn restore(&mut self, position: usize, line_number: u32, line_column: u32) {
- self.position = position;
- self.line_number = line_number;
- self.line_column = line_column;
- self.eof = position > self.source_len();
- // position is one past current_code_unit, so restore from position - 1
- if position > 0 && position <= self.source_len() {
- self.current_code_unit = self.source[position - 1];
- } else {
- self.current_code_unit = 0;
- }
- }
-
- pub fn save_state(&mut self) {
- self.saved_states.push(SavedLexerState {
- position: self.position,
- current_code_unit: self.current_code_unit,
- eof: self.eof,
- line_number: self.line_number,
- line_column: self.line_column,
- current_token_type: self.current_token_type,
- template_states: self.template_states.clone(),
- });
- }
-
- pub fn load_state(&mut self) {
- let state = self.saved_states.pop().expect("No saved lexer state");
- self.position = state.position;
- self.current_code_unit = state.current_code_unit;
- self.eof = state.eof;
- self.line_number = state.line_number;
- self.line_column = state.line_column;
- self.current_token_type = state.current_token_type;
- self.template_states = state.template_states;
- }
-
- pub fn discard_saved_state(&mut self) {
- self.saved_states.pop();
- }
-
- /// Re-lex the current Slash or SlashEquals token as a regex literal.
- pub fn force_slash_as_regex(&mut self) -> Token {
- let has_equals = self.current_token_type == TokenType::SlashEquals;
-
- assert!(self.position > 0);
- let mut value_start = self.position - 1;
-
- // Capture line position at the start of the '/' token, before consuming the regex body.
- let token_line_number = self.line_number;
- let mut token_line_column = self.line_column.saturating_sub(1);
-
- if has_equals {
- value_start -= 1;
- self.position -= 1;
- self.current_code_unit = ch(b'=');
- token_line_column = token_line_column.saturating_sub(1);
- }
-
- let token_type = self.consume_regex_literal();
- self.current_token_type = token_type;
-
- Token {
- token_type,
- trivia_start: 0,
- trivia_len: 0,
- value_start: u32_from_usize(value_start.saturating_sub(1)),
- value_len: u32_from_usize(self.position - value_start),
- line_number: token_line_number,
- line_column: token_line_column,
- offset: u32_from_usize(value_start.saturating_sub(1)),
- trivia_has_line_terminator: false,
- identifier_value: None,
- message: None,
- }
- }
}
fn hex_value(cu: u16) -> u32 {
diff --git a/Libraries/LibJS/Rust/src/lib.rs b/Libraries/LibJS/Rust/src/lib.rs
index 7df243ebe18..78f50573139 100644
--- a/Libraries/LibJS/Rust/src/lib.rs
+++ b/Libraries/LibJS/Rust/src/lib.rs
@@ -6,31 +6,25 @@
//! # LibJS
//!
-//! LibJS's frontend and runtime. The frontend parses JavaScript into an AST and compiles it to bytecode, which the
+//! LibJS's frontend and runtime. The frontend parses JavaScript into a syntax tree and compiles it to bytecode, which the
//! runtime runs in the Flap-generated interpreter, on cells allocated from LibGC.
//!
//! ## Architecture
//!
//! ```text
-//! Source code (UTF-16)
+//! Source code (Latin-1 or UTF-16)
//! │
//! ▼
//! ┌─────────────────────────────────────────────────────┐
-//! │ Lexer (lexer.rs) │
-//! │ Tokenizes UTF-16 source into Token stream │
+//! │ Parser (parser/) │
+//! │ Lexes and parses into flat columns, analyzes │
+//! │ scopes, and resolves identifiers │
//! └──────────────────────┬──────────────────────────────┘
-//! │ tokens
+//! │ syntax tree (ast.rs)
//! ▼
//! ┌─────────────────────────────────────────────────────┐
-//! │ Parser (parser.rs + parser/*.rs) │
-//! │ Recursive descent with precedence climbing │
-//! │ Builds AST (ast.rs) │
-//! └──────────────────────┬──────────────────────────────┘
-//! │ AST
-//! ▼
-//! ┌─────────────────────────────────────────────────────┐
-//! │ Codegen (bytecode/codegen.rs) │
-//! │ Walks AST, emits bytecode via Generator │
+//! │ Codegen (bytecode/codegen/) │
+//! │ Sweeps the rows of the tree, emits bytecode │
//! └──────────────────────┬──────────────────────────────┘
//! │ assembled bytecode
//! ▼
@@ -46,16 +40,11 @@
//! - `host.rs` — Functions every embedding runtime provides to the frontend
//! - `token.rs` — Token types
//! - `tokenize.rs` — Tokens of a source without parsing it, for syntax highlighting
-//! - `lexer.rs` — Tokenizer: UTF-16 input → Token stream
-//! - `parser.rs` — Parser state, helpers, token consumption
-//! - `parser/expressions.rs` — Expression parsing (precedence climbing)
-//! - `parser/statements.rs` — Statement parsing (if, for, while, etc.)
-//! - `parser/declarations.rs` — Functions, classes, variables, modules
-//! - `ast.rs` — AST type definitions
+//! - `lexer.rs` — Tokenizer: UTF-16 input → Token stream, for tokenize.rs
+//! - `parser/` — The parser, the columns of its syntax tree, scope analysis and identifier resolution
+//! - `ast.rs` — The syntax tree and the typed views that everything after the parser reads it through
//! - `bytecode/` — Bytecode generator, instruction types, and dumper
-//! - `bytecode_cache.rs` — Serialization of compiled programs for the bytecode cache
//! - `breakpoint_positions.rs` — Where in a source a debugger can stop
-//! - `scope_collector.rs` — Scope analysis
//! - `interpreter/`, `runtime/`, `gc/`, `layout/`, `embedding/` — The runtime and its embedding ABI
#[cfg(feature = "allocator")]
@@ -99,10 +88,8 @@ pub mod ast_dump;
#[cfg(not(test))]
pub mod breakpoint;
pub mod breakpoint_positions;
-#[cfg(not(test))]
pub mod build_configuration;
pub mod bytecode;
-pub mod bytecode_cache;
pub mod compile;
#[cfg(not(test))]
pub mod console;
@@ -146,14 +133,13 @@ mod layout_forward;
pub mod lexer;
#[cfg(not(test))]
pub mod lexical_path;
+#[path = "parser/mod.rs"]
pub mod parser;
-#[cfg(not(test))]
pub mod parser_error;
#[cfg(not(test))]
pub mod random;
#[cfg(not(test))]
pub mod runtime;
-pub mod scope_collector;
#[cfg(not(test))]
pub mod script;
#[cfg(not(test))]
@@ -168,7 +154,6 @@ pub mod token;
pub mod tokenize;
#[cfg(not(test))]
pub mod unicode;
-#[cfg(not(test))]
pub mod utf16;
#[cfg(not(test))]
pub mod utilities;
diff --git a/Libraries/LibJS/Rust/src/parser/mod.rs b/Libraries/LibJS/Rust/src/parser/mod.rs
new file mode 100644
index 00000000000..43aabcff1c5
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/parser/mod.rs
@@ -0,0 +1,651 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The JavaScript parser. Lexing is driven by the parser, the syntax tree is a set of flat columns, and scope analysis
+//! happens while parsing, with no map per scope. [`crate::ast`] is how everything after the parser reads the tree.
+//!
+//! A source is parsed once for all of its early errors. That leaves a [`ScriptData`], which is all that is kept of the
+//! source, and the tree of its top-level code. A function is parsed again on its own when it is first called. Its tree
+//! lives as long as the compile job that needs it, and nested functions are skipped by what the first parse recorded.
+
+pub(crate) mod base;
+pub(crate) mod columns;
+pub(crate) mod expr;
+mod intern;
+mod lexer;
+pub(crate) mod literals;
+pub(crate) mod resolve;
+mod stmt;
+pub(crate) mod token;
+pub(crate) mod unit;
+
+use crate::ast::Name;
+use crate::ast::NameTable;
+use crate::ast::Position;
+use crate::ast::ProgramType;
+use crate::ast::Resolution;
+use crate::ast::ScopeTable;
+use crate::ast::SyntaxTree;
+use crate::u32_from_usize;
+use base::Mode;
+use base::Parser;
+use columns::Ast;
+use columns::FunctionIndex;
+use columns::function_flag;
+use core::sync::atomic::AtomicUsize;
+use core::sync::atomic::Ordering;
+use intern::Interner;
+pub(crate) use resolve::EnclosingCode;
+pub(crate) use resolve::OuterResolutions;
+use std::cell::Cell;
+use std::sync::Arc;
+use std::sync::Mutex;
+use unit::Unit;
+
+/// How many zero code units the lexer needs after the source.
+const SOURCE_PADDING: usize = 64;
+
+/// A function of a source, as the row that the first parse of the source gave it.
+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
+pub struct FunctionRow(pub(crate) u32);
+
+/// A parser that keeps reparsing the functions of one source: it knows the names of the source.
+enum ReparseContext {
+ Narrow(Box<Parser<'static, u8>>),
+ Wide(Box<Parser<'static, u16>>),
+}
+
+// SAFETY: The parser of a context only points at what the ScriptData holding the context owns, or, during a reparse, into
+// the memory of that reparse.
+unsafe impl Send for ReparseContext {}
+
+/// All that is kept of a source once it is parsed: the source, one row for each of its functions, and the names that the
+/// rows speak of. Compile jobs on any thread parse the functions again from this.
+pub struct ScriptData {
+ pub(crate) index: FunctionIndex,
+ pub(crate) names: NameTable,
+ pub(crate) positions: Arc<SourcePositions>,
+ pub(crate) program_type: ProgramType,
+ pub(crate) program_context: base::ProgramContext,
+ /// The rows of the top level with marks, or that they did not fit the stack, until the compile of the top level.
+ top_level_rows: Mutex<Option<TopLevelRows>>,
+ pub(crate) default_export_name: Name,
+ pub(crate) default_constructor_parameter_name: Name,
+ /// The undeclared names that something in a `with` uses, which are not simply globals, sorted.
+ global_names_used_in_with: Vec<u32>,
+ /// Filled in when the first function gets parsed again, for the ones after it.
+ reparse_context: Mutex<Option<ReparseContext>>,
+}
+
+/// The memory of the tree of a function that a compile job is done with, for the next one on the thread.
+struct SpareTreeMemory {
+ ast: Ast,
+ resolutions: Vec<Resolution>,
+ scopes: ScopeTable,
+ function_scope_rows: Vec<(u32, u32)>,
+}
+
+/// The most nodes of a tree whose memory stays around.
+const MAXIMUM_SPARE_NODES: usize = 1 << 16;
+
+thread_local! {
+ static SPARE_TREE_MEMORY: Cell<Option<SpareTreeMemory>> = const { Cell::new(None) };
+}
+
+impl SyntaxTree {
+ /// Leaves the memory of this tree, which is one of a function, to the next one parsed on the thread.
+ pub(crate) fn give_back_memory(self) {
+ if self.ast.tag.capacity() > MAXIMUM_SPARE_NODES {
+ return;
+ }
+ let Self {
+ mut ast,
+ mut resolutions,
+ mut scopes,
+ mut function_scope_rows,
+ ..
+ } = self;
+ ast.reset();
+ resolutions.clear();
+ scopes.clear();
+ function_scope_rows.clear();
+ SPARE_TREE_MEMORY.set(Some(SpareTreeMemory {
+ ast,
+ resolutions,
+ scopes,
+ function_scope_rows,
+ }));
+ }
+}
+
+/// A function could not be parsed or compiled, because the stack that is left does not hold it.
+#[derive(Clone, Copy, Debug)]
+pub struct OutOfStack;
+
+/// The address that the stack can only go `bytes` below where it is now.
+pub fn stack_limit_for_budget(bytes: usize) -> usize {
+ let marker = 0u8;
+ (&raw const marker as usize).saturating_sub(bytes)
+}
+
+#[cfg(target_os = "linux")]
+fn thread_stack_lowest_address() -> Option<usize> {
+ // SAFETY: The attributes live for the calls, and are destroyed once initialized.
+ unsafe {
+ let mut attributes: libc::pthread_attr_t = std::mem::zeroed();
+ if libc::pthread_getattr_np(libc::pthread_self(), &raw mut attributes) != 0 {
+ return None;
+ }
+ let mut address = std::ptr::null_mut();
+ let mut size = 0;
+ let result = libc::pthread_attr_getstack(&raw const attributes, &raw mut address, &raw mut size);
+ libc::pthread_attr_destroy(&raw mut attributes);
+ (result == 0).then_some(address as usize)
+ }
+}
+
+#[cfg(target_os = "macos")]
+#[allow(clippy::unnecessary_wraps)] // The other platforms' versions can fail.
+fn thread_stack_lowest_address() -> Option<usize> {
+ // SAFETY: These only read the stack of the calling thread.
+ unsafe {
+ let thread = libc::pthread_self();
+ let top = libc::pthread_get_stackaddr_np(thread) as usize;
+ Some(top - libc::pthread_get_stacksize_np(thread))
+ }
+}
+
+#[cfg(not(any(target_os = "linux", target_os = "macos")))]
+fn thread_stack_lowest_address() -> Option<usize> {
+ None
+}
+
+/// How low a VM lets the stack of this thread go, or `None` if that cannot be told.
+pub(crate) fn vm_stack_limit_of_this_thread() -> Option<usize> {
+ // NB: Asking for the stack of the main thread reads /proc/self/maps on Linux, and eval parses a program every time.
+ thread_local! {
+ static LOWEST_ADDRESS: Option<usize> = thread_stack_lowest_address();
+ }
+ LOWEST_ADDRESS
+ .with(|lowest_address| *lowest_address)
+ .map(|lowest_address| lowest_address.saturating_add(crate::build_configuration::VM_STACK_SPACE_LIMIT as usize))
+}
+
+impl ScriptData {
+ /// The rows of the top level for a sweep, which the parse of the source left here for its one compile.
+ pub(crate) fn take_top_level_rows(self: &Arc<Self>) -> Result<(SyntaxTree, u32), OutOfStack> {
+ let rows = self.top_level_rows.lock().expect("nothing panics with the rows").take();
+ let (ast, node) = rows.expect("a top level compiles once")?;
+ let tree = SyntaxTree {
+ script: self.clone(),
+ ast,
+ root: node,
+ first_token_start: 0,
+ is_strict_mode: false,
+ has_top_level_await: false,
+ eval_referenced_private_names: Vec::new(),
+ resolutions: Vec::new(),
+ scopes: ScopeTable::default(),
+ program_scope_row: 0,
+ function_scope_rows: Vec::new(),
+ outer_resolutions: None,
+ };
+ Ok((tree, node))
+ }
+
+ /// Parses the function at `row` again into a tree for a sweep, which goes by the summary of the first parse: nothing
+ /// keeps track of scopes.
+ pub(crate) fn reparse_for_sweep(
+ self: &Arc<Self>,
+ row: FunctionRow,
+ stack_limit: usize,
+ ) -> Result<(SyntaxTree, u32), OutOfStack> {
+ let memory = SPARE_TREE_MEMORY.take().unwrap_or_else(|| SpareTreeMemory {
+ ast: Ast::with_capacity(256),
+ resolutions: Vec::new(),
+ scopes: ScopeTable::default(),
+ function_scope_rows: Vec::new(),
+ });
+ let (ast, node) = {
+ let mut context = self.reparse_context.lock().expect("a reparse does not panic");
+ let context = context.get_or_insert_with(|| self.make_reparse_context());
+ match (context, self.positions.source.as_units()) {
+ (
+ ReparseContext::Narrow(parser),
+ ak::Utf16StringUnits::Ascii(units) | ak::Utf16StringUnits::Latin1(units),
+ ) => {
+ parser.tracks_scopes = false;
+ parser.marks = true;
+ let result = self.reparse_code_units(parser, memory.ast, units, row, stack_limit);
+ parser.tracks_scopes = true;
+ parser.marks = false;
+ result
+ }
+ (ReparseContext::Wide(parser), ak::Utf16StringUnits::Utf16(units)) => {
+ parser.tracks_scopes = false;
+ parser.marks = true;
+ let result = self.reparse_code_units(parser, memory.ast, units, row, stack_limit);
+ parser.tracks_scopes = true;
+ parser.marks = false;
+ result
+ }
+ _ => unreachable!("the storage of a source does not change"),
+ }
+ }?;
+ let tree = SyntaxTree {
+ script: self.clone(),
+ ast,
+ root: node,
+ first_token_start: 0,
+ is_strict_mode: false,
+ has_top_level_await: false,
+ eval_referenced_private_names: Vec::new(),
+ resolutions: memory.resolutions,
+ scopes: memory.scopes,
+ program_scope_row: 0,
+ function_scope_rows: memory.function_scope_rows,
+ outer_resolutions: None,
+ };
+ Ok((tree, node))
+ }
+
+ fn make_reparse_context(&self) -> ReparseContext {
+ let module = self.program_type == ProgramType::Module;
+ let length = u32_from_usize(self.positions.source.length_in_code_units());
+ let interner = Interner::with_names(self.names.parser_names());
+ // SAFETY: The context lives in this ScriptData, whose index stays where it is, since it is shared by an Arc,
+ // and never changes.
+ unsafe {
+ match self.positions.source.as_units() {
+ ak::Utf16StringUnits::Ascii(_) | ak::Utf16StringUnits::Latin1(_) => {
+ ReparseContext::Narrow(Box::new(Parser::for_reparsing(module, interner, &self.index, length)))
+ }
+ ak::Utf16StringUnits::Utf16(_) => {
+ ReparseContext::Wide(Box::new(Parser::for_reparsing(module, interner, &self.index, length)))
+ }
+ }
+ }
+ }
+
+ /// Bytes after a function are real source, so that it can be read in place. What the lexer sees of a function that
+ /// comes too close to the end of the source for that gets copied, with the padding that the end of the source has
+ /// to have.
+ fn reparse_code_units<U: Unit + Default>(
+ &self,
+ parser: &mut Parser<'static, U>,
+ ast: Ast,
+ source: &[U],
+ row: FunctionRow,
+ stack_limit: usize,
+ ) -> Result<(Ast, u32), OutOfStack> {
+ let row_index = row.0 as usize;
+ let needs_padding = self.index.flags[row_index] & function_flag::REACHES_SOURCE_END != 0;
+ let mut tail = Vec::new();
+ // SAFETY: The source outlives the parse, and the first parse found out that the lexer stays clear of its end
+ // unless the tail is what it reads.
+ unsafe {
+ if needs_padding {
+ let first_read = self.index.params_start[row_index] as usize;
+ tail.reserve_exact(source.len() - first_read + SOURCE_PADDING);
+ tail.extend_from_slice(&source[first_read..]);
+ tail.resize(tail.capacity(), U::default());
+ parser.set_reparse_source(tail.as_ptr(), u32_from_usize(first_read), u32_from_usize(source.len()));
+ } else {
+ parser.set_reparse_source(source.as_ptr(), 0, u32_from_usize(source.len()));
+ }
+ }
+ parser.stack_limit = stack_limit;
+ parser.ast = ast;
+ let node = parser.reparse_function(row.0);
+ let error = parser.err.take();
+ let ast = std::mem::replace(&mut parser.ast, Ast::unallocated());
+ parser.finish_reparse();
+ match error {
+ None => Ok((ast, node)),
+ Some(error) => {
+ assert_eq!(
+ error.message,
+ base::RECURSION_LIMIT_MESSAGE,
+ "the first parse found no errors"
+ );
+ Err(OutOfStack)
+ }
+ }
+ }
+
+ pub(crate) fn is_global_name_used_in_with(&self, name: Name) -> bool {
+ self.global_names_used_in_with.binary_search(&name.0).is_ok()
+ }
+}
+
+pub struct ParseError {
+ pub message: String,
+ pub line: u32,
+ pub column: u32,
+}
+
+/// What code needs of its source to report positions, which it keeps for as long as it lives. That can be long after the
+/// rest of [`ScriptData`] is of no use to anything.
+pub struct SourcePositions {
+ pub(crate) source: ak::Utf16String,
+ pub(crate) lines: LineTable,
+}
+
+/// Maps source offsets to lines and columns. Lines count from the line number of the first line, and columns count
+/// code points.
+pub(crate) struct LineTable {
+ line_starts: Vec<u32>,
+ /// The offsets of the second halves of surrogate pairs.
+ low_surrogates: Vec<u32>,
+ source_length: u32,
+ /// Whether the source ends with a line terminator, which only counts as one if something follows it.
+ ends_with_lone_line_terminator: bool,
+ initial_line_number: u32,
+ /// The index of the line that the last lookup hit, since lookups tend to come in source order.
+ last_line: AtomicUsize,
+}
+
+impl LineTable {
+ fn new<U: Unit>(source: &[U], initial_line_number: u32) -> Self {
+ let mut line_starts = vec![0];
+ let mut low_surrogates = Vec::new();
+ let mut ends_with_lone_line_terminator = false;
+ let mut index = 0;
+ while index < source.len() {
+ let code_unit = source[index].code();
+ index += 1;
+ ends_with_lone_line_terminator = false;
+ if code_unit == 0x0D && source.get(index).is_some_and(|next| next.code() == 0x0A) {
+ index += 1;
+ line_starts.push(u32_from_usize(index));
+ } else if matches!(code_unit, 0x0A | 0x0D | 0x2028 | 0x2029) {
+ line_starts.push(u32_from_usize(index));
+ ends_with_lone_line_terminator = true;
+ } else if U::WIDE
+ && (0xD800..0xDC00).contains(&code_unit)
+ && source
+ .get(index)
+ .is_some_and(|low| (0xDC00..0xE000).contains(&low.code()))
+ {
+ low_surrogates.push(u32_from_usize(index));
+ index += 1;
+ }
+ }
+ Self {
+ line_starts,
+ low_surrogates,
+ source_length: u32_from_usize(source.len()),
+ ends_with_lone_line_terminator,
+ initial_line_number,
+ last_line: AtomicUsize::new(0),
+ }
+ }
+
+ fn line_of(&self, offset: u32) -> usize {
+ let last_line = self.last_line.load(Ordering::Relaxed);
+ let is_on_last_line = self.line_starts[last_line] <= offset
+ && self.line_starts.get(last_line + 1).is_none_or(|&next| offset < next);
+ let line = if is_on_last_line {
+ last_line
+ } else {
+ self.line_starts.partition_point(|&start| start <= offset) - 1
+ };
+ self.last_line.store(line, Ordering::Relaxed);
+ line
+ }
+
+ fn column_of(&self, line: usize, offset: u32) -> u32 {
+ let line_start = self.line_starts[line];
+ if self.low_surrogates.is_empty() {
+ return offset - line_start + 1;
+ }
+ let low_surrogates = self.low_surrogates.partition_point(|&low| low < offset)
+ - self.low_surrogates.partition_point(|&low| low < line_start);
+ offset - line_start + 1 - u32_from_usize(low_surrogates)
+ }
+
+ pub(crate) fn position(&self, offset: u32) -> Position {
+ let at_end = offset == self.source_length && self.source_length != 0;
+ let (line, column) = if at_end && self.ends_with_lone_line_terminator {
+ // NB: The end of the source is on the line of a line terminator that ends it.
+ let line = self.line_starts.len() - 2;
+ (line, self.column_of(line, offset - 1) + 1)
+ } else if at_end && self.line_starts.last() == Some(&offset) {
+ // NB: A CRLF that ends the source starts a line before its LF.
+ (self.line_starts.len() - 1, 2)
+ } else {
+ let line = self.line_of(offset);
+ (line, self.column_of(line, offset))
+ };
+ Position {
+ line: self.initial_line_number + u32_from_usize(line),
+ column,
+ offset,
+ }
+ }
+}
+
+/// What the code being parsed may do, which the code around it decides.
+#[derive(Clone, Copy)]
+pub struct ParseOptions {
+ pub program_type: ProgramType,
+ pub initial_line_number: u32,
+ pub starts_in_strict_mode: bool,
+ pub initiated_by_eval: bool,
+ pub in_eval_function_context: bool,
+ pub allow_super_property_lookup: bool,
+ pub allow_super_constructor_call: bool,
+ pub in_class_field_initializer: bool,
+ /// The code is that of a function body of this kind.
+ pub function_body: Option<crate::ast::FunctionKind>,
+ /// No identifier may resolve to a global binding.
+ pub suppress_globals: bool,
+ /// Keep the tree of everything, for a dump of it, rather than just of what runs first.
+ pub keep_whole_tree: bool,
+}
+
+impl ParseOptions {
+ /// What parsing the top level again has to know of how it got parsed.
+ fn program_context(&self) -> base::ProgramContext {
+ use base::ctx;
+ let mut context = 0;
+ if self.in_eval_function_context {
+ context |= ctx::NEW_TARGET;
+ }
+ if self.allow_super_property_lookup {
+ context |= ctx::SUPER_PROPERTY;
+ }
+ if self.allow_super_constructor_call {
+ context |= ctx::SUPER_CALL;
+ }
+ if self.in_class_field_initializer {
+ context |= ctx::NO_ARGUMENTS;
+ }
+ if let Some(kind) = self.function_body {
+ use crate::ast::FunctionKind;
+ context |= ctx::RETURN | ctx::NEW_TARGET;
+ if matches!(kind, FunctionKind::Generator | FunctionKind::AsyncGenerator) {
+ context |= ctx::GENERATOR;
+ }
+ if matches!(kind, FunctionKind::Async | FunctionKind::AsyncGenerator) {
+ context |= ctx::ASYNC | ctx::CAN_AWAIT;
+ }
+ }
+ base::ProgramContext {
+ context,
+ starts_in_strict_mode: self.starts_in_strict_mode,
+ initiated_by_eval: self.initiated_by_eval,
+ has_no_globals: self.initiated_by_eval || self.suppress_globals,
+ }
+ }
+
+ pub fn new(program_type: ProgramType) -> Self {
+ Self {
+ program_type,
+ initial_line_number: 1,
+ starts_in_strict_mode: false,
+ initiated_by_eval: false,
+ in_eval_function_context: false,
+ allow_super_property_lookup: false,
+ allow_super_constructor_call: false,
+ in_class_field_initializer: false,
+ function_body: None,
+ suppress_globals: false,
+ keep_whole_tree: false,
+ }
+ }
+}
+
+/// What parsing a source without errors leaves behind.
+/// The rows of a top level with marks, and the row of the program.
+type TopLevelRows = Result<(Ast, u32), OutOfStack>;
+
+/// What a parse is for, which decides whether there is any use in rows for a sweep.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum ParsePurpose {
+ Compile,
+ CheckSyntax,
+}
+
+struct ParserOutput {
+ ast: Ast,
+ top_level_rows: Option<TopLevelRows>,
+ index: FunctionIndex,
+ interner: Interner,
+ root: u32,
+ first_token_start: u32,
+ is_strict_mode: bool,
+ has_top_level_await: bool,
+ eval_referenced_private_names: Vec<u32>,
+ global_names_used_in_with: Vec<u32>,
+ lines: LineTable,
+}
+
+/// Parses `source`, from a copy of it that is followed by the padding the lexer needs for as long as the parse takes.
+fn parse_code_units<U: Unit + Default>(
+ source: &[U],
+ options: &ParseOptions,
+ purpose: ParsePurpose,
+) -> Result<ParserOutput, Vec<ParseError>> {
+ let mut padded = Vec::with_capacity(source.len() + SOURCE_PADDING);
+ padded.extend_from_slice(source);
+ padded.resize(source.len() + SOURCE_PADDING, U::default());
+ // SAFETY: The source is followed by the padding.
+ let mut parser = unsafe {
+ Parser::new(
+ &padded[..source.len()],
+ options.program_type == ProgramType::Module,
+ if options.keep_whole_tree {
+ Mode::Full
+ } else {
+ Mode::Lazy
+ },
+ )
+ };
+ parser.strict |= options.starts_in_strict_mode;
+ parser.initiated_by_eval = options.initiated_by_eval;
+ parser.add_context(options.program_context().context);
+ let root = parser.parse_program();
+ let lines = LineTable::new(source, options.initial_line_number);
+ if let Some(error) = parser.err.take() {
+ let position = lines.position(error.pos.min(u32_from_usize(source.len())));
+ return Err(vec![ParseError {
+ message: error.message,
+ line: position.line,
+ column: position.column,
+ }]);
+ }
+ let top_level_rows =
+ (purpose == ParsePurpose::Compile).then(|| parser.parse_top_level_rows(options.program_context()));
+ Ok(ParserOutput {
+ top_level_rows,
+ root,
+ first_token_start: parser.first_token_start,
+ is_strict_mode: parser.strict,
+ has_top_level_await: parser.has_top_level_await,
+ ast: parser.ast,
+ index: parser.index,
+ interner: parser.interner,
+ eval_referenced_private_names: parser.eval_referenced_private_names,
+ global_names_used_in_with: parser.global_names_used_in_with,
+ lines,
+ })
+}
+
+/// Parses `source` at the width of its storage.
+fn parse_source(
+ source: &ak::Utf16String,
+ options: &ParseOptions,
+ purpose: ParsePurpose,
+) -> Result<ParserOutput, Vec<ParseError>> {
+ match source.as_units() {
+ ak::Utf16StringUnits::Ascii(units) | ak::Utf16StringUnits::Latin1(units) => {
+ parse_code_units(units, options, purpose)
+ }
+ ak::Utf16StringUnits::Utf16(units) => parse_code_units(units, options, purpose),
+ }
+}
+
+/// Parses `source` into a tree of its top-level code with its identifiers resolved.
+pub fn parse_to_tree(source: &ak::Utf16String, options: &ParseOptions) -> Result<SyntaxTree, Vec<ParseError>> {
+ let mut output = parse_source(source, options, ParsePurpose::Compile)?;
+ let default_export_name = Name(output.interner.intern_bytes(b"*default*"));
+ let default_constructor_parameter_name = Name(output.interner.intern_bytes(b"args"));
+ let mut names = NameTable::default();
+ for name in 0..output.interner.len() {
+ names.push(output.interner.text(u32_from_usize(name)));
+ }
+ let mut global_names_used_in_with = output.global_names_used_in_with;
+ global_names_used_in_with.sort_unstable();
+ global_names_used_in_with.dedup();
+ output.index.shrink_to_fit();
+ let script = Arc::new(ScriptData {
+ index: output.index,
+ names,
+ positions: Arc::new(SourcePositions {
+ source: source.clone(),
+ lines: output.lines,
+ }),
+ program_type: options.program_type,
+ program_context: options.program_context(),
+ top_level_rows: Mutex::new(output.top_level_rows),
+ default_export_name,
+ default_constructor_parameter_name,
+ global_names_used_in_with,
+ reparse_context: Mutex::new(None),
+ });
+ let mut tree = SyntaxTree {
+ script,
+ ast: output.ast,
+ root: output.root,
+ first_token_start: output.first_token_start,
+ is_strict_mode: output.is_strict_mode,
+ has_top_level_await: options.program_type == ProgramType::Module && output.has_top_level_await,
+ eval_referenced_private_names: output
+ .eval_referenced_private_names
+ .iter()
+ .map(|&name| Name(name))
+ .collect(),
+ resolutions: Vec::new(),
+ scopes: ScopeTable::default(),
+ program_scope_row: 0,
+ function_scope_rows: Vec::new(),
+ outer_resolutions: None,
+ };
+ resolve::resolve_program(
+ &mut tree,
+ &resolve::ResolveOptions {
+ initiated_by_eval: options.initiated_by_eval,
+ suppress_globals: options.suppress_globals,
+ },
+ );
+ Ok(tree)
+}
+
+/// Parses `source` for its syntax errors alone.
+pub fn check_syntax(source: &ak::Utf16String, options: &ParseOptions) -> Result<(), Vec<ParseError>> {
+ parse_source(source, options, ParsePurpose::CheckSyntax).map(|_| ())
+}
diff --git a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
index 7906717f7d0..487c5aa1622 100644
--- a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
+++ b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
@@ -138,7 +138,7 @@ fn with_callee_context<T>(
argument_count: u32::try_from(arguments_list.len()).expect("the argument count fits in u32"),
..Default::default()
};
- function.get_stack_frame_info(vm, &mut stack_frame_info);
+ function.get_stack_frame_info(vm, &mut stack_frame_info)?;
let stack = vm.interpreter_stack();
let stack_mark = stack.top.get();
@@ -1265,11 +1265,11 @@ struct EvalResult<'vm> {
declaration_data: EvalDeclarationData<'vm>,
}
-fn fly_string_of(name: &crate::ast::Utf16String) -> Utf16FlyString {
- Utf16FlyString::from_utf16(&name.0)
+fn fly_string_of(name: &Utf16String) -> Utf16FlyString {
+ Utf16View::of_string(name).to_utf16_fly_string()
}
-fn fly_strings_of(names: &[crate::ast::Utf16String]) -> Vec<Utf16FlyString> {
+fn fly_strings_of(names: &[Utf16String]) -> Vec<Utf16FlyString> {
names.iter().map(fly_string_of).collect()
}
@@ -1289,10 +1289,6 @@ fn compile_eval(
in_class_field_initializer: bool,
) -> Result<EvalResult<'_>, String> {
let source_code = SourceCode::create(Utf16String::default(), code);
- let mut code_units = Vec::with_capacity(source_code.length_in_code_units());
- Utf16View::of_string(source_code.code()).append_to(&mut code_units);
- let length = code_units.len();
-
let context = EvalContext {
starts_in_strict_mode: strict_caller == CallerMode::Strict,
in_eval_function_context: in_function,
@@ -1300,7 +1296,7 @@ fn compile_eval(
allow_super_constructor_call: in_derived_constructor,
in_class_field_initializer,
};
- let parsed = parse_eval(&code_units, context).map_err(|errors| {
+ let parsed = parse_eval(source_code.code(), context).map_err(|errors| {
errors
.first()
.map(|error| format!("{} (line: {}, column: {})", error.message, error.line, error.column))
@@ -1310,17 +1306,17 @@ fn compile_eval(
let CompiledEval {
executable,
declarations,
- } = crate::compile::compile_eval(parsed, length);
+ } = crate::compile::compile_eval(parsed);
let executable = Executable::create_with_source_code(vm, executable, Some(&source_code));
executable.set_name(Utf16FlyString::from_utf8("eval"));
let functions_to_initialize_shared_data = MarkedVec::with_capacity(vm, declarations.functions_to_initialize.len());
let mut functions_to_initialize = Vec::with_capacity(declarations.functions_to_initialize.len());
let mut declared_function_names = HashSet::new();
- for mut function in declarations.functions_to_initialize {
+ for function in &declarations.functions_to_initialize {
functions_to_initialize_shared_data.push(SharedFunctionInstanceData::create_from_pending_shared_function_data(
vm,
- &mut function.shared_function_data,
+ &function.shared_function_data,
declarations.is_strict,
Some(&source_code),
));
diff --git a/Libraries/LibJS/Rust/src/runtime/bound_function.rs b/Libraries/LibJS/Rust/src/runtime/bound_function.rs
index 1ad9cd9aa2a..628b02a077a 100644
--- a/Libraries/LibJS/Rust/src/runtime/bound_function.rs
+++ b/Libraries/LibJS/Rust/src/runtime/bound_function.rs
@@ -247,13 +247,14 @@ impl BoundFunction {
internal_construct(&target, vm, callee_context, final_new_target)
}
- fn get_stack_frame_info(object: &Object, vm: &Vm, stack_frame_info: &mut StackFrameInfo) {
+ fn get_stack_frame_info(object: &Object, vm: &Vm, stack_frame_info: &mut StackFrameInfo) -> ThrowCompletionOr<()> {
let function = as_bound_function(object);
function
.bound_target_function()
- .get_stack_frame_info(vm, stack_frame_info);
+ .get_stack_frame_info(vm, stack_frame_info)?;
stack_frame_info.argument_count +=
u32::try_from(function.bound_arguments_count()).expect("the bound argument count fits in u32");
+ Ok(())
}
pub fn name_for_call_stack(&self) -> Utf16String {
diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
index 2cfa747c90b..64533531f29 100644
--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
@@ -454,29 +454,29 @@ impl EcmascriptFunctionObject {
}
/// The function's executable, compiled first if the function never ran.
- pub fn compiled_executable(&self, vm: &Vm) -> Gc<Executable> {
+ pub fn compiled_executable(&self, vm: &Vm) -> ThrowCompletionOr<Gc<Executable>> {
let shared_data = self.shared_data();
if let Some(executable) = shared_data.executable() {
- return executable;
+ return Ok(executable);
}
- let rust_executable = SharedFunctionInstanceData::compile_function(vm, shared_data, false)
- .expect("an ECMAScript function compiles to an executable");
+ let rust_executable = SharedFunctionInstanceData::compile_function(vm, shared_data, false)?;
shared_data.set_executable(Some(rust_executable));
rust_executable.set_name(self.name());
if should_dump_bytecode() {
rust_executable.dump();
}
shared_data.clear_compile_inputs();
- rust_executable
+ Ok(rust_executable)
}
- fn get_stack_frame_info(object: &Object, vm: &Vm, stack_frame_info: &mut StackFrameInfo) {
+ fn get_stack_frame_info(object: &Object, vm: &Vm, stack_frame_info: &mut StackFrameInfo) -> ThrowCompletionOr<()> {
let function = as_ecmascript_function(object);
- let executable = function.compiled_executable(vm);
+ let executable = function.compiled_executable(vm)?;
stack_frame_info.registers_and_locals_count = executable.registers_and_locals_count();
stack_frame_info.constant_count =
u32::try_from(executable.constants().len()).expect("the constant count fits in u32");
stack_frame_info.argument_count = stack_frame_info.argument_count.max(function.formal_parameter_count());
+ Ok(())
}
// 10.2.1 [[Call]] ( thisArgument, argumentsList ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-call-thisargument-argumentslist
diff --git a/Libraries/LibJS/Rust/src/runtime/function_constructor.rs b/Libraries/LibJS/Rust/src/runtime/function_constructor.rs
index f955b2112b0..9b839b0b075 100644
--- a/Libraries/LibJS/Rust/src/runtime/function_constructor.rs
+++ b/Libraries/LibJS/Rust/src/runtime/function_constructor.rs
@@ -338,11 +338,9 @@ pub fn compile_dynamic_function(
kind: FunctionKind,
) -> Result<Gc<SharedFunctionInstanceData>, ParserError> {
let source_code = SourceCode::create(Utf16String::default(), source_text.clone());
- let mut full_source = Vec::with_capacity(source_code.length_in_code_units());
- Utf16View::of_string(source_code.code()).append_to(&mut full_source);
-
- let description = crate::compile::parse_dynamic_function(&full_source, parameters_string, body_parse_string, kind)
- .and_then(crate::compile::ParsedDynamicFunction::into_description);
+ let description =
+ crate::compile::parse_dynamic_function(source_code.code(), parameters_string, body_parse_string, kind)
+ .and_then(crate::compile::ParsedDynamicFunction::into_description);
let description = match description {
Ok(description) => description,
Err(errors) => {
@@ -355,7 +353,7 @@ pub fn compile_dynamic_function(
}
};
- let function_data = SharedFunctionInstanceData::create(vm, description, Some(&source_code));
+ let function_data = SharedFunctionInstanceData::create(vm, &description, description.strict, Some(&source_code));
function_data.set_source_text_owner(source_text.clone());
Ok(function_data)
}
diff --git a/Libraries/LibJS/Rust/src/runtime/generator_object.rs b/Libraries/LibJS/Rust/src/runtime/generator_object.rs
index a6163e959f3..d25ee18627d 100644
--- a/Libraries/LibJS/Rust/src/runtime/generator_object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/generator_object.rs
@@ -59,7 +59,7 @@ impl GeneratingFunction {
GeneratingFunction::Ecmascript(function) => function
.bytecode_executable()
.expect("a generating function is compiled before it is called"),
- GeneratingFunction::NativeJavaScriptBacked(function) => function.bytecode_executable(vm),
+ GeneratingFunction::NativeJavaScriptBacked(function) => function.bytecode_executable(vm).must(),
}
}
}
diff --git a/Libraries/LibJS/Rust/src/runtime/intrinsics.rs b/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
index 8ec6f7f48e1..fb3e27cf97b 100644
--- a/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
+++ b/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
@@ -167,7 +167,6 @@ use crate::runtime::weak_set_constructor::WeakSetConstructor;
use crate::runtime::weak_set_prototype::WeakSetPrototype;
use crate::runtime::wrap_for_valid_iterator_prototype::WrapForValidIteratorPrototype;
use crate::source_code::SourceCode;
-use crate::utf16::Utf16View;
/// Declares the intrinsics' slots, which all start out empty.
macro_rules! define_intrinsics {
@@ -855,9 +854,7 @@ pub(crate) fn parse_builtin_file<'vm>(
Utf16String::from_utf8("BuiltinFile"),
Utf16String::from_utf8(script_text),
);
- let mut source = Vec::with_capacity(code.length_in_code_units());
- Utf16View::of_string(code.code()).append_to(&mut source);
- let parsed = crate::compile::parse_builtin_file(&source);
+ let parsed = crate::compile::parse_builtin_file(code.code());
Rc::new((code, parsed))
})
.clone()
@@ -866,7 +863,12 @@ pub(crate) fn parse_builtin_file<'vm>(
let shared_data_list = MarkedVec::new(vm);
for description in crate::compile::describe_builtin_file_functions(parsed) {
- shared_data_list.push(SharedFunctionInstanceData::create(vm, description, Some(code)));
+ shared_data_list.push(SharedFunctionInstanceData::create(
+ vm,
+ &description,
+ description.strict,
+ Some(code),
+ ));
}
shared_data_list
}
diff --git a/Libraries/LibJS/Rust/src/runtime/module_request.rs b/Libraries/LibJS/Rust/src/runtime/module_request.rs
index 1738b75ecd1..8d551b2f5b1 100644
--- a/Libraries/LibJS/Rust/src/runtime/module_request.rs
+++ b/Libraries/LibJS/Rust/src/runtime/module_request.rs
@@ -75,16 +75,11 @@ impl ModuleRequest {
/// The ModuleRequest a module request of the frontend stands for: the attributes of a request that has any are
/// sorted.
pub fn from_frontend(request: &ast::ModuleRequest) -> Self {
- let specifier = Utf16FlyString::from_utf16(&request.module_specifier);
+ let specifier = Utf16View::of_string(&request.module_specifier).to_utf16_fly_string();
let attributes: Vec<ImportAttribute> = request
.attributes
.iter()
- .map(|attribute| {
- ImportAttribute::new(
- Utf16String::from_utf16(&attribute.key),
- Utf16String::from_utf16(&attribute.value),
- )
- })
+ .map(|attribute| ImportAttribute::new(attribute.key.clone(), attribute.value.clone()))
.collect();
if attributes.is_empty() {
return Self::new(specifier);
diff --git a/Libraries/LibJS/Rust/src/runtime/native_javascript_backed_function.rs b/Libraries/LibJS/Rust/src/runtime/native_javascript_backed_function.rs
index b848deb35a7..ccbb4b8a74b 100644
--- a/Libraries/LibJS/Rust/src/runtime/native_javascript_backed_function.rs
+++ b/Libraries/LibJS/Rust/src/runtime/native_javascript_backed_function.rs
@@ -123,9 +123,9 @@ impl NativeJavaScriptBackedFunction {
Gc::from_ref(self)
}
- fn get_stack_frame_info(object: &Object, vm: &Vm, stack_frame_info: &mut StackFrameInfo) {
+ fn get_stack_frame_info(object: &Object, vm: &Vm, stack_frame_info: &mut StackFrameInfo) -> ThrowCompletionOr<()> {
let function = as_native_javascript_backed_function(object);
- let bytecode_executable = function.bytecode_executable(vm);
+ let bytecode_executable = function.bytecode_executable(vm)?;
stack_frame_info.registers_and_locals_count = bytecode_executable.registers_and_locals_count();
stack_frame_info.constant_count =
u32::try_from(bytecode_executable.constants().len()).expect("the constant count fits in u32");
@@ -134,6 +134,7 @@ impl NativeJavaScriptBackedFunction {
let function_length =
u32::try_from(function.shared_data().function_length()).expect("a builtin's length is not negative");
stack_frame_info.argument_count = stack_frame_info.argument_count.max(function_length);
+ Ok(())
}
fn call(function: &NativeFunction, vm: &Vm) -> ThrowCompletionOr<Value> {
@@ -142,7 +143,7 @@ impl NativeJavaScriptBackedFunction {
let running_execution_context = vm
.running_execution_context()
.expect("a NativeJavaScriptBackedFunction runs in its own execution context");
- let result = vm.run_executable(running_execution_context, function.bytecode_executable(vm), 0);
+ let result = vm.run_executable(running_execution_context, function.bytecode_executable(vm)?, 0);
let kind = function.kind();
if kind == FunctionKind::Normal {
@@ -185,10 +186,10 @@ impl NativeJavaScriptBackedFunction {
)))
}
- pub fn bytecode_executable(&self, vm: &Vm) -> Gc<Executable> {
+ pub fn bytecode_executable(&self, vm: &Vm) -> ThrowCompletionOr<Gc<Executable>> {
let shared_data = self.shared_data();
if let Some(executable) = shared_data.executable() {
- return executable;
+ return Ok(executable);
}
// NB: The abstract operations a builtin file calls are functions of the realm that is current while its
@@ -196,18 +197,18 @@ impl NativeJavaScriptBackedFunction {
// another realm, so it is compiled in its own.
let running_execution_context = vm.running_execution_context_if_any();
let caller_realm = running_execution_context.and_then(|context| context.realm.replace(Some(self.realm())));
- let rust_executable = SharedFunctionInstanceData::compile_function(vm, shared_data, true)
- .expect("a builtin written in JavaScript compiles to an executable");
+ let rust_executable = SharedFunctionInstanceData::compile_function(vm, shared_data, true);
if let Some(context) = running_execution_context {
context.realm.set(caller_realm);
}
+ let rust_executable = rust_executable?;
shared_data.set_executable(Some(rust_executable));
rust_executable.set_name(shared_data.name());
if should_dump_bytecode() {
rust_executable.dump();
}
shared_data.clear_compile_inputs();
- rust_executable
+ Ok(rust_executable)
}
/// The executable an inline call of this builtin runs, if the interpreter can call it inline: it is a normal
@@ -216,7 +217,7 @@ impl NativeJavaScriptBackedFunction {
if self.kind() != FunctionKind::Normal || self.function_environment_needed() {
return None;
}
- Some(self.bytecode_executable(vm))
+ self.bytecode_executable(vm).ok()
}
pub fn shared_data(&self) -> Gc<SharedFunctionInstanceData> {
diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rs
index 74b8b6ccc39..f36f93c42f0 100644
--- a/Libraries/LibJS/Rust/src/runtime/object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object.rs
@@ -231,7 +231,7 @@ pub struct ObjectMethods {
pub has_constructor: fn(&Object) -> bool,
pub is_strict_mode: fn(&Object) -> bool,
/// Takes the VM since an ECMAScript function compiles its body the first time it is asked.
- pub get_stack_frame_info: fn(&Object, &Vm, &mut StackFrameInfo),
+ pub get_stack_frame_info: fn(&Object, &Vm, &mut StackFrameInfo) -> ThrowCompletionOr<()>,
/// FunctionObject::realm(), the [[Realm]] of a function that has one.
pub function_realm: fn(&Object) -> Option<Gc<Realm>>,
/// FunctionObject::name_for_call_stack(), which every class of function object defines.
@@ -278,7 +278,7 @@ pub static ORDINARY_OBJECT_METHODS: ObjectMethods = ObjectMethods {
internal_construct: None,
has_constructor: |_| false,
is_strict_mode: |_| false,
- get_stack_frame_info: |_, _, _| {},
+ get_stack_frame_info: |_, _, _| Ok(()),
function_realm: |_| None,
name_for_call_stack: |_| unreachable!("FunctionObject::name_for_call_stack is pure virtual"),
native_function: None,
@@ -2074,8 +2074,8 @@ impl Object {
(self.methods().is_strict_mode)(self)
}
- pub fn get_stack_frame_info(&self, vm: &Vm, info: &mut StackFrameInfo) {
- (self.methods().get_stack_frame_info)(self, vm, info);
+ pub fn get_stack_frame_info(&self, vm: &Vm, info: &mut StackFrameInfo) -> ThrowCompletionOr<()> {
+ (self.methods().get_stack_frame_info)(self, vm, info)
}
pub fn function_realm(&self) -> Option<Gc<Realm>> {
diff --git a/Libraries/LibJS/Rust/src/runtime/proxy_object.rs b/Libraries/LibJS/Rust/src/runtime/proxy_object.rs
index 42ade3193db..80b414de422 100644
--- a/Libraries/LibJS/Rust/src/runtime/proxy_object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/proxy_object.rs
@@ -1293,10 +1293,10 @@ impl ProxyObject {
Ok(())
}
- fn get_stack_frame_info(object: &Object, vm: &Vm, stack_frame_info: &mut StackFrameInfo) {
+ fn get_stack_frame_info(object: &Object, vm: &Vm, stack_frame_info: &mut StackFrameInfo) -> ThrowCompletionOr<()> {
let target = as_proxy_object(object).target.get();
assert!(target.is_function());
- target.get_stack_frame_info(vm, stack_frame_info);
+ target.get_stack_frame_info(vm, stack_frame_info)
}
pub fn name_for_call_stack() -> Utf16String {
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 25a7f72f495..91d56fd50e5 100644
--- a/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
+++ b/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
@@ -7,31 +7,30 @@
use core::cell::{Cell, OnceCell, RefCell};
use std::collections::HashSet;
use std::rc::Rc;
+use std::sync::Arc;
use ak::{Utf16FlyString, Utf16String};
use libjs_runtime_macros::Trace;
pub use crate::ast::FunctionKind;
-use crate::ast::FunctionPayload;
-use crate::bytecode::bytecode_cache::materialize_cached_function_executable;
use crate::bytecode::executable::Executable;
-use crate::bytecode::generator::{FunctionSfdMetadata, PendingSharedFunctionData, PrecompiledFunction};
-use crate::bytecode_cache::{DecodedCachedExecutableRecord, DecodedFunctionRecord};
-use crate::compile::FunctionPrecompileMode;
+use crate::bytecode::executable_data::{FunctionSfdMetadata, PendingSharedFunctionData, PrecompiledFunction};
+use crate::compile::FunctionPayload;
use crate::compile::SharedFunctionDescription;
use crate::gc::class::{GcCell, define_cell};
use crate::gc::defer_gc::DeferGc;
use crate::gc::gc_ref_cell::GcRefCell;
-use crate::gc::root::MarkedVec;
use crate::gc::visitor::{Trace, Visitor};
-use crate::interpreter::run::should_dump_bytecode;
use crate::interpreter::vm::Vm;
use crate::layout::cell::{CellHeaderTail, Gc};
use crate::layout::execution_context::{ScriptOrModule, ScriptOrModuleSlot};
use crate::layout::function_object::CallEnvironmentTemplate;
pub use crate::layout::function_object::{SharedFunctionInstanceData, asm_call_metadata};
use crate::layout::member::NullableMember;
+use crate::runtime::completion::ThrowCompletionOr;
use crate::runtime::environment_shape::{EnvironmentShape, EnvironmentShapeCache};
+use crate::runtime::error::ErrorKind;
+use crate::runtime::error_types::ErrorType;
use crate::runtime::property_key::PropertyKey;
use crate::runtime::shape::Shape;
use crate::source_code::SourceCode;
@@ -71,12 +70,10 @@ pub enum ClassFieldInitializerName {
/// What a function's executable is made from when it is first called, which only one thing can be at a time.
enum CompileInput {
None,
- /// The function's AST, which its bytecode is compiled from.
- FunctionAst(Box<FunctionPayload>),
+ /// The function is not parsed yet: its source and its row there, which its tree is parsed from.
+ Unparsed(Arc<FunctionPayload>),
/// Freshly compiled bytecode.
- PrecompiledBytecode(Box<PrecompiledFunction>),
- /// The function's executable in a bytecode cache blob.
- CachedBytecode(Box<DecodedCachedExecutableRecord>),
+ PrecompiledBytecode(Arc<PrecompiledFunction>),
}
/// A CompileInput in one word: the pointer, with what it points at in its lowest bits.
@@ -86,14 +83,12 @@ struct CompileInputSlot(Cell<*mut ()>);
const _: () = assert!(
align_of::<FunctionPayload>() > CompileInputSlot::TAG_MASK
&& align_of::<PrecompiledFunction>() > CompileInputSlot::TAG_MASK
- && align_of::<DecodedCachedExecutableRecord>() > CompileInputSlot::TAG_MASK
);
impl CompileInputSlot {
const TAG_MASK: usize = 0b11;
- const TAG_FUNCTION_AST: usize = 1;
+ const TAG_UNPARSED: usize = 1;
const TAG_PRECOMPILED_BYTECODE: usize = 2;
- const TAG_CACHED_BYTECODE: usize = 3;
fn new(input: CompileInput) -> Self {
let slot = Self(Cell::new(core::ptr::null_mut()));
@@ -105,11 +100,10 @@ impl CompileInputSlot {
drop(self.take());
self.0.set(match input {
CompileInput::None => core::ptr::null_mut(),
- CompileInput::FunctionAst(ast) => Self::tagged(Box::into_raw(ast), Self::TAG_FUNCTION_AST),
+ CompileInput::Unparsed(payload) => Self::tagged(Arc::into_raw(payload).cast_mut(), Self::TAG_UNPARSED),
CompileInput::PrecompiledBytecode(precompiled) => {
- Self::tagged(Box::into_raw(precompiled), Self::TAG_PRECOMPILED_BYTECODE)
+ Self::tagged(Arc::into_raw(precompiled).cast_mut(), Self::TAG_PRECOMPILED_BYTECODE)
}
- CompileInput::CachedBytecode(cached) => Self::tagged(Box::into_raw(cached), Self::TAG_CACHED_BYTECODE),
});
}
@@ -120,21 +114,16 @@ impl CompileInputSlot {
fn take(&self) -> CompileInput {
let word = self.0.replace(core::ptr::null_mut());
let pointer = word.map_addr(|address| address & !Self::TAG_MASK);
- // SAFETY: set() made the word from a box of the type its tag says, which nothing else owns now that the word
- // is gone from the slot.
+ // SAFETY: set() made the word from a reference of the type its tag says, which this takes over now that the
+ // word is gone from the slot.
unsafe {
match word.addr() & Self::TAG_MASK {
- Self::TAG_FUNCTION_AST => CompileInput::FunctionAst(Box::from_raw(pointer.cast())),
- Self::TAG_PRECOMPILED_BYTECODE => CompileInput::PrecompiledBytecode(Box::from_raw(pointer.cast())),
- Self::TAG_CACHED_BYTECODE => CompileInput::CachedBytecode(Box::from_raw(pointer.cast())),
+ Self::TAG_UNPARSED => CompileInput::Unparsed(Arc::from_raw(pointer.cast())),
+ Self::TAG_PRECOMPILED_BYTECODE => CompileInput::PrecompiledBytecode(Arc::from_raw(pointer.cast())),
_ => CompileInput::None,
}
}
}
-
- fn tag(&self) -> usize {
- self.0.get().addr() & Self::TAG_MASK
- }
}
impl Drop for CompileInputSlot {
@@ -161,11 +150,6 @@ struct SharedFunctionInstanceDataRareData {
#[gc(untraced)]
source_text_owner: RefCell<Utf16String>,
class_field_initializer_name: GcRefCell<ClassFieldInitializerName>, // [[ClassFieldInitializerName]]
- /// The source text range the function was created with, which a bytecode cache blob identifies the function by,
- /// once the source text range of the function no longer is that, as when a class constructor's grows to the whole
- /// class.
- #[gc(untraced)]
- bytecode_cache_source_text_range: Cell<Option<(u32, u32)>>,
/// Functions with parameter expressions may have a separate var environment.
var_environment_bindings_count: Cell<u32>,
var_environment_shape: NullableMember<EnvironmentShape>,
@@ -176,14 +160,14 @@ struct SharedFunctionInstanceDataRareData {
pub struct SharedFunctionInstanceDataStorage {
name: Utf16FlyString,
- // NB: source_text_offset and source_text_length are a range of the source code we parsed the AST from.
+ // NB: source_text_offset and source_text_length are a range of the source code we parsed the function from.
#[gc(untraced)]
source_code: Cell<Option<Rc<SourceCode>>>,
source_text_offset: Cell<u32>,
source_text_length: Cell<u32>, // [[SourceText]]
#[gc(untraced)]
- parameter_names: Option<Box<ParameterNames>>,
+ parameter_names: OnceCell<Box<ParameterNames>>,
#[gc(untraced)]
compile_input: CompileInputSlot,
rare_data: OnceCell<Box<SharedFunctionInstanceDataRareData>>,
@@ -231,10 +215,23 @@ unsafe impl Trace for CallEnvironmentTemplate {
/// OPTIMIZATION: Precompute the argument indices that alias parameter bindings. Only the last occurrence of each
/// parameter name is eligible; each arguments object also limits the mapping to its argument count.
/// https://tc39.es/ecma262/#sec-createmappedargumentsobject
-fn parameter_names_of(parameter_names: Vec<Utf16FlyString>) -> Option<Box<ParameterNames>> {
+fn parameter_names_of(parameter_names: &[Utf16FlyString]) -> Option<Box<ParameterNames>> {
if parameter_names.is_empty() {
return None;
}
+ // OPTIMIZATION: Going through a few names beats a hash set of them.
+ const MAXIMUM_PARAMETERS_TO_SCAN: usize = 8;
+ if parameter_names.len() <= MAXIMUM_PARAMETERS_TO_SCAN {
+ let has_repeated_name =
+ (1..parameter_names.len()).any(|index| parameter_names[..index].contains(&parameter_names[index]));
+ if !has_repeated_name {
+ let names: Rc<[Utf16FlyString]> = parameter_names.into();
+ return Some(Box::new(ParameterNames {
+ mapped_argument_names: names.clone(),
+ parameter_binding_names: names,
+ }));
+ }
+ }
let mut seen_names = HashSet::with_capacity(parameter_names.len());
let mut mapped_names: Vec<Utf16FlyString> = vec![Utf16FlyString::default(); parameter_names.len()];
let mut has_repeated_name = false;
@@ -254,7 +251,7 @@ fn parameter_names_of(parameter_names: Vec<Utf16FlyString>) -> Option<Box<Parame
let parameter_binding_names = if has_repeated_name {
let mut seen_names = HashSet::with_capacity(parameter_names.len());
let mut names: Vec<Utf16FlyString> = Vec::with_capacity(parameter_names.len());
- for name in &parameter_names {
+ for name in parameter_names {
if seen_names.insert(name) {
names.push(name.clone());
}
@@ -286,7 +283,7 @@ impl SharedFunctionInstanceData {
is_arrow_function: bool,
has_simple_parameter_list: bool,
parameter_names_for_mapped_arguments: Vec<Utf16FlyString>,
- function_ast: Option<Box<FunctionPayload>>,
+ payload: Option<Arc<FunctionPayload>>,
) -> Self {
// NB: initialize_after_construction()
let mut metadata = u64::from(formal_parameter_count)
@@ -316,10 +313,9 @@ impl SharedFunctionInstanceData {
source_code: Cell::new(None),
source_text_offset: Cell::new(0),
source_text_length: Cell::new(0),
- parameter_names: parameter_names_of(parameter_names_for_mapped_arguments),
- compile_input: CompileInputSlot::new(
- function_ast.map_or(CompileInput::None, CompileInput::FunctionAst),
- ),
+ parameter_names: parameter_names_of(&parameter_names_for_mapped_arguments)
+ .map_or_else(OnceCell::new, OnceCell::from),
+ compile_input: CompileInputSlot::new(payload.map_or(CompileInput::None, CompileInput::Unparsed)),
rare_data: OnceCell::new(),
function_environment_bindings_count: Cell::new(0),
function_environment_shape: NullableMember::null(),
@@ -351,36 +347,25 @@ impl SharedFunctionInstanceData {
self.asm_call_metadata.set(metadata);
}
- /// Creates the shared data of a function the frontend described.
+ /// Creates the shared data of a function the frontend described, which is strict if `strict`.
pub fn create(
vm: &Vm,
- description: SharedFunctionDescription,
+ description: &SharedFunctionDescription,
+ strict: bool,
source_code: Option<&Rc<SourceCode>>,
) -> Gc<SharedFunctionInstanceData> {
- let name = if description.name.is_empty() {
- Utf16FlyString::default()
- } else {
- Utf16FlyString::from_utf16(&description.name)
- };
-
- let mapped_parameter_names = if description.has_simple_parameter_list {
- description.parameter_names
- } else {
- Vec::new()
- };
-
let shared = vm.heap().allocate(|defer| {
Self::new(
defer,
description.function_kind,
- name,
+ description.name.clone(),
description.function_length,
description.formal_parameter_count,
- description.strict,
+ strict,
description.is_arrow,
description.has_simple_parameter_list,
- mapped_parameter_names,
- Some(description.payload),
+ Vec::new(),
+ Some(description.payload.clone()),
)
});
shared.update_can_inline_call();
@@ -400,63 +385,6 @@ impl SharedFunctionInstanceData {
shared
}
- /// Creates the shared data of a function of a bytecode cache blob that passed validation, whose executable stays in
- /// the blob until the function is first called. The function is strict if its own code is or `outer_strict` is.
- pub fn create_from_bytecode_cache(
- vm: &Vm,
- function: &DecodedFunctionRecord,
- outer_strict: bool,
- source_code: &Rc<SourceCode>,
- ) -> Gc<SharedFunctionInstanceData> {
- let name = function
- .function_name()
- .map_or_else(Utf16FlyString::default, |name| Utf16FlyString::from_utf16(&name));
- let simple_parameter_names = function.simple_parameter_names();
- let has_simple_parameter_list = simple_parameter_names.is_some();
- let source_text_range = function.source_text_range();
- let source_text_length = source_text_range.end.saturating_sub(source_text_range.start);
- let is_arrow_function = function.is_arrow();
-
- let shared = vm.heap().allocate(|defer| {
- Self::new(
- defer,
- function.function_kind(),
- name,
- function.length(),
- function.parameter_count(),
- function.has_strict_code() || outer_strict,
- is_arrow_function,
- has_simple_parameter_list,
- simple_parameter_names.unwrap_or_default(),
- None,
- )
- });
- shared.update_can_inline_call();
-
- // Set parsing insights that must be available before lazy compilation.
- let (uses_this, uses_this_from_environment) = function.parsing_insights_about_this();
- shared.set_uses_this(uses_this);
- shared.set_metadata_bit(
- asm_call_metadata::THIS_VALUE_NEEDS_ENVIRONMENT_RESOLUTION,
- uses_this_from_environment,
- );
- if uses_this_from_environment && !is_arrow_function {
- shared.set_function_environment_needed(true);
- }
-
- shared.storage.source_code.set(Some(source_code.clone()));
- shared.initialize_source_text_range(source_text_range.start, source_text_length);
- if let Some((name, is_private)) = function.field_initializer_name() {
- shared.set_class_field_initializer_name_from_utf16(&name, is_private);
- }
- shared.set_metadata(function.scope_metadata());
- shared
- .storage
- .compile_input
- .set(CompileInput::CachedBytecode(Box::new(function.cached_executable())));
- shared
- }
-
fn initialize_source_text_range(&self, source_text_offset: usize, source_text_length: usize) {
self.storage
.source_text_offset
@@ -466,80 +394,12 @@ impl SharedFunctionInstanceData {
.set(source_text_offset_or_length(source_text_length));
}
- /// The offset and length of the source text the function was created with.
- pub fn bytecode_cache_source_text_range(&self) -> (usize, usize) {
- let (offset, length) = self
- .storage
- .rare_data
- .get()
- .and_then(|rare_data| rare_data.bytecode_cache_source_text_range.get())
- .unwrap_or((
- self.storage.source_text_offset.get(),
- self.storage.source_text_length.get(),
- ));
- (offset as usize, length as usize)
- }
-
- /// Keeps the range a bytecode cache blob identifies the function by, as the source text range is about to change.
- fn preserve_bytecode_cache_source_text_range(&self) {
- let range = (
- self.storage.source_text_offset.get(),
- self.storage.source_text_length.get(),
- );
- let slot = &self.rare_data().bytecode_cache_source_text_range;
- if slot.get().is_none() {
- slot.set(Some(range));
- }
- }
-
- /// Whether `function`, a function of a bytecode cache blob nested in code that is strict if `outer_strict` is, is
- /// the function this shared data was created for, as rust_sfd_matches_bytecode_cache_function decides.
- pub fn matches_bytecode_cache_function(&self, function: &DecodedFunctionRecord, outer_strict: bool) -> bool {
- let source_text_range = function.source_text_range();
- self.bytecode_cache_source_text_range()
- == (
- source_text_range.start,
- source_text_range.end.saturating_sub(source_text_range.start),
- )
- && self.function_length == function.length()
- && self.formal_parameter_count() == function.parameter_count()
- && self.kind() == function.function_kind()
- && self.strict() == (function.has_strict_code() || outer_strict)
- && self.is_arrow_function() == function.is_arrow()
- && self.has_simple_parameter_list() == function.simple_parameter_names().is_some()
- }
-
- /// Replaces how the function compiles with its executable in a bytecode cache blob, which becomes its executable
- /// when it is first called, as rust_sfd_install_cached_bytecode_executable does.
- pub fn install_cached_bytecode_executable(
- &self,
- cached_executable: DecodedCachedExecutableRecord,
- metadata: &FunctionSfdMetadata,
- ) {
- self.set_metadata(metadata);
- self.storage
- .compile_input
- .set(CompileInput::CachedBytecode(Box::new(cached_executable)));
- }
-
- /// Replaces the executable of a function that already ran with one materialized from a bytecode cache blob, which
- /// took over the inline caches of the previous one, as rust_sfd_install_bytecode_cache_executable does.
- pub fn install_bytecode_cache_executable(&self, executable: Gc<Executable>, metadata: &FunctionSfdMetadata) {
- self.set_metadata(metadata);
- self.set_executable(Some(executable));
- executable.set_name(self.name());
- if should_dump_bytecode() {
- executable.dump();
- }
- self.clear_compile_inputs();
- }
-
/// vm.heap().allocate<SharedFunctionInstanceData>(vm, kind, name, function_length, formal_parameter_count, strict,
/// is_arrow_function, has_simple_parameter_list, parameter_names_for_mapped_arguments, NoSharedFunctionDataList {},
- /// nullptr): shared data that has no AST to compile, such as the wrapper of a module with top-level await, whose
+ /// nullptr): shared data that has nothing to compile, such as the wrapper of a module with top-level await, whose
/// executable the caller sets.
#[allow(clippy::too_many_arguments)]
- pub fn create_without_function_ast(
+ pub fn create_without_compile_input(
vm: &Vm,
kind: FunctionKind,
name: Utf16FlyString,
@@ -568,20 +428,20 @@ impl SharedFunctionInstanceData {
shared
}
- /// Creates the shared data of one of the functions an executable declares, taking what the frontend kept for it:
- /// its AST, its class field initializer name and the bytecode it may have compiled already.
+ /// Creates the shared data of one of the functions an executable declares, from what the frontend kept for it: its
+ /// description, its class field initializer name and the bytecode it may have compiled already.
pub fn create_from_pending_shared_function_data(
vm: &Vm,
- pending: &mut PendingSharedFunctionData,
+ pending: &PendingSharedFunctionData,
is_strict: bool,
source_code: Option<&Rc<SourceCode>>,
) -> Gc<SharedFunctionInstanceData> {
- let shared = Self::create(vm, pending.take_description(is_strict), source_code);
+ let shared = Self::create(vm, &pending.description, pending.is_strict_in(is_strict), source_code);
if let Some((name, is_private)) = &pending.class_field_initializer_name {
- shared.set_class_field_initializer_name_from_utf16(name, *is_private);
+ shared.set_class_field_initializer_name_from_utf16(&name.to_utf16(), *is_private);
}
- if let Some(precompiled) = pending.precompiled_function.take() {
- shared.set_precompiled_bytecode_executable(precompiled);
+ if let Some(precompiled) = &pending.precompiled_function {
+ shared.set_precompiled_bytecode_executable(precompiled.clone());
}
shared
}
@@ -643,7 +503,6 @@ impl SharedFunctionInstanceData {
}
pub fn set_source_text(&self, source_text: Utf16String) {
- self.preserve_bytecode_cache_source_text_range();
self.rare_data().source_text_owner.replace(source_text);
self.storage.source_code.set(None);
self.storage.source_text_offset.set(0);
@@ -656,7 +515,6 @@ impl SharedFunctionInstanceData {
source_text_offset: usize,
source_text_length: usize,
) {
- self.preserve_bytecode_cache_source_text_range();
self.rare_data().source_text_owner.replace(Utf16String::default());
self.storage.source_code.set(Some(source_code.clone()));
self.initialize_source_text_range(source_text_offset, source_text_length);
@@ -672,58 +530,11 @@ impl SharedFunctionInstanceData {
self.storage.compile_input.set(CompileInput::None);
}
- pub fn clear_non_bytecode_cache_compile_inputs(&self) {
- if self.storage.compile_input.tag() != CompileInputSlot::TAG_CACHED_BYTECODE {
- self.clear_compile_inputs();
- }
- }
-
- /// Whether the function still has the AST it compiles from when it is first called.
- pub fn has_function_ast(&self) -> bool {
- self.storage.compile_input.tag() == CompileInputSlot::TAG_FUNCTION_AST
- }
-
- /// Whether the function still has bytecode compiled ahead of its first call, apart from that of a bytecode cache.
- pub fn has_precompiled_bytecode(&self) -> bool {
- self.storage.compile_input.tag() == CompileInputSlot::TAG_PRECOMPILED_BYTECODE
- }
-
- /// Whether the function's executable is still in a bytecode cache blob, waiting for its first call.
- pub fn has_cached_bytecode(&self) -> bool {
- self.storage.compile_input.tag() == CompileInputSlot::TAG_CACHED_BYTECODE
- }
-
- /// Appends the functions that `executable` creates and that have not been compiled yet to `functions`, and returns
- /// a copy of the AST of each, so that they can be compiled elsewhere, such as on another thread, while their own
- /// ASTs stay in place for a first call that comes sooner.
- pub fn uncompiled_functions_of(
- executable: Gc<Executable>,
- functions: &MarkedVec<'_, Gc<SharedFunctionInstanceData>>,
- ) -> Vec<Box<FunctionPayload>> {
- let mut function_asts = Vec::new();
- for index in 0..executable.shared_function_data_count() {
- let shared_data = executable.shared_function_data(u32::try_from(index).expect("the index fits in u32"));
- if shared_data.executable().is_some() {
- continue;
- }
- if !shared_data.has_function_ast() {
- continue;
- }
- let CompileInput::FunctionAst(function_ast) = shared_data.storage.compile_input.take() else {
- unreachable!("the function has its AST");
- };
- functions.push(shared_data);
- function_asts.push(function_ast.clone());
- shared_data
- .storage
- .compile_input
- .set(CompileInput::FunctionAst(function_ast));
- }
- function_asts
- }
-
/// Records what scope analysis found out about the function's body, as rust_sfd_set_metadata does.
pub fn set_metadata(&self, metadata: &FunctionSfdMetadata) {
+ if let Some(parameter_names) = parameter_names_of(&metadata.parameter_names) {
+ let _ = self.storage.parameter_names.set(parameter_names);
+ }
self.set_uses_this(metadata.uses_this);
self.set_metadata_bit(
asm_call_metadata::THIS_VALUE_NEEDS_ENVIRONMENT_RESOLUTION,
@@ -747,7 +558,7 @@ impl SharedFunctionInstanceData {
/// Keeps bytecode the frontend compiled ahead of the first call, as rust_sfd_set_precompiled_bytecode_executable
/// does.
- pub fn set_precompiled_bytecode_executable(&self, precompiled: Box<PrecompiledFunction>) {
+ pub fn set_precompiled_bytecode_executable(&self, precompiled: Arc<PrecompiledFunction>) {
self.set_metadata(&precompiled.metadata);
self.storage
.compile_input
@@ -808,14 +619,14 @@ impl SharedFunctionInstanceData {
}
pub fn mapped_argument_names(&self) -> Rc<[Utf16FlyString]> {
- self.storage.parameter_names.as_ref().map_or_else(
+ self.storage.parameter_names.get().map_or_else(
|| Vm::of_cell(self).no_parameter_names.clone(),
|names| names.mapped_argument_names.clone(),
)
}
pub fn parameter_binding_names(&self) -> Rc<[Utf16FlyString]> {
- self.storage.parameter_names.as_ref().map_or_else(
+ self.storage.parameter_names.get().map_or_else(
|| Vm::of_cell(self).no_parameter_names.clone(),
|names| names.parameter_binding_names.clone(),
)
@@ -978,43 +789,39 @@ impl SharedFunctionInstanceData {
}
/// RustIntegration::compile_function(): the function's executable, from the bytecode compiled ahead of time if
- /// there is some, and otherwise compiled from its AST now.
+ /// there is some, and otherwise parsed and compiled now. Running out of stack on the way is a RangeError, like
+ /// running out of stack in the call that got here.
pub fn compile_function(
vm: &Vm,
shared_data: Gc<SharedFunctionInstanceData>,
builtin_abstract_operations_enabled: bool,
- ) -> Option<Gc<Executable>> {
+ ) -> ThrowCompletionOr<Gc<Executable>> {
let source_code = shared_data.source_code();
let payload = match shared_data.storage.compile_input.take() {
CompileInput::PrecompiledBytecode(precompiled) => {
- return Some(Executable::create_with_source_code(
+ // NB: This stays the only reference to the code if nothing else holds the function.
+ let executable = Arc::try_unwrap(precompiled)
+ .map_or_else(|shared| shared.executable.clone(), |unique| unique.executable);
+ return Ok(Executable::create_with_source_code(
vm,
- precompiled.executable,
+ executable,
source_code.as_ref(),
));
}
- CompileInput::CachedBytecode(cached_executable) => {
- let source_code = source_code.expect("a function of a bytecode cache blob has its source code");
- return materialize_cached_function_executable(vm, &cached_executable, &source_code);
- }
- CompileInput::FunctionAst(payload) => payload,
- CompileInput::None => panic!("a function that was not compiled yet has its AST"),
+ CompileInput::Unparsed(payload) => payload,
+ CompileInput::None => panic!("a function that was not compiled yet knows how to compile"),
+ };
+ let precompiled =
+ crate::compile::compile_function(&payload, builtin_abstract_operations_enabled, vm.native_stack_limit());
+ let Ok(precompiled) = precompiled else {
+ shared_data.storage.compile_input.set(CompileInput::Unparsed(payload));
+ return vm.throw_completion(ErrorKind::RangeError, ErrorType::CallStackSizeExceeded, &[]);
};
- // NB: The frontend checks that nested functions lie within the source, which is unknown without a source code.
- let source_length = source_code
- .as_ref()
- .map_or(usize::MAX, |source_code| source_code.length_in_code_units());
- let precompiled = crate::compile::compile_function(
- payload,
- source_length,
- builtin_abstract_operations_enabled,
- FunctionPrecompileMode::EagerOnly,
- );
shared_data.set_metadata(&precompiled.metadata);
- Some(Executable::create_with_source_code(
+ Ok(Executable::create_with_source_code(
vm,
precompiled.executable,
source_code.as_ref(),
diff --git a/Libraries/LibJS/Rust/src/runtime/source_text_module.rs b/Libraries/LibJS/Rust/src/runtime/source_text_module.rs
index e3d48dcddc4..763d9e3a35f 100644
--- a/Libraries/LibJS/Rust/src/runtime/source_text_module.rs
+++ b/Libraries/LibJS/Rust/src/runtime/source_text_module.rs
@@ -12,13 +12,9 @@ use ak::{ScopeGuard, Utf16FlyString};
use libjs_runtime_macros::Trace;
use crate::ast::ProgramType;
-use crate::bytecode::bytecode_cache::{
- BytecodeCacheInstall, DecodedBytecodeCache, ExecutableBacking, create_executable_and_its_functions,
- failed_to_materialize_bytecode_cache, functions_created_by, have_only_bytecode_cache_compile_inputs,
-};
use crate::bytecode::executable::Executable;
-use crate::bytecode_cache::{DecodedDeclarationMetadata, ModuleExportEntryRecord, ModuleRequestRecord};
use crate::compile::{CompiledModule, ModuleDeclarations, ParsedProgram, compile_module, parse};
+use crate::fast_hash::HashSet;
use crate::gc::class::{GcCell, define_cell};
use crate::gc::foreign::ForeignCellSlot;
use crate::gc::gc_ref_cell::GcRefCell;
@@ -49,6 +45,7 @@ use crate::runtime::private_environment::PrivateEnvironment;
use crate::runtime::promise_capability::PromiseCapability;
use crate::runtime::shared_function_instance_data::{FunctionKind, SharedFunctionInstanceData};
use crate::source_code::SourceCode;
+use crate::utf16::Utf16View;
/// SourceTextModule::FunctionToInitialize.
#[derive(Trace)]
@@ -104,30 +101,11 @@ pub struct SourceTextModule {
executable: Cell<Option<Gc<Executable>>>,
tla_shared_data: Option<Gc<SharedFunctionInstanceData>>,
- #[gc(untraced)]
- executable_backing: Cell<ExecutableBacking>,
/// What the module's functions compile themselves from when they are first called.
#[gc(untraced)]
source_code: Rc<SourceCode>,
}
-/// What a Source Text Module Record is made of, however its code was compiled.
-struct SourceTextModuleParts {
- has_top_level_await: bool,
- requested_modules: Vec<ModuleRequest>,
- import_entries: Vec<ImportEntry>,
- local_export_entries: Vec<ExportEntry>,
- indirect_export_entries: Vec<ExportEntry>,
- star_export_entries: Vec<ExportEntry>,
- var_declared_names: Vec<Utf16FlyString>,
- lexical_bindings: Vec<LexicalBinding>,
- function_names: Vec<Utf16FlyString>,
- default_export_binding_name: Option<Utf16FlyString>,
- /// The body, or the body of the async function that a module with top-level await runs.
- executable: Gc<Executable>,
- executable_backing: ExecutableBacking,
-}
-
define_cell!(SourceTextModule, Other, extends: [CyclicModule, Module]);
impl Deref for SourceTextModule {
@@ -157,13 +135,13 @@ fn as_source_text_module(module: &Module) -> &SourceTextModule {
.expect("only Source Text Module Records have the methods of source text modules")
}
-fn fly_string_of(name: &crate::ast::Utf16String) -> Utf16FlyString {
- Utf16FlyString::from_utf16(&name.0)
+fn fly_string_of(name: &ak::Utf16String) -> Utf16FlyString {
+ Utf16View::of_string(name).to_utf16_fly_string()
}
-fn export_entries_of(entries: Vec<crate::compile::ModuleExportEntry>) -> Vec<ExportEntry> {
+fn export_entries_of(entries: &[crate::compile::ModuleExportEntry]) -> Vec<ExportEntry> {
entries
- .into_iter()
+ .iter()
.map(|entry| ExportEntry {
kind: entry.kind,
export_name: entry.export_name.as_ref().map(fly_string_of),
@@ -194,10 +172,7 @@ impl SourceTextModule {
host_defined: ForeignCellSlot,
line_number_offset: usize,
) -> Result<Gc<SourceTextModule>, Vec<ParserError>> {
- let source = source_code.code().to_utf16();
- let source_length = source.len();
- let parsed = parse(&source, ProgramType::Module, line_number_offset);
- drop(source);
+ let parsed = parse(source_code.code(), ProgramType::Module, line_number_offset);
if parsed.has_errors() {
return Err(ParserError::all_from_parsed_program(&parsed));
}
@@ -205,10 +180,9 @@ impl SourceTextModule {
vm,
realm,
filename,
- compile_module(parsed, source_length),
+ compile_module(parsed),
source_code,
host_defined,
- ExecutableBacking::Source,
))
}
@@ -222,21 +196,18 @@ impl SourceTextModule {
filename: &str,
) -> Gc<SourceTextModule> {
assert!(parsed.program_type() == ProgramType::Module && !parsed.has_errors());
- let source_length = source_code.length_in_code_units();
Self::create(
vm,
realm,
filename,
- compile_module(parsed, source_length),
+ compile_module(parsed),
source_code,
ForeignCellSlot::empty(),
- ExecutableBacking::Source,
)
}
/// The Source Text Module Record of a module compiled, on any thread, from the code of `source_code`, whose
/// filename the module's code reports. Module loading resolves the module's imports against `filename`.
- /// `executable_backing` says where it was compiled.
pub fn create(
vm: &Vm,
realm: Gc<Realm>,
@@ -244,7 +215,6 @@ impl SourceTextModule {
compiled: CompiledModule,
source_code: Rc<SourceCode>,
host_defined: ForeignCellSlot,
- executable_backing: ExecutableBacking,
) -> Gc<SourceTextModule> {
let CompiledModule {
executable,
@@ -261,10 +231,11 @@ impl SourceTextModule {
functions_to_initialize,
lexical_bindings,
requested_modules,
- } = declarations;
+ } = &*declarations;
+ let has_top_level_await = *has_top_level_await;
let import_entries = import_entries
- .into_iter()
+ .iter()
.map(|entry| ImportEntry {
import_name: entry.import_name.as_ref().map(fly_string_of),
local_name: fly_string_of(&entry.local_name),
@@ -276,13 +247,13 @@ impl SourceTextModule {
let rooted_shared_data = MarkedVec::with_capacity(vm, functions_to_initialize.len());
let mut function_names = Vec::with_capacity(functions_to_initialize.len());
for function in functions_to_initialize {
- let mut description = function.description;
- // NB: The shared data of an anonymous default export takes the name the module binds it under, from which
- // the function's name is all that follows.
- if function.is_anonymous_default_export {
- description.name.clone_from(&function.name.0);
- }
- rooted_shared_data.push(SharedFunctionInstanceData::create(vm, description, Some(&source_code)));
+ let description = &function.description;
+ rooted_shared_data.push(SharedFunctionInstanceData::create(
+ vm,
+ description,
+ description.strict,
+ Some(&source_code),
+ ));
function_names.push(fly_string_of(&function.name));
}
@@ -298,150 +269,10 @@ impl SourceTextModule {
let requested_modules = requested_modules.iter().map(ModuleRequest::from_frontend).collect();
let executable = Executable::create_with_source_code(vm, executable, Some(&source_code));
- Self::allocate(
- vm,
- realm,
- filename,
- SourceTextModuleParts {
- has_top_level_await,
- requested_modules,
- import_entries,
- local_export_entries: export_entries_of(local_export_entries),
- indirect_export_entries: export_entries_of(indirect_export_entries),
- star_export_entries: export_entries_of(star_export_entries),
- var_declared_names: var_names.iter().map(fly_string_of).collect(),
- lexical_bindings,
- function_names,
- default_export_binding_name: default_export_binding_name.as_ref().map(fly_string_of),
- executable,
- executable_backing,
- },
- &rooted_shared_data,
- source_code,
- host_defined,
- )
- }
-
- /// SourceTextModule::parse_from_bytecode_cache(): the Source Text Module Record of a module from a bytecode cache
- /// blob of its code, which the blob must match. Its executables run in place in the blob, and its functions
- /// compile from the blob when they are first called. Fails with a single error if the blob does not match the
- /// source code or turns out to be malformed.
- pub fn create_from_bytecode_cache(
- vm: &Vm,
- realm: Gc<Realm>,
- filename: &str,
- bytecode_cache: &DecodedBytecodeCache,
- source_code: Rc<SourceCode>,
- host_defined: ForeignCellSlot,
- ) -> Result<Gc<SourceTextModule>, Vec<ParserError>> {
- let blob = bytecode_cache
- .validated_blob(source_code.length_in_code_units())
- .ok_or_else(failed_to_materialize_bytecode_cache)?;
- let DecodedDeclarationMetadata::Module {
- metadata,
- declaration_functions,
- } = blob.declaration_metadata()
- else {
- return Err(failed_to_materialize_bytecode_cache());
- };
- let program = blob.program();
- if program.is_async_module() != blob.has_top_level_await()
- || declaration_functions.len() != metadata.function_names.len()
- {
- return Err(failed_to_materialize_bytecode_cache());
- }
-
- let module_request_of = |request: Option<&ModuleRequestRecord>| {
- ModuleRequest::of_entry_from_frontend(request.map(crate::ast::ModuleRequest::from).as_ref())
- };
- let import_entries = metadata
- .import_entries
- .iter()
- .map(|entry| ImportEntry {
- import_name: entry.import_name.as_ref().map(fly_string_of),
- local_name: fly_string_of(&entry.local_name),
- module_request: module_request_of(Some(&entry.module_request)),
- })
- .collect();
- let export_entries_of_records = |entries: &[ModuleExportEntryRecord]| {
- entries
- .iter()
- .map(|entry| ExportEntry {
- kind: entry.kind,
- export_name: entry.export_name.as_ref().map(fly_string_of),
- local_or_import_name: entry.local_or_import_name.as_ref().map(fly_string_of),
- module_request: module_request_of(entry.module_request.as_ref()),
- })
- .collect()
- };
- let requested_modules = metadata
- .requested_modules
- .iter()
- .map(|request| ModuleRequest::from_frontend(&crate::ast::ModuleRequest::from(request)))
- .collect();
- let lexical_bindings = metadata
- .lexical_bindings
- .iter()
- .map(|binding| LexicalBinding {
- name: fly_string_of(&binding.name),
- is_constant: binding.is_constant,
- function_index: usize::try_from(binding.function_index).ok(),
- })
- .collect();
-
- // The functions stay rooted until the module that holds them is allocated.
- let rooted_shared_data = MarkedVec::with_capacity(vm, declaration_functions.len());
- for function in declaration_functions {
- rooted_shared_data.push(SharedFunctionInstanceData::create_from_bytecode_cache(
- vm,
- function,
- true,
- &source_code,
- ));
- }
- let executable = create_executable_and_its_functions(vm, program.executable(), &source_code)
- .ok_or_else(failed_to_materialize_bytecode_cache)?;
-
- Ok(Self::allocate(
- vm,
- realm,
- filename,
- SourceTextModuleParts {
- has_top_level_await: blob.has_top_level_await(),
- requested_modules,
- import_entries,
- local_export_entries: export_entries_of_records(&metadata.local_exports),
- indirect_export_entries: export_entries_of_records(&metadata.indirect_exports),
- star_export_entries: export_entries_of_records(&metadata.star_exports),
- var_declared_names: metadata.var_declared_names.iter().map(fly_string_of).collect(),
- lexical_bindings,
- function_names: metadata.function_names.iter().map(fly_string_of).collect(),
- default_export_binding_name: metadata.default_export_binding_name.as_ref().map(fly_string_of),
- executable,
- executable_backing: ExecutableBacking::MappedBytecodeCache,
- },
- &rooted_shared_data,
- source_code,
- host_defined,
- ))
- }
-
- fn allocate(
- vm: &Vm,
- realm: Gc<Realm>,
- filename: &str,
- parts: SourceTextModuleParts,
- rooted_shared_data: &MarkedVec<'_, Gc<SharedFunctionInstanceData>>,
- source_code: Rc<SourceCode>,
- host_defined: ForeignCellSlot,
- ) -> Gc<SourceTextModule> {
- let (executable, tla_shared_data) = if parts.has_top_level_await {
- (
- None,
- Some(Self::create_top_level_await_shared_data(vm, parts.executable)),
- )
+ let (executable, tla_shared_data) = if has_top_level_await {
+ (None, Some(Self::create_top_level_await_shared_data(vm, executable)))
} else {
- (Some(parts.executable), None)
+ (Some(executable), None)
};
let module = vm.heap().allocate(|defer_gc| SourceTextModule {
@@ -450,35 +281,33 @@ impl SourceTextModule {
Self::CLASS,
realm,
filename.to_string(),
- parts.has_top_level_await,
- parts.requested_modules,
+ has_top_level_await,
+ requested_modules,
host_defined,
),
execution_context: OwnedExecutionContext::create(0, 0, 0),
import_meta: Cell::new(None),
- import_entries: parts.import_entries,
- local_export_entries: parts.local_export_entries,
- indirect_export_entries: parts.indirect_export_entries,
- star_export_entries: parts.star_export_entries,
+ import_entries,
+ local_export_entries: export_entries_of(local_export_entries),
+ indirect_export_entries: export_entries_of(indirect_export_entries),
+ star_export_entries: export_entries_of(star_export_entries),
imported_bindings: GcRefCell::new(Vec::new()),
- var_declared_names: parts.var_declared_names,
- lexical_bindings: parts.lexical_bindings,
+ var_declared_names: var_names.iter().map(fly_string_of).collect(),
+ lexical_bindings,
functions_to_initialize: rooted_shared_data
.values()
.iter()
- .zip(parts.function_names)
+ .zip(function_names)
.map(|(&shared_data, name)| FunctionToInitialize { shared_data, name })
.collect(),
- default_export_binding_name: parts.default_export_binding_name,
+ default_export_binding_name: default_export_binding_name.as_ref().map(fly_string_of),
executable: Cell::new(executable),
tla_shared_data,
- executable_backing: Cell::new(parts.executable_backing),
source_code,
});
assert!(
module.executable.get().is_some() || module.tla_shared_data.is_some_and(|data| data.executable().is_some())
);
- module.verify_executable_backing_invariants(vm);
module
}
@@ -487,7 +316,7 @@ impl SourceTextModule {
vm: &Vm,
top_level_await_executable: Gc<Executable>,
) -> Gc<SharedFunctionInstanceData> {
- let tla_shared_data = SharedFunctionInstanceData::create_without_function_ast(
+ let tla_shared_data = SharedFunctionInstanceData::create_without_compile_input(
vm,
FunctionKind::Async,
Utf16FlyString::from_utf8("module code with top-level await"),
@@ -505,162 +334,6 @@ impl SourceTextModule {
tla_shared_data
}
- pub fn executable_backing(&self) -> ExecutableBacking {
- self.executable_backing.get()
- }
-
- fn has_executable(&self) -> bool {
- self.executable.get().is_some() || self.tla_shared_data.is_some_and(|data| data.executable().is_some())
- }
-
- pub fn can_generate_bytecode_cache(&self) -> bool {
- self.has_executable() && self.executable_backing.get().can_generate_bytecode_cache()
- }
-
- pub fn can_install_generated_bytecode_cache(&self) -> bool {
- self.has_executable() && self.executable_backing.get().can_install_generated_bytecode_cache()
- }
-
- /// Marks the module as one whose bytecode cache is being generated, until the cache is installed or the
- /// generation finishes without installing it.
- ///
- /// # Panics
- /// Panics unless the module can generate a bytecode cache.
- pub fn begin_bytecode_cache_generation(&self, vm: &Vm) {
- assert!(
- self.has_executable(),
- "a module that generates a bytecode cache has an executable"
- );
- self.executable_backing
- .set(self.executable_backing.get().with_bytecode_cache_generation_begun());
- self.verify_executable_backing_invariants(vm);
- }
-
- /// # Panics
- /// Panics unless a bytecode cache is being generated for the module.
- pub fn finish_bytecode_cache_generation_without_install(&self, vm: &Vm) {
- self.executable_backing.set(
- self.executable_backing
- .get()
- .with_bytecode_cache_generation_finished_without_install(),
- );
- self.verify_executable_backing_invariants(vm);
- }
-
- /// SourceTextModule::try_install_bytecode_cache(): like Script::try_install_bytecode_cache(), for a module, whose
- /// body is that of the async function of a module with top-level await.
- pub fn try_install_bytecode_cache(
- &self,
- vm: &Vm,
- bytecode_cache: &DecodedBytecodeCache,
- source_code: &Rc<SourceCode>,
- ) -> bool {
- if self.executable_backing.get().is_mapped_bytecode_cache() {
- return false;
- }
- let Some(blob) = bytecode_cache.validated_blob(source_code.length_in_code_units()) else {
- return false;
- };
- let DecodedDeclarationMetadata::Module {
- metadata,
- declaration_functions,
- } = blob.declaration_metadata()
- else {
- return false;
- };
- if declaration_functions.len() != metadata.function_names.len() {
- return false;
- }
-
- let existing_functions = self.functions_created_so_far(vm);
- let mut install = BytecodeCacheInstall::new(vm, source_code, &existing_functions);
- for function in declaration_functions {
- if install.prepare_function(function, true).is_none() {
- return false;
- }
- }
- let program = blob.program();
- let replaced_executable = if program.is_async_module() {
- if !blob.has_top_level_await() {
- return false;
- }
- let Some(top_level_await_executable) = self.tla_shared_data.and_then(|data| data.executable()) else {
- return false;
- };
- top_level_await_executable
- } else {
- if blob.has_top_level_await() {
- return false;
- }
- let Some(executable) = self.executable.get() else {
- return false;
- };
- executable
- };
- let Some(executable) = install.prepare_executable(program.executable(), Some(replaced_executable)) else {
- return false;
- };
- if !install.commit() {
- return false;
- }
-
- match self.tla_shared_data {
- Some(tla_shared_data) if program.is_async_module() => {
- tla_shared_data.set_executable(Some(executable));
- tla_shared_data.clear_non_bytecode_cache_compile_inputs();
- }
- _ => self.executable.set(Some(executable)),
- }
- for function in existing_functions.values().iter() {
- function.clear_non_bytecode_cache_compile_inputs();
- }
- self.executable_backing.set(ExecutableBacking::MappedBytecodeCache);
- self.verify_executable_backing_invariants(vm);
- true
- }
-
- /// SourceTextModule::install_generated_bytecode_cache(): installs the bytecode cache that was generated for the
- /// module.
- ///
- /// # Panics
- /// Panics unless a bytecode cache is being generated for the module, and if the blob does not match it.
- pub fn install_generated_bytecode_cache(
- &self,
- vm: &Vm,
- bytecode_cache: &DecodedBytecodeCache,
- source_code: &Rc<SourceCode>,
- ) {
- assert!(
- self.can_install_generated_bytecode_cache(),
- "a bytecode cache is being generated for the module"
- );
- assert!(
- self.try_install_bytecode_cache(vm, bytecode_cache, source_code),
- "the bytecode cache generated for a module matches it"
- );
- }
-
- fn functions_created_so_far<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, Gc<SharedFunctionInstanceData>> {
- let body = self
- .executable
- .get()
- .or_else(|| self.tla_shared_data.and_then(|data| data.executable()));
- functions_created_by(
- vm,
- self.functions_to_initialize.iter().map(|function| function.shared_data),
- body,
- )
- }
-
- fn verify_executable_backing_invariants(&self, vm: &Vm) {
- if self.executable_backing.get().is_mapped_bytecode_cache() {
- assert!(
- have_only_bytecode_cache_compile_inputs(&self.functions_created_so_far(vm)),
- "the functions of a module with a bytecode cache compile from the cache"
- );
- }
- }
-
pub fn import_meta(&self) -> Option<Gc<Object>> {
self.import_meta.get()
}
@@ -906,7 +579,9 @@ impl SourceTextModule {
// 19. Let varDeclarations be the VarScopedDeclarations of code.
// 20. Let declaredVarNames be a new empty List.
- let mut declared_var_names: Vec<Utf16FlyString> = Vec::new();
+ // OPTIMIZATION: A set, as a bundled module can declare tens of thousands of names.
+ let mut declared_var_names =
+ HashSet::with_capacity_and_hasher(self.var_declared_names.len(), Default::default());
// 21. For each element d of varDeclarations, do
// a. For each element dn of the BoundNames of d, do
@@ -922,7 +597,7 @@ impl SourceTextModule {
.must();
// 3. Append dn to declaredVarNames.
- declared_var_names.push(name.clone());
+ declared_var_names.insert(name.clone());
}
}
diff --git a/Libraries/LibJS/Rust/src/script.rs b/Libraries/LibJS/Rust/src/script.rs
index ace1666f128..46033399948 100644
--- a/Libraries/LibJS/Rust/src/script.rs
+++ b/Libraries/LibJS/Rust/src/script.rs
@@ -13,13 +13,8 @@ use std::rc::Rc;
use ak::Utf16FlyString;
use libjs_runtime_macros::Trace;
-use crate::ast::{ProgramType, Utf16String};
-use crate::bytecode::bytecode_cache::{
- BytecodeCacheInstall, DecodedBytecodeCache, ExecutableBacking, create_executable_and_its_functions,
- failed_to_materialize_bytecode_cache, functions_created_by, have_only_bytecode_cache_compile_inputs,
-};
+use crate::ast::ProgramType;
use crate::bytecode::executable::Executable;
-use crate::bytecode_cache::DecodedDeclarationMetadata;
use crate::compile::{CompiledScript, ParsedProgram, compile_script, parse};
use crate::gc::class::{GcCell, define_cell};
use crate::gc::foreign::ForeignCellSlot;
@@ -40,6 +35,7 @@ use crate::runtime::module_request::LoadedModuleRequest;
use crate::runtime::private_environment::PrivateEnvironment;
use crate::runtime::shared_function_instance_data::SharedFunctionInstanceData;
use crate::source_code::SourceCode;
+use ak::Utf16String;
/// Script::FunctionToInitialize.
#[derive(Trace)]
@@ -64,8 +60,6 @@ pub struct Script {
loaded_modules: GcRefCell<Vec<LoadedModuleRequest>>, // [[LoadedModules]]
host_defined: ForeignCellSlot, // [[HostDefined]]
executable: Cell<Gc<Executable>>,
- #[gc(untraced)]
- executable_backing: Cell<ExecutableBacking>,
/// What the script's functions compile themselves from when they are first called.
#[gc(untraced)]
source_code: Rc<SourceCode>,
@@ -90,28 +84,16 @@ pub struct Script {
define_cell!(Script, Other);
fn fly_string_of(name: &Utf16String) -> Utf16FlyString {
- Utf16FlyString::from_utf16(&name.0)
+ crate::utf16::Utf16View::of_string(name).to_utf16_fly_string()
}
fn fly_strings_of(names: &[Utf16String]) -> Vec<Utf16FlyString> {
names.iter().map(fly_string_of).collect()
}
-/// What a Script Record is made of, however its code was compiled.
-struct ScriptParts {
- executable: Gc<Executable>,
- executable_backing: ExecutableBacking,
- function_names: Vec<Utf16FlyString>,
- lexical_names: Vec<Utf16FlyString>,
- var_names: Vec<Utf16FlyString>,
- var_scoped_names: Vec<Utf16FlyString>,
- annex_b_candidate_names: Vec<Utf16FlyString>,
- lexical_bindings: Vec<LexicalBinding>,
-}
-
impl Script {
// 16.1.5 ParseScript ( sourceText, realm, hostDefined ), https://tc39.es/ecma262/#sec-parse-script
- pub fn parse(vm: &Vm, source: &[u16], realm: Gc<Realm>) -> Result<Gc<Script>, Vec<ParserError>> {
+ pub fn parse(vm: &Vm, source: &ak::Utf16String, realm: Gc<Realm>) -> Result<Gc<Script>, Vec<ParserError>> {
Self::parse_with_filename(vm, source, realm, "")
}
@@ -119,7 +101,7 @@ impl Script {
/// specifiers of its dynamic imports against.
pub fn parse_with_filename(
vm: &Vm,
- source: &[u16],
+ source: &ak::Utf16String,
realm: Gc<Realm>,
filename: &str,
) -> Result<Gc<Script>, Vec<ParserError>> {
@@ -139,7 +121,7 @@ impl Script {
/// [[HostDefined]].
pub fn parse_with_host_defined(
vm: &Vm,
- source: &[u16],
+ source: &ak::Utf16String,
realm: Gc<Realm>,
filename: &str,
display_filename: ak::Utf16String,
@@ -155,36 +137,17 @@ impl Script {
} else {
display_filename
};
- let source_code = SourceCode::create(display_filename, ak::Utf16String::from_utf16(source));
- let source_length = source_code.length_in_code_units();
+ let source_code = SourceCode::create(display_filename, source.clone());
Ok(Self::create(
vm,
realm,
- compile_script(parsed, source_length),
+ compile_script(parsed),
source_code,
filename,
host_defined,
- ExecutableBacking::Source,
))
}
- /// Compiles a script the caller parsed without errors from `source`.
- pub fn compile_parsed_program(vm: &Vm, parsed: ParsedProgram, source: &[u16], realm: Gc<Realm>) -> Gc<Script> {
- Self::compile_parsed_program_with_filename(vm, parsed, source, realm, ak::Utf16String::default())
- }
-
- /// Compiles a script the caller parsed without errors from `source`, which came from `filename`.
- pub fn compile_parsed_program_with_filename(
- vm: &Vm,
- parsed: ParsedProgram,
- source: &[u16],
- realm: Gc<Realm>,
- filename: ak::Utf16String,
- ) -> Gc<Script> {
- let source_code = SourceCode::create(filename, ak::Utf16String::from_utf16(source));
- Self::create_from_parsed(vm, parsed, source_code, realm)
- }
-
/// Compiles a script the caller parsed without errors from the code of `source_code`, whose filename the
/// script's code reports.
pub fn create_from_parsed(
@@ -207,21 +170,18 @@ impl Script {
filename: &str,
) -> Gc<Script> {
assert!(parsed.program_type() == ProgramType::Script && !parsed.has_errors());
- let source_length = source_code.length_in_code_units();
Self::create(
vm,
realm,
- compile_script(parsed, source_length),
+ compile_script(parsed),
source_code,
filename,
ForeignCellSlot::empty(),
- ExecutableBacking::Source,
)
}
/// The Script Record of a script compiled, on any thread, from the code of `source_code`, whose filename the
/// script's code reports. Module loading resolves the specifiers of its dynamic imports against `filename`.
- /// `executable_backing` says where it was compiled.
pub fn create(
vm: &Vm,
realm: Gc<Realm>,
@@ -229,7 +189,6 @@ impl Script {
source_code: Rc<SourceCode>,
filename: &str,
host_defined: ForeignCellSlot,
- executable_backing: ExecutableBacking,
) -> Gc<Script> {
let CompiledScript {
executable,
@@ -241,10 +200,10 @@ impl Script {
// The functions stay rooted until the script that holds them is allocated.
let rooted_shared_data = MarkedVec::with_capacity(vm, declarations.functions_to_initialize.len());
let mut function_names = Vec::with_capacity(declarations.functions_to_initialize.len());
- for mut function in declarations.functions_to_initialize {
+ for function in &declarations.functions_to_initialize {
rooted_shared_data.push(SharedFunctionInstanceData::create_from_pending_shared_function_data(
vm,
- &mut function.shared_function_data,
+ &function.shared_function_data,
is_strict,
Some(&source_code),
));
@@ -259,132 +218,32 @@ impl Script {
})
.collect();
- Self::allocate(
- vm,
- realm,
- ScriptParts {
- executable,
- executable_backing,
- function_names,
- lexical_names: fly_strings_of(&declarations.lexical_names),
- var_names: fly_strings_of(&declarations.var_names),
- var_scoped_names: fly_strings_of(&declarations.var_scoped_names),
- annex_b_candidate_names: fly_strings_of(&declarations.annex_b_candidate_names),
- lexical_bindings,
- },
- &rooted_shared_data,
- source_code,
- filename,
- host_defined,
- )
- }
-
- /// Script::create_from_bytecode_cache(): the Script Record of a classic script from a bytecode cache blob of its
- /// code, which the blob must match. Its executables run in place in the blob, and its functions compile from the
- /// blob when they are first called. Fails with a single error if the blob does not match the source code or turns
- /// out to be malformed.
- pub fn create_from_bytecode_cache(
- vm: &Vm,
- realm: Gc<Realm>,
- bytecode_cache: &DecodedBytecodeCache,
- source_code: Rc<SourceCode>,
- filename: &str,
- host_defined: ForeignCellSlot,
- ) -> Result<Gc<Script>, Vec<ParserError>> {
- let blob = bytecode_cache
- .validated_blob(source_code.length_in_code_units())
- .ok_or_else(failed_to_materialize_bytecode_cache)?;
- let DecodedDeclarationMetadata::Script {
- metadata,
- declaration_functions,
- } = blob.declaration_metadata()
- else {
- return Err(failed_to_materialize_bytecode_cache());
- };
- let program = blob.program();
- if program.is_async_module() || declaration_functions.len() != metadata.function_names.len() {
- return Err(failed_to_materialize_bytecode_cache());
- }
-
- // The functions stay rooted until the script that holds them is allocated.
- let rooted_shared_data = MarkedVec::with_capacity(vm, declaration_functions.len());
- for function in declaration_functions {
- rooted_shared_data.push(SharedFunctionInstanceData::create_from_bytecode_cache(
- vm,
- function,
- blob.is_strict_mode(),
- &source_code,
- ));
- }
- let executable = create_executable_and_its_functions(vm, program.executable(), &source_code)
- .ok_or_else(failed_to_materialize_bytecode_cache)?;
- let lexical_bindings = metadata
- .lexical_bindings
- .iter()
- .map(|binding| LexicalBinding {
- name: fly_string_of(&binding.name),
- is_constant: binding.is_constant,
- })
- .collect();
-
- Ok(Self::allocate(
- vm,
- realm,
- ScriptParts {
- executable,
- executable_backing: ExecutableBacking::MappedBytecodeCache,
- function_names: fly_strings_of(&metadata.function_names),
- lexical_names: fly_strings_of(&metadata.lexical_names),
- var_names: fly_strings_of(&metadata.var_names),
- var_scoped_names: fly_strings_of(&metadata.var_scoped_names),
- annex_b_candidate_names: fly_strings_of(&metadata.annex_b_candidate_names),
- lexical_bindings,
- },
- &rooted_shared_data,
- source_code,
- filename,
- host_defined,
- ))
- }
-
- fn allocate(
- vm: &Vm,
- realm: Gc<Realm>,
- parts: ScriptParts,
- rooted_shared_data: &MarkedVec<'_, Gc<SharedFunctionInstanceData>>,
- source_code: Rc<SourceCode>,
- filename: &str,
- host_defined: ForeignCellSlot,
- ) -> Gc<Script> {
- let declared_function_names = parts.function_names.iter().cloned().collect();
+ let declared_function_names = function_names.iter().cloned().collect();
- let script = vm.heap().allocate(|_| Script {
+ vm.heap().allocate(|_| Script {
header: CellHeader::for_class(Self::CLASS),
realm,
loaded_modules: GcRefCell::new(Vec::new()),
host_defined,
- executable: Cell::new(parts.executable),
- executable_backing: Cell::new(parts.executable_backing),
+ executable: Cell::new(executable),
source_code,
- lexical_names: parts.lexical_names,
- var_names: parts.var_names,
+ lexical_names: fly_strings_of(&declarations.lexical_names),
+ var_names: fly_strings_of(&declarations.var_names),
functions_to_initialize: rooted_shared_data
.values()
.iter()
- .zip(parts.function_names)
+ .zip(function_names)
.map(|(&shared_data, name)| FunctionToInitialize { shared_data, name })
.collect(),
declared_function_names,
- var_scoped_names: parts.var_scoped_names,
- annex_b_candidate_names: parts.annex_b_candidate_names,
- lexical_bindings: parts.lexical_bindings,
+ var_scoped_names: fly_strings_of(&declarations.var_scoped_names),
+ annex_b_candidate_names: fly_strings_of(&declarations.annex_b_candidate_names),
+ lexical_bindings,
// NB: A script is never marked strict here, so Annex B function hoisting always runs; the frontend only
// collects candidates for sloppy scripts.
is_strict_mode: false,
filename: filename.to_string(),
- });
- script.verify_executable_backing_invariants(vm);
- script
+ })
}
pub fn realm(&self) -> Gc<Realm> {
@@ -407,129 +266,6 @@ impl Script {
self.executable.get()
}
- pub fn executable_backing(&self) -> ExecutableBacking {
- self.executable_backing.get()
- }
-
- pub fn can_generate_bytecode_cache(&self) -> bool {
- self.executable_backing.get().can_generate_bytecode_cache()
- }
-
- pub fn can_install_generated_bytecode_cache(&self) -> bool {
- self.executable_backing.get().can_install_generated_bytecode_cache()
- }
-
- /// Marks the script as one whose bytecode cache is being generated, until the cache is installed or the generation
- /// finishes without installing it.
- ///
- /// # Panics
- /// Panics unless the script can generate a bytecode cache.
- pub fn begin_bytecode_cache_generation(&self, vm: &Vm) {
- self.executable_backing
- .set(self.executable_backing.get().with_bytecode_cache_generation_begun());
- self.verify_executable_backing_invariants(vm);
- }
-
- /// # Panics
- /// Panics unless a bytecode cache is being generated for the script.
- pub fn finish_bytecode_cache_generation_without_install(&self, vm: &Vm) {
- self.executable_backing.set(
- self.executable_backing
- .get()
- .with_bytecode_cache_generation_finished_without_install(),
- );
- self.verify_executable_backing_invariants(vm);
- }
-
- /// Script::try_install_bytecode_cache(): from now on, the script and its functions run from the bytecode cache
- /// blob of its code, if the blob matches the source code and every function the script created so far. Functions
- /// that already ran get executables from the blob, which take over their inline caches; the others compile from
- /// the blob on their first call. Returns false and changes nothing otherwise, and for a script that already runs
- /// from a blob.
- pub fn try_install_bytecode_cache(
- &self,
- vm: &Vm,
- bytecode_cache: &DecodedBytecodeCache,
- source_code: &Rc<SourceCode>,
- ) -> bool {
- if self.executable_backing.get().is_mapped_bytecode_cache() {
- return false;
- }
- let Some(blob) = bytecode_cache.validated_blob(source_code.length_in_code_units()) else {
- return false;
- };
- let DecodedDeclarationMetadata::Script {
- metadata,
- declaration_functions,
- } = blob.declaration_metadata()
- else {
- return false;
- };
- let program = blob.program();
- if program.is_async_module() || declaration_functions.len() != metadata.function_names.len() {
- return false;
- }
-
- let existing_functions = self.functions_created_so_far(vm);
- let mut install = BytecodeCacheInstall::new(vm, source_code, &existing_functions);
- for function in declaration_functions {
- if install.prepare_function(function, blob.is_strict_mode()).is_none() {
- return false;
- }
- }
- let Some(executable) = install.prepare_executable(program.executable(), Some(self.executable.get())) else {
- return false;
- };
- if !install.commit() {
- return false;
- }
-
- self.executable.set(executable);
- for function in existing_functions.values().iter() {
- function.clear_non_bytecode_cache_compile_inputs();
- }
- self.executable_backing.set(ExecutableBacking::MappedBytecodeCache);
- self.verify_executable_backing_invariants(vm);
- true
- }
-
- /// Script::install_generated_bytecode_cache(): installs the bytecode cache that was generated for the script.
- ///
- /// # Panics
- /// Panics unless a bytecode cache is being generated for the script, and if the blob does not match it.
- pub fn install_generated_bytecode_cache(
- &self,
- vm: &Vm,
- bytecode_cache: &DecodedBytecodeCache,
- source_code: &Rc<SourceCode>,
- ) {
- assert!(
- self.can_install_generated_bytecode_cache(),
- "a bytecode cache is being generated for the script"
- );
- assert!(
- self.try_install_bytecode_cache(vm, bytecode_cache, source_code),
- "the bytecode cache generated for a script matches it"
- );
- }
-
- fn functions_created_so_far<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, Gc<SharedFunctionInstanceData>> {
- functions_created_by(
- vm,
- self.functions_to_initialize.iter().map(|function| function.shared_data),
- Some(self.executable.get()),
- )
- }
-
- fn verify_executable_backing_invariants(&self, vm: &Vm) {
- if self.executable_backing.get().is_mapped_bytecode_cache() {
- assert!(
- have_only_bytecode_cache_compile_inputs(&self.functions_created_so_far(vm)),
- "the functions of a script with a bytecode cache compile from the cache"
- );
- }
- }
-
pub fn functions_to_initialize(&self) -> &[FunctionToInitialize] {
&self.functions_to_initialize
}
diff --git a/Libraries/LibJS/Rust/src/test_host.rs b/Libraries/LibJS/Rust/src/test_host.rs
index 098cb932586..934f2d2366b 100644
--- a/Libraries/LibJS/Rust/src/test_host.rs
+++ b/Libraries/LibJS/Rust/src/test_host.rs
@@ -121,6 +121,13 @@ extern "C" fn ladybird_utf16_fly_string_from_utf8(data: *const u8, length: usize
fly_string_from_utf16(&string.encode_utf16().collect::<Vec<_>>())
}
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_utf16_string_from_utf8(data: *const u8, length: usize) -> usize {
+ // SAFETY: The frontend passes `length` readable bytes of UTF-8.
+ let string = std::str::from_utf8(unsafe { ak::slice_from_raw_parts(data, length) }).expect("valid UTF-8");
+ allocate_utf16_string(&string.encode_utf16().collect::<Vec<_>>())
+}
+
#[unsafe(no_mangle)]
extern "C" fn ladybird_utf16_string_create_uninitialized(length: usize, has_latin1_storage: bool) -> usize {
allocate_uninitialized_string(length, has_latin1_storage)
diff --git a/Libraries/LibJS/Rust/src/token.rs b/Libraries/LibJS/Rust/src/token.rs
index bae3856b596..796b1430def 100644
--- a/Libraries/LibJS/Rust/src/token.rs
+++ b/Libraries/LibJS/Rust/src/token.rs
@@ -195,7 +195,7 @@ pub struct Token {
pub trivia_has_line_terminator: bool,
/// Decoded identifier value, set when the identifier contains unicode
/// escape sequences (e.g. `l\u0065t` → `let`).
- pub identifier_value: Option<crate::ast::Utf16String>,
+ pub identifier_value: Option<ak::Utf16String>,
/// Error message for Invalid tokens (e.g. "Unterminated multi-line comment").
pub message: Option<String>,
}
diff --git a/Libraries/LibJS/Rust/src/tokenize.rs b/Libraries/LibJS/Rust/src/tokenize.rs
index ff6e6fb4339..78db1d902b4 100644
--- a/Libraries/LibJS/Rust/src/tokenize.rs
+++ b/Libraries/LibJS/Rust/src/tokenize.rs
@@ -9,6 +9,7 @@
use crate::lexer::Lexer;
use crate::token::TokenCategory;
use crate::token::TokenType;
+use crate::utf16::Utf16View;
/// A token, with the trivia (whitespace and comments) before it. Offsets and lengths count UTF-16 code units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -22,7 +23,7 @@ pub struct SourceToken {
}
/// The tokens of `source`, ending with its end-of-file token, whose trivia is whatever follows the last token.
-pub fn tokenize(source: &[u16]) -> SourceTokens<'_> {
+pub fn tokenize(source: Utf16View<'_>) -> SourceTokens<'_> {
SourceTokens {
lexer: Lexer::new(source, 1, 0),
reached_end_of_file: false,
diff --git a/Libraries/LibJS/Rust/src/utf16.rs b/Libraries/LibJS/Rust/src/utf16.rs
index c7349137099..52c8240eac4 100644
--- a/Libraries/LibJS/Rust/src/utf16.rs
+++ b/Libraries/LibJS/Rust/src/utf16.rs
@@ -313,6 +313,7 @@ impl<'a> Utf16View<'a> {
/// Mirrors AK::Utf16String::to_lowercase() without a locale, which LibUnicode implements with ICU's full case
/// mapping in the default locale.
+ #[cfg(not(test))]
pub fn to_lowercase(self) -> Utf16String {
if let Self::Ascii(units) = self {
return Utf16String::from_ascii_with(units.len(), |storage| {
@@ -326,6 +327,7 @@ impl<'a> Utf16View<'a> {
/// Mirrors AK::Utf16String::to_uppercase() without a locale, which LibUnicode implements with ICU's full case
/// mapping in the default locale.
+ #[cfg(not(test))]
pub fn to_uppercase(self) -> Utf16String {
if let Self::Ascii(units) = self {
return Utf16String::from_ascii_with(units.len(), |storage| {
@@ -339,6 +341,18 @@ impl<'a> Utf16View<'a> {
}
/// Mirrors AK::TrimMode.
+impl<'a> From<&'a Utf16String> for Utf16View<'a> {
+ fn from(string: &'a Utf16String) -> Self {
+ Self::of_string(string)
+ }
+}
+
+impl From<Utf16View<'_>> for Utf16String {
+ fn from(view: Utf16View<'_>) -> Self {
+ view.to_utf16_string()
+ }
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TrimMode {
Left,
@@ -722,6 +736,30 @@ impl PartialEq for Utf16View<'_> {
impl Eq for Utf16View<'_> {}
+impl<'a> From<&'a [u16]> for Utf16View<'a> {
+ fn from(units: &'a [u16]) -> Self {
+ Self::Utf16(units)
+ }
+}
+
+impl<'a> From<&'a Vec<u16>> for Utf16View<'a> {
+ fn from(units: &'a Vec<u16>) -> Self {
+ Self::Utf16(units)
+ }
+}
+
+impl<'a> From<&Utf16View<'a>> for Utf16View<'a> {
+ fn from(view: &Utf16View<'a>) -> Self {
+ *view
+ }
+}
+
+impl PartialEq<&[u16]> for Utf16View<'_> {
+ fn eq(&self, other: &&[u16]) -> bool {
+ self.code_units().eq(other.iter().copied())
+ }
+}
+
impl PartialEq<str> for Utf16View<'_> {
fn eq(&self, other: &str) -> bool {
self.code_units().eq(other.encode_utf16())
diff --git a/Libraries/LibJS/Rust/src/utilities/js.rs b/Libraries/LibJS/Rust/src/utilities/js.rs
index ecbfb50c55a..1b2613a2348 100644
--- a/Libraries/LibJS/Rust/src/utilities/js.rs
+++ b/Libraries/LibJS/Rust/src/utilities/js.rs
@@ -1234,17 +1234,17 @@ fn parse_and_run(
let mut result: ThrowCompletionOr<Value> = Ok(Value::UNDEFINED);
// Like Utf16String::from_utf8(), this stops the process for a source that is not valid UTF-8, which the caller
// has ruled out.
- let utf16_source = utf16_from_wtf8(source).expect("the source is valid UTF-8");
+ let source_text = Utf16String::from_utf8(core::str::from_utf8(source).expect("the source is valid UTF-8"));
let program_type = if options.as_module {
ProgramType::Module
} else {
ProgramType::Script
};
- let mut parsed = parse(&utf16_source, program_type, 1);
+ let mut parsed = parse(&source_text, program_type, 1);
if parsed.has_errors() {
let error = ParserError::all_from_parsed_program(&parsed).swap_remove(0);
- let hint = error.source_location_hint(&utf16_source, b' ', b'^');
+ let hint = error.source_location_hint(&source_text.to_utf16(), b' ', b'^');
if !hint.is_empty() {
standard_output::outln(&Utf16View::Utf16(&hint).to_wtf8());
}
@@ -1262,10 +1262,7 @@ fn parse_and_run(
let _ = stdout.write_all(b"\n");
let _ = stdout.flush();
}
- let source_code = SourceCode::create(
- Utf16String::from_utf8(source_name),
- Utf16String::from_utf16(&utf16_source),
- );
+ let source_code = SourceCode::create(Utf16String::from_utf8(source_name), source_text);
if !options.as_module {
let script = Script::create_from_parsed_with_filename(vm, parsed, source_code, realm, source_name);
if !parse_only {
@@ -1702,7 +1699,7 @@ mod repl {
// - <N>.<P>
// where N is the complete name of a variable and
// P is part of the name of one of its properties
- let mut lexer = Lexer::new(&code, 1, 0);
+ let mut lexer = Lexer::new(Utf16View::Utf16(&code), 1, 0);
let mut last_token_has_trivia = loop {
let token = lexer.next();
if token.token_type == TokenType::Eof {
@@ -1831,7 +1828,7 @@ mod repl {
fn update_line_level_for_line(line: &[u16]) -> bool {
let mut label_state = LabelState::NotInLabelOrObjectKey;
- let mut lexer = Lexer::new(line, 1, 0);
+ let mut lexer = Lexer::new(Utf16View::Utf16(line), 1, 0);
loop {
let token = lexer.next();
match token.token_type {
diff --git a/Libraries/LibJS/Rust/src/utilities/test262_runner.rs b/Libraries/LibJS/Rust/src/utilities/test262_runner.rs
index fd6af75c966..94bf736a0ce 100644
--- a/Libraries/LibJS/Rust/src/utilities/test262_runner.rs
+++ b/Libraries/LibJS/Rust/src/utilities/test262_runner.rs
@@ -510,7 +510,7 @@ fn decoded_source<'source>(source: Option<&'source [u16]>, what: &str) -> &'sour
}
fn parse_only_check(source: &[u16], program_type: ProgramType) -> Result<(), TestError> {
- if parse(source, program_type, 1).has_errors() {
+ if parse(&Utf16String::from_utf16(source), program_type, 1).has_errors() {
return Err(TestError::syntax_error(
NegativePhase::ParseOrEarly,
"Parse error".to_string(),
@@ -537,7 +537,7 @@ fn parse_program(
TestError::syntax_error(NegativePhase::ParseOrEarly, first_parser_error(&errors), "")
};
if program_type == ProgramType::Script {
- return Script::parse_with_filename(vm, source, realm, filepath)
+ return Script::parse_with_filename(vm, &Utf16String::from_utf16(source), realm, filepath)
.map(ScriptOrModuleProgram::Script)
.map_err(syntax_error);
}
@@ -639,7 +639,7 @@ fn run_test(
let harness_source = utf16_from_wtf8(&harness_source);
let harness_program = Script::parse_with_filename(
&vm,
- decoded_source(harness_source.as_deref(), "The harness"),
+ &Utf16String::from_utf16(decoded_source(harness_source.as_deref(), "The harness")),
realm,
"<harness>",
)
@@ -1039,7 +1039,8 @@ mod agent_mode {
fn run_agent_script(vm: &Vm, realm: Gc<Realm>, source: &[u8]) -> Result<(), TestError> {
let source = utf16_from_wtf8(source);
- let script = Script::parse_with_filename(vm, decoded_source(source.as_deref(), "The agent"), realm, "<agent>")
+ let source = ak::Utf16String::from_utf16(decoded_source(source.as_deref(), "The agent"));
+ let script = Script::parse_with_filename(vm, &source, realm, "<agent>")
.map_err(|errors| TestError::syntax_error(NegativePhase::ParseOrEarly, first_parser_error(&errors), ""))?;
run_program(vm, ScriptOrModuleProgram::Script(script))?;
match UNHANDLED_REJECTIONS.take().into_iter().next() {
diff --git a/Libraries/LibJS/Rust/src/utilities/test_js/javascript_test_runner.rs b/Libraries/LibJS/Rust/src/utilities/test_js/javascript_test_runner.rs
index fc12a8b4e6f..670ac80ff4a 100644
--- a/Libraries/LibJS/Rust/src/utilities/test_js/javascript_test_runner.rs
+++ b/Libraries/LibJS/Rust/src/utilities/test_js/javascript_test_runner.rs
@@ -215,7 +215,8 @@ fn file_parser_error(errors: Vec<ParserError>, source_text: &[u16]) -> FileParse
pub fn parse_script(vm: &Vm, path: &str, realm: Gc<Realm>) -> Result<Gc<Script>, FileParserError> {
let source_text = source_text_of(path);
- Script::parse_with_filename(vm, &source_text, realm, path).map_err(|errors| file_parser_error(errors, &source_text))
+ let source = Utf16String::from_utf16(&source_text);
+ Script::parse_with_filename(vm, &source, realm, path).map_err(|errors| file_parser_error(errors, &source_text))
}
pub fn parse_module(vm: &Vm, path: &str, realm: Gc<Realm>) -> Result<Gc<SourceTextModule>, FileParserError> {
diff --git a/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs b/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs
index 1f41428f14b..5a4d5c7109c 100644
--- a/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs
+++ b/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs
@@ -10,7 +10,7 @@
use core::ops::ControlFlow;
use std::ffi::{CStr, CString};
-use ak::{Utf16FlyString, Utf16String};
+use ak::Utf16FlyString;
use super::javascript_test_runner::{JSFileResult, parse_module, parse_script};
use super::test_runner::{Case, Suite, TestResult, get_time_in_ms, relative_path};
@@ -72,10 +72,6 @@ pub const EXPOSED_GLOBAL_FUNCTIONS: &[(&str, RawNativeFunctionPointer)] = &[
("createDefaultTypedArray", raw_native!(create_default_typed_array)),
];
-fn code_units_of(string: &Utf16String) -> Vec<u16> {
- Utf16View::of_string(string).code_units().collect()
-}
-
/// Value::as_if<T>(): the object `value` is, if it is a T.
fn as_if<T: GcCell + Extends<Object>>(value: Value) -> Option<Gc<T>> {
if !value.is_object() {
@@ -106,7 +102,7 @@ fn set_dictionary_generation(vm: &Vm) -> ThrowCompletionOr<Value> {
fn can_parse_source(vm: &Vm) -> ThrowCompletionOr<Value> {
let realm = vm.current_realm().expect("canParseSource runs in a realm");
let source = vm.argument(0).to_utf16_string(vm)?;
- let script = Script::parse(vm, &code_units_of(&source), realm);
+ let script = Script::parse(vm, &source, realm);
Ok(Value::from_bool(script.is_ok()))
}
@@ -138,7 +134,7 @@ fn evaluate_source(vm: &Vm) -> ThrowCompletionOr<Value> {
let source = vm.argument(0).to_utf16_string(vm)?;
- let script = match Script::parse(vm, &code_units_of(&source), realm) {
+ let script = match Script::parse(vm, &source, realm) {
Ok(script) => script,
Err(errors) => return vm.throw_completion_with_message(ErrorKind::SyntaxError, errors[0].to_string()),
};
diff --git a/Libraries/LibJS/Script.cpp b/Libraries/LibJS/Script.cpp
index 3db3fe46a42..8cf51b51caa 100644
--- a/Libraries/LibJS/Script.cpp
+++ b/Libraries/LibJS/Script.cpp
@@ -29,39 +29,9 @@ Result<GC::Ref<Script>, Vector<ParserError>> Script::parse(Utf16View source_text
return record_or_parser_errors_from_abi<Script>(script, errors);
}
-Result<GC::Ref<Script>, Vector<ParserError>> Script::create_from_bytecode_cache(NonnullRefPtr<RustIntegration::DecodedBytecodeCache> bytecode_cache, NonnullRefPtr<SourceCode const> source_code, Realm& realm, StringView filename, GC::Ptr<GC::Cell> host_defined)
-{
- ParserErrorCollector errors;
- auto utf16_filename = filename_to_utf16(filename);
- auto* script = js_bytecode_cache_create_script(
- vm_to_abi(realm.vm()),
- decoded_bytecode_cache_to_abi(*bytecode_cache),
- source_code_to_abi(*source_code),
- realm_to_abi(realm),
- utf16_view_to_abi(utf16_filename.utf16_view()),
- host_defined.ptr(),
- errors.sink());
- return record_or_parser_errors_from_abi<Script>(script, errors);
-}
-
GC::Ptr<GC::Cell> Script::host_defined() const
{
return static_cast<GC::Cell*>(js_script_host_defined(script_to_abi(*this)));
}
-void Script::begin_bytecode_cache_generation()
-{
- js_bytecode_cache_script_begin_generation(vm_to_abi(vm()), script_to_abi(*this));
-}
-
-void Script::finish_bytecode_cache_generation_without_install()
-{
- js_bytecode_cache_script_finish_generation_without_install(vm_to_abi(vm()), script_to_abi(*this));
-}
-
-void Script::install_generated_bytecode_cache(NonnullRefPtr<RustIntegration::DecodedBytecodeCache> bytecode_cache, NonnullRefPtr<SourceCode const> source_code)
-{
- js_bytecode_cache_script_install_generated(vm_to_abi(vm()), script_to_abi(*this), decoded_bytecode_cache_to_abi(*bytecode_cache), source_code_to_abi(*source_code));
-}
-
}
diff --git a/Libraries/LibJS/Script.h b/Libraries/LibJS/Script.h
index faba4fa49c7..bf29b46bad5 100644
--- a/Libraries/LibJS/Script.h
+++ b/Libraries/LibJS/Script.h
@@ -15,7 +15,6 @@
#include <AK/Vector.h>
#include <LibGC/Ptr.h>
#include <LibGC/Root.h>
-#include <LibJS/DecodedBytecodeCache.h>
#include <LibJS/Export.h>
#include <LibJS/Forward.h>
#include <LibJS/Heap/EngineCell.h>
@@ -34,16 +33,7 @@ class JS_API Script final : public EngineCell {
public:
static Result<GC::Ref<Script>, Vector<ParserError>> parse(Utf16View source_text, Realm&, StringView filename = {}, Utf16View display_filename = {}, GC::Ptr<GC::Cell> host_defined = nullptr, size_t line_number_offset = 1);
- // Fails with one error if the cache turns out not to match the source code.
- static Result<GC::Ref<Script>, Vector<ParserError>> create_from_bytecode_cache(NonnullRefPtr<RustIntegration::DecodedBytecodeCache>, NonnullRefPtr<SourceCode const> source_code, Realm&, StringView filename, GC::Ptr<GC::Cell> host_defined = nullptr);
-
GC::Ptr<GC::Cell> host_defined() const;
-
- // A host that generates a bytecode cache for the script marks it as such until it installs the cache, which then
- // replaces the script's bytecode, or gives up.
- void begin_bytecode_cache_generation();
- void finish_bytecode_cache_generation_without_install();
- void install_generated_bytecode_cache(NonnullRefPtr<RustIntegration::DecodedBytecodeCache>, NonnullRefPtr<SourceCode const> source_code);
};
}
diff --git a/Libraries/LibJS/ScriptAndModuleABIConversions.h b/Libraries/LibJS/ScriptAndModuleABIConversions.h
index 9e0da554dea..ce1f4756e0b 100644
--- a/Libraries/LibJS/ScriptAndModuleABIConversions.h
+++ b/Libraries/LibJS/ScriptAndModuleABIConversions.h
@@ -12,7 +12,6 @@
#include <AK/StringView.h>
#include <AK/Utf16String.h>
#include <AK/Vector.h>
-#include <LibJS/DecodedBytecodeCache.h>
#include <LibJS/EmbeddingABIConversions.h>
#include <LibJS/Module.h>
#include <LibJS/ModuleLoading.h>
@@ -43,25 +42,6 @@ inline NonnullRefPtr<SourceCode const> adopt_source_code_from_abi(JSSourceCode c
return adopt_ref(*reinterpret_cast<SourceCode const*>(source_code));
}
-inline JSDecodedBytecodeCache const* decoded_bytecode_cache_to_abi(RustIntegration::DecodedBytecodeCache const& cache)
-{
- return reinterpret_cast<JSDecodedBytecodeCache const*>(&cache);
-}
-
-// A decoded cache whose one reference the runtime created it with, which the caller takes over.
-inline RefPtr<RustIntegration::DecodedBytecodeCache> adopt_decoded_bytecode_cache_from_abi(JSDecodedBytecodeCache const* cache)
-{
- if (!cache)
- return {};
- auto& adopted_cache = *reinterpret_cast<RustIntegration::DecodedBytecodeCache*>(const_cast<JSDecodedBytecodeCache*>(cache));
- return adopt_ref(adopted_cache);
-}
-
-inline JSProgramType program_type_to_abi(RustIntegration::ProgramType program_type)
-{
- return to_underlying(program_type);
-}
-
inline JSRealm* realm_to_abi(Realm const& realm)
{
return cell_to_abi<JSRealm>(realm);
diff --git a/Libraries/LibJS/ScriptCompilation.cpp b/Libraries/LibJS/ScriptCompilation.cpp
index f4f89c708cf..d2dcdd1e485 100644
--- a/Libraries/LibJS/ScriptCompilation.cpp
+++ b/Libraries/LibJS/ScriptCompilation.cpp
@@ -4,7 +4,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibCore/EventLoop.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/ScriptAndModuleABIConversions.h>
@@ -24,6 +23,11 @@ static_assert(sizeof(Position) == sizeof(JSPosition));
static_assert(offsetof(Position, line) == offsetof(JSPosition, line));
static_assert(offsetof(Position, column) == offsetof(JSPosition, column));
+static JSProgramType program_type_to_abi(ProgramType program_type)
+{
+ return to_underlying(program_type);
+}
+
static JSParsedProgram* parsed_program_to_abi(FFI::ParsedProgram* program)
{
return reinterpret_cast<JSParsedProgram*>(program);
@@ -107,9 +111,9 @@ ParsedProgram::~ParsedProgram()
js_compile_parsed_program_destroy(parsed_program_to_abi(m_program));
}
-ParsedProgram ParsedProgram::parse(Utf16View source_text, ProgramType program_type, size_t line_number_offset)
+ParsedProgram ParsedProgram::parse(Utf16String source_text, ProgramType program_type, size_t line_number_offset)
{
- return ParsedProgram { parsed_program_from_abi(js_compile_parse(utf16_view_to_abi(source_text), program_type_to_abi(program_type), line_number_offset)) };
+ return ParsedProgram { parsed_program_from_abi(js_compile_parse(owned_utf16_string_to_abi(move(source_text)), program_type_to_abi(program_type), line_number_offset)) };
}
bool ParsedProgram::has_errors() const
@@ -117,11 +121,6 @@ bool ParsedProgram::has_errors() const
return js_compile_parsed_program_has_errors(parsed_program_to_abi(m_program));
}
-ParsedProgram ParsedProgram::clone() const
-{
- return ParsedProgram { parsed_program_from_abi(js_compile_parsed_program_clone(parsed_program_to_abi(m_program))) };
-}
-
CompiledProgram::CompiledProgram(FFI::CompiledProgram* program)
: m_program(program)
{
@@ -152,26 +151,6 @@ CompiledProgram CompiledProgram::compile(ParsedProgram parsed)
return CompiledProgram { compiled_program_from_abi(js_compile_parsed_program(program)) };
}
-CompiledProgram CompiledProgram::compile_all_functions(ParsedProgram parsed)
-{
- auto* program = parsed_program_to_abi(exchange(parsed.m_program, nullptr));
- return CompiledProgram { compiled_program_from_abi(js_compile_parsed_program_with_all_functions(program)) };
-}
-
-ByteBuffer CompiledProgram::serialize_for_bytecode_cache(ProgramType program_type, ReadonlyBytes source_hash) const
-{
- ByteBuffer blob;
- JSByteSink sink {
- .context = &blob,
- .append = [](void* context, u8 const* bytes, size_t length) {
- return !static_cast<ByteBuffer*>(context)->try_append(bytes, length).is_error();
- },
- };
- if (!js_bytecode_cache_serialize(compiled_program_to_abi(m_program), program_type_to_abi(program_type), source_hash.data(), source_hash.size(), &sink))
- return {};
- return blob;
-}
-
Result<GC::Ref<Script>, Vector<ParserError>> create_script(ParsedProgram parsed, NonnullRefPtr<SourceCode const> source_code, Realm& realm, StringView filename, GC::Ptr<GC::Cell> host_defined)
{
ParserErrorCollector errors;
@@ -228,50 +207,7 @@ Result<GC::Ref<SourceTextModule>, Vector<ParserError>> create_module(CompiledPro
return module_from_abi<SourceTextModule>(module);
}
-RefPtr<DecodedBytecodeCache> decode_and_validate_bytecode_cache(Core::ImmutableBytes bytes, ProgramType program_type, ReadonlyBytes source_hash, size_t source_length_in_code_units, Core::EventLoop& main_thread_event_loop)
-{
- // The runtime may release the bytes on this thread, so their last reference goes on the main thread.
- struct BlobBytesOwner {
- AK_ALLOC_WITH_KMALLOC;
-
- Core::ImmutableBytes bytes;
- Core::EventLoop& main_thread_event_loop;
- };
- auto* bytes_owner = new BlobBytesOwner { move(bytes), main_thread_event_loop };
- JSBytecodeCacheBlobOwner owner {
- .owner = bytes_owner,
- .release = [](void* owner) {
- auto* bytes_owner = static_cast<BlobBytesOwner*>(owner);
- bytes_owner->main_thread_event_loop.deferred_invoke([bytes_owner] { delete bytes_owner; });
- },
- };
- auto blob = bytes_owner->bytes.bytes();
- return adopt_decoded_bytecode_cache_from_abi(js_bytecode_cache_decode_and_validate(blob.data(), blob.size(), program_type_to_abi(program_type), source_hash.data(), source_hash.size(), source_length_in_code_units, owner));
-}
-
// The host's callbacks, which the runtime shares between the main thread and the workers until it releases them.
-static JSOffThreadCompilationCallbacks off_thread_compilation_callbacks_to_abi(OffThreadCompilationCallbacks callbacks)
-{
- return JSOffThreadCompilationCallbacks {
- .context = new OffThreadCompilationCallbacks(move(callbacks)),
- .submit_work = [](void* context, JSOffThreadTask task) { static_cast<OffThreadCompilationCallbacks*>(context)->submit_work([task] { task.run(task.data); }); },
- .post_to_main_thread = [](void* context, JSOffThreadTask task) { static_cast<OffThreadCompilationCallbacks*>(context)->post_to_main_thread([task] { task.run(task.data); }); },
- .release = [](void* context) { delete static_cast<OffThreadCompilationCallbacks*>(context); },
- };
-}
-
-void compile_remaining_functions_off_thread(Script& script, NonnullRefPtr<SourceCode const>, OffThreadCompilationCallbacks callbacks)
-{
- auto abi_callbacks = off_thread_compilation_callbacks_to_abi(move(callbacks));
- js_compile_remaining_functions_of_script_off_thread(vm_to_abi(script.vm()), script_to_abi(script), &abi_callbacks);
-}
-
-void compile_remaining_functions_off_thread(SourceTextModule& module, NonnullRefPtr<SourceCode const>, OffThreadCompilationCallbacks callbacks)
-{
- auto abi_callbacks = off_thread_compilation_callbacks_to_abi(move(callbacks));
- js_compile_remaining_functions_of_module_off_thread(vm_to_abi(module.vm()), module_to_abi(module), &abi_callbacks);
-}
-
RefPtr<SourceCode const> top_level_source_code(Script const& script)
{
return source_code_from_abi(js_compile_top_level_source_code_of_script(script_to_abi(script)));
diff --git a/Libraries/LibJS/ScriptCompilation.h b/Libraries/LibJS/ScriptCompilation.h
index 7b019774702..2720cf97df0 100644
--- a/Libraries/LibJS/ScriptCompilation.h
+++ b/Libraries/LibJS/ScriptCompilation.h
@@ -17,11 +17,8 @@
#include <AK/Utf16String.h>
#include <AK/Utf16View.h>
#include <AK/Vector.h>
-#include <LibCore/Forward.h>
-#include <LibCore/ImmutableBytes.h>
#include <LibGC/Ptr.h>
#include <LibGC/Root.h>
-#include <LibJS/DecodedBytecodeCache.h>
#include <LibJS/Export.h>
#include <LibJS/Forward.h>
#include <LibJS/Heap/EngineCell.h>
@@ -40,8 +37,10 @@ struct CompiledProgram;
namespace JS {
-using ProgramType = RustIntegration::ProgramType;
-using DecodedBytecodeCache = RustIntegration::DecodedBytecodeCache;
+enum class ProgramType : u8 {
+ Script = 0,
+ Module = 1,
+};
// A function compiled from standalone source text the way CreateDynamicFunction compiles one, for hosts that create
// functions outside of any script, such as event handler content attributes.
@@ -84,7 +83,7 @@ class JS_API ParsedProgram {
AK_MAKE_NONCOPYABLE(ParsedProgram);
public:
- static ParsedProgram parse(Utf16View source_text, ProgramType, size_t line_number_offset);
+ static ParsedProgram parse(Utf16String source_text, ProgramType, size_t line_number_offset);
ParsedProgram() = default;
ParsedProgram(ParsedProgram&&);
@@ -95,7 +94,6 @@ public:
bool has_errors() const;
// Only for a program without errors. The copy compiles independently of the original.
- ParsedProgram clone() const;
private:
friend class CompiledProgram;
@@ -111,11 +109,9 @@ class JS_API CompiledProgram {
AK_MAKE_NONCOPYABLE(CompiledProgram);
public:
- // Both consume a program without errors. compile() generates bytecode for the top level and for the functions it
- // invokes immediately; every other function is compiled on its first call, or by
- // compile_remaining_functions_off_thread(). compile_all_functions() compiles everything, as a bytecode cache needs.
+ // Consumes a program without errors, and generates bytecode for the top level and for the functions it invokes
+ // immediately. Every other function is compiled on its first call.
static CompiledProgram compile(ParsedProgram);
- static CompiledProgram compile_all_functions(ParsedProgram);
CompiledProgram() = default;
CompiledProgram(CompiledProgram&&);
@@ -124,9 +120,6 @@ public:
explicit operator bool() const { return m_program; }
- // A versioned bytecode cache blob for the program, or an empty buffer if the program cannot be cached.
- ByteBuffer serialize_for_bytecode_cache(ProgramType, ReadonlyBytes source_hash) const;
-
private:
friend JS_API Result<GC::Ref<Script>, Vector<ParserError>> create_script(CompiledProgram, NonnullRefPtr<SourceCode const>, Realm&, StringView filename, GC::Ptr<GC::Cell>);
friend JS_API Result<GC::Ref<SourceTextModule>, Vector<ParserError>> create_module(CompiledProgram, NonnullRefPtr<SourceCode const>, Realm&, StringView filename, GC::Ptr<GC::Cell>);
@@ -136,28 +129,6 @@ private:
FFI::CompiledProgram* m_program { nullptr };
};
-// Thread-safe. Decodes a bytecode cache blob and validates it against the source it claims to be compiled from, or
-// returns null if the blob does not match that source or is corrupt. The blob's bytes are released on the main thread
-// event loop.
-JS_API RefPtr<DecodedBytecodeCache> decode_and_validate_bytecode_cache(Core::ImmutableBytes, ProgramType, ReadonlyBytes source_hash, size_t source_length_in_code_units, Core::EventLoop& main_thread_event_loop);
-
-// How the host runs background compilation work. submit_work is called on the main thread and must run the work on a
-// worker thread. post_to_main_thread is called on that worker thread and must run the task on the main thread. Both
-// callbacks may be destroyed on either thread.
-struct OffThreadCompilationCallbacks {
- AK_ALLOC_WITH_KMALLOC;
-
- Function<void(Function<void()>)> submit_work;
- Function<void(Function<void()>)> post_to_main_thread;
-};
-
-// On a worker thread, compiles the functions that the record's top-level code creates and that have not been compiled
-// yet, so that their first calls do not have to. Functions that start running in the meantime are compiled on the main
-// thread as usual, and the functions they create are then compiled off thread as well. Must be called on the main
-// thread.
-JS_API void compile_remaining_functions_off_thread(Script&, NonnullRefPtr<SourceCode const>, OffThreadCompilationCallbacks);
-JS_API void compile_remaining_functions_off_thread(SourceTextModule&, NonnullRefPtr<SourceCode const>, OffThreadCompilationCallbacks);
-
// The source that the record's top-level code was compiled from. Null for a module with top-level await, whose body is
// compiled as an async function instead.
JS_API RefPtr<SourceCode const> top_level_source_code(Script const&);
diff --git a/Libraries/LibJS/SourceCode.cpp b/Libraries/LibJS/SourceCode.cpp
index f6e492636a2..77e2023146b 100644
--- a/Libraries/LibJS/SourceCode.cpp
+++ b/Libraries/LibJS/SourceCode.cpp
@@ -22,32 +22,11 @@ static Utf16String const& string_in_place_from_abi(JSOwnedUtf16String const* str
return *reinterpret_cast<Utf16String const*>(string);
}
-// What SourceCode decodes its source bytes to: the code units in the range, with the encoding of a byte order mark
-// taking precedence over the given one.
-static Utf16String decode_source_bytes(ReadonlyBytes source_bytes, StringView source_encoding, size_t length_in_code_units)
-{
- if (length_in_code_units == 0)
- return {};
-
- auto decoder = TextCodec::decoder_for(source_encoding);
- VERIFY(decoder.has_value());
-
- auto code = MUST(TextCodec::decode_to_utf16(source_bytes, *decoder));
- if (code.length_in_code_units() > length_in_code_units)
- return Utf16String::from_utf16(code.utf16_view().substring_view(0, length_in_code_units));
- return code;
-}
-
NonnullRefPtr<SourceCode const> SourceCode::create(Utf16String filename, Utf16String code)
{
return adopt_source_code_from_abi(js_source_code_create(owned_utf16_string_to_abi(move(filename)), owned_utf16_string_to_abi(move(code))));
}
-NonnullRefPtr<SourceCode const> SourceCode::create(Utf16String filename, size_t length_in_code_units, ByteString source_encoding, Core::ImmutableBytes source_bytes)
-{
- return create(move(filename), decode_source_bytes(source_bytes.bytes(), source_encoding.view(), length_in_code_units));
-}
-
Utf16String const& SourceCode::filename() const
{
return string_in_place_from_abi(js_source_code_filename_address(source_code_to_abi(*this)));
diff --git a/Libraries/LibJS/SourceCode.h b/Libraries/LibJS/SourceCode.h
index ef90e179263..82497345c92 100644
--- a/Libraries/LibJS/SourceCode.h
+++ b/Libraries/LibJS/SourceCode.h
@@ -6,14 +6,12 @@
#pragma once
-#include <AK/ByteString.h>
#include <AK/Noncopyable.h>
#include <AK/NonnullRefPtr.h>
#include <AK/Optional.h>
#include <AK/RefPtr.h>
#include <AK/Utf16String.h>
#include <AK/Vector.h>
-#include <LibCore/ImmutableBytes.h>
#include <LibJS/Export.h>
#include <LibJS/Forward.h>
#include <LibJS/Position.h>
@@ -30,9 +28,6 @@ class JS_API SourceCode {
public:
static NonnullRefPtr<SourceCode const> create(Utf16String filename, Utf16String code);
- // This decodes the bytes right away rather than when the code is first needed.
- static NonnullRefPtr<SourceCode const> create(Utf16String filename, size_t length_in_code_units, ByteString source_encoding, Core::ImmutableBytes source_bytes);
-
Utf16String const& filename() const;
Utf16String const& code() const;
size_t length_in_code_units() const;
diff --git a/Libraries/LibJS/SourceTextModule.cpp b/Libraries/LibJS/SourceTextModule.cpp
index de67f4f3089..0515265839f 100644
--- a/Libraries/LibJS/SourceTextModule.cpp
+++ b/Libraries/LibJS/SourceTextModule.cpp
@@ -30,34 +30,4 @@ Result<GC::Ref<SourceTextModule>, Vector<ParserError>> SourceTextModule::parse(U
return record_or_parser_errors_from_abi<SourceTextModule>(module, errors);
}
-Result<GC::Ref<SourceTextModule>, Vector<ParserError>> SourceTextModule::parse_from_bytecode_cache(NonnullRefPtr<RustIntegration::DecodedBytecodeCache> bytecode_cache, NonnullRefPtr<SourceCode const> source_code, Realm& realm, StringView filename, GC::Ptr<GC::Cell> host_defined)
-{
- ParserErrorCollector errors;
- auto utf16_filename = filename_to_utf16(filename);
- auto* module = js_bytecode_cache_create_module(
- vm_to_abi(realm.vm()),
- decoded_bytecode_cache_to_abi(*bytecode_cache),
- source_code_to_abi(*source_code),
- realm_to_abi(realm),
- utf16_view_to_abi(utf16_filename.utf16_view()),
- host_defined.ptr(),
- errors.sink());
- return record_or_parser_errors_from_abi<SourceTextModule>(module, errors);
-}
-
-void SourceTextModule::begin_bytecode_cache_generation()
-{
- js_bytecode_cache_module_begin_generation(vm_to_abi(vm()), module_to_abi(*this));
-}
-
-void SourceTextModule::finish_bytecode_cache_generation_without_install()
-{
- js_bytecode_cache_module_finish_generation_without_install(vm_to_abi(vm()), module_to_abi(*this));
-}
-
-void SourceTextModule::install_generated_bytecode_cache(NonnullRefPtr<RustIntegration::DecodedBytecodeCache> bytecode_cache, NonnullRefPtr<SourceCode const> source_code)
-{
- js_bytecode_cache_module_install_generated(vm_to_abi(vm()), module_to_abi(*this), decoded_bytecode_cache_to_abi(*bytecode_cache), source_code_to_abi(*source_code));
-}
-
}
diff --git a/Libraries/LibJS/SourceTextModule.h b/Libraries/LibJS/SourceTextModule.h
index 6e1f76b3491..cbc5e66dde0 100644
--- a/Libraries/LibJS/SourceTextModule.h
+++ b/Libraries/LibJS/SourceTextModule.h
@@ -12,7 +12,6 @@
#include <AK/StringView.h>
#include <AK/Utf16View.h>
#include <LibJS/CyclicModule.h>
-#include <LibJS/DecodedBytecodeCache.h>
#include <LibJS/Export.h>
#include <LibJS/Forward.h>
#include <LibJS/ParserError.h>
@@ -25,15 +24,6 @@ namespace JS {
class JS_API SourceTextModule final : public CyclicModule {
public:
static Result<GC::Ref<SourceTextModule>, Vector<ParserError>> parse(Utf16View source_text, Realm&, StringView filename = {}, Utf16View display_filename = {}, GC::Ptr<GC::Cell> host_defined = nullptr, size_t line_number_offset = 0);
-
- // Fails with one error if the cache turns out not to match the source code.
- static Result<GC::Ref<SourceTextModule>, Vector<ParserError>> parse_from_bytecode_cache(NonnullRefPtr<RustIntegration::DecodedBytecodeCache>, NonnullRefPtr<SourceCode const> source_code, Realm&, StringView filename, GC::Ptr<GC::Cell> host_defined = nullptr);
-
- // A host that generates a bytecode cache for the module marks it as such until it installs the cache, which then
- // replaces the module's bytecode, or gives up.
- void begin_bytecode_cache_generation();
- void finish_bytecode_cache_generation_without_install();
- void install_generated_bytecode_cache(NonnullRefPtr<RustIntegration::DecodedBytecodeCache>, NonnullRefPtr<SourceCode const> source_code);
};
}
diff --git a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp
index b1f1e7561bc..ab122833820 100644
--- a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp
@@ -60,37 +60,17 @@ static ByteBuffer take_body_bytes_as_byte_buffer(Fetch::Infrastructure::FetchAlg
return body_bytes.get<Core::ImmutableBytes>().copy_to_byte_buffer().release_value_but_fixme_should_propagate_errors();
}
-static JS::OffThreadCompilationCallbacks thread_pool_compilation_callbacks()
-{
- auto& main_thread_event_loop = Core::EventLoop::current();
- return {
- .submit_work = [](Function<void()> work) { Threading::ThreadPool::the().submit(move(work)); },
- .post_to_main_thread = [&main_thread_event_loop](Function<void()> task) { main_thread_event_loop.deferred_invoke(move(task)); },
- };
-}
-
-static void compile_remaining_module_functions_off_thread(ModuleScript& module_script, NonnullRefPtr<JS::SourceCode const> source_code)
-{
- module_script.record().visit(
- [](Empty) { },
- [](GC::Ref<JS::SyntheticModule>) { },
- [](GC::Ref<JS::HostModule>) { },
- [source_code = move(source_code)](GC::Ref<JS::SourceTextModule> module) mutable {
- JS::compile_remaining_functions_off_thread(*module, move(source_code), thread_pool_compilation_callbacks());
- });
-}
-
// Submit parsing and top-level bytecode generation to the thread pool, then bounce back to the main thread via
// deferred_invoke once the worker is done, and on to a task of the settings object's global there. Syntax errors still
// come back as a ParsedProgram so the main thread can report them through the same Script/ModuleScript construction
// paths; successful programs come back as CompiledProgram artifacts whose GC-backed Executable materialization must
// still happen on the main thread.
-// NB: The SourceCode stays on the main thread inside the heap-allocated callback. The worker thread only receives a view
-// of its code, which stays unchanged while the SourceCode lives.
+// NB: The SourceCode stays on the main thread inside the heap-allocated callback. The worker thread only receives its
+// code, which is thread-safe to share.
static void compile_off_thread(EnvironmentSettingsObject& settings_object, NonnullRefPtr<JS::SourceCode const> source_code, JS::ProgramType type, size_t line_number_offset, Function<void(OffThreadCompiledProgram, NonnullRefPtr<JS::SourceCode const>)> on_compiled)
{
- // Extract the view the parser needs while still on the main thread.
- auto source_text = source_code->code().utf16_view();
+ // Take the code the parser needs while still on the main thread.
+ auto source_text = source_code->code();
// Capture source_code in the callback so it stays alive on the main thread and is available for materialization.
// The script runs in a task of the settings object's global, so never beside a rendering update in flight that holds
@@ -108,8 +88,8 @@ static void compile_off_thread(EnvironmentSettingsObject& settings_object, Nonnu
auto& main_thread_event_loop = Core::EventLoop::current();
- Threading::ThreadPool::the().submit([source_text, type, line_number_offset, callback, &main_thread_event_loop]() {
- OffThreadCompiledProgram result { .parsed = JS::ParsedProgram::parse(source_text, type, line_number_offset) };
+ Threading::ThreadPool::the().submit([source_text = move(source_text), type, line_number_offset, callback, &main_thread_event_loop]() mutable {
+ OffThreadCompiledProgram result { .parsed = JS::ParsedProgram::parse(move(source_text), type, line_number_offset) };
if (result.parsed && !result.parsed.has_errors())
result.compiled = JS::CompiledProgram::compile(move(result.parsed));
@@ -492,8 +472,6 @@ void fetch_classic_script(JS::Realm& realm, URL::URL const& url, EnvironmentSett
auto script = result.compiled
? ClassicScript::create_from_pre_compiled(move(filename), source_code, *settings_root, move(response_url), move(result.compiled), muted_errors)
: ClassicScript::create_from_pre_parsed(move(filename), source_code, *settings_root, move(response_url), move(result.parsed), muted_errors);
- if (auto script_record = script->script_record())
- JS::compile_remaining_functions_off_thread(*script_record, move(source_code), thread_pool_compilation_callbacks());
on_complete_root->function()(script);
});
};
@@ -864,10 +842,8 @@ void fetch_single_module_script(JS::Realm& realm,
auto module_script = result.compiled
? ModuleScript::create_from_pre_compiled(url_string, source_code, *settings_root, move(response_url), move(result.compiled)).release_value_but_fixme_should_propagate_errors()
: ModuleScript::create_from_pre_parsed(url_string, source_code, *settings_root, move(response_url), move(result.parsed)).release_value_but_fixme_should_propagate_errors();
- if (module_script) {
+ if (module_script)
module_script->set_fetch_options(options);
- compile_remaining_module_functions_off_thread(*module_script, move(source_code));
- }
settings_root->module_map().complete_fetch(url, module_type_string, module_script);
});
return;
diff --git a/Tests/LibJS/AST/expected/binding-pattern-positions.txt b/Tests/LibJS/AST/expected/binding-pattern-positions.txt
index cab67b59262..0cca30919d3 100644
--- a/Tests/LibJS/AST/expected/binding-pattern-positions.txt
+++ b/Tests/LibJS/AST/expected/binding-pattern-positions.txt
@@ -14,12 +14,12 @@ Program (script) @6:1
│ ├─ BindingPattern (object)
│ │ ├─ entry
│ │ │ ├─ name
-│ │ │ │ └─ Identifier "x" [global] @7:7
+│ │ │ │ └─ Identifier "x" @7:7
│ │ │ └─ alias
│ │ │ └─ Identifier "aliased" [global] (let) @7:10
│ │ └─ entry
│ │ ├─ name
-│ │ │ └─ Identifier "y" [global] @7:19
+│ │ │ └─ Identifier "y" @7:19
│ │ └─ alias
│ │ └─ Identifier "also" [global] (let) @7:22
│ └─ ObjectExpression @7:31
@@ -39,7 +39,7 @@ Program (script) @6:1
│ ├─ BindingPattern (object)
│ │ ├─ entry
│ │ │ ├─ name
-│ │ │ │ └─ Identifier "nested" [global] @9:7
+│ │ │ │ └─ Identifier "nested" @9:7
│ │ │ └─ alias
│ │ │ └─ BindingPattern (object)
│ │ │ └─ entry
@@ -73,7 +73,7 @@ Program (script) @6:1
│ │ │ └─ Identifier "p" [variable:0] @12:25
│ │ └─ entry
│ │ ├─ name
- │ │ │ └─ Identifier "q" [global] @12:28
+ │ │ │ └─ Identifier "q" @12:28
│ │ └─ alias
│ │ └─ Identifier "r" [variable:1] @12:31
│ └─ BindingPattern (array)
diff --git a/Tests/LibJS/AST/expected/binding-pattern-property-keys.txt b/Tests/LibJS/AST/expected/binding-pattern-property-keys.txt
index eb34458a4bc..e54d3309b17 100644
--- a/Tests/LibJS/AST/expected/binding-pattern-property-keys.txt
+++ b/Tests/LibJS/AST/expected/binding-pattern-property-keys.txt
@@ -4,12 +4,12 @@ Program (script) @1:1
├─ BindingPattern (object)
│ ├─ entry
│ │ ├─ name
- │ │ │ └─ Identifier "foo" [global] @1:7
+ │ │ │ └─ Identifier "foo" @1:7
│ │ └─ alias
│ │ └─ Identifier "a" [global] (let) @1:12
│ └─ entry
│ ├─ name
- │ │ └─ Identifier "1" [global] @1:15
+ │ │ └─ Identifier "1" @1:15
│ └─ alias
│ └─ Identifier "b" [global] (let) @1:18
└─ ObjectExpression @1:24
diff --git a/Tests/LibJS/AST/expected/destructured-parameter-locals.txt b/Tests/LibJS/AST/expected/destructured-parameter-locals.txt
index 3c03b3f1263..0af0a78e69e 100644
--- a/Tests/LibJS/AST/expected/destructured-parameter-locals.txt
+++ b/Tests/LibJS/AST/expected/destructured-parameter-locals.txt
@@ -53,7 +53,7 @@ Program (script) @1:1
│ │ └─ BindingPattern (object)
│ │ └─ entry
│ │ ├─ name
-│ │ │ └─ Identifier "a" [global] @13:19
+│ │ │ └─ Identifier "a" @13:19
│ │ └─ alias
│ │ └─ BindingPattern (object)
│ │ └─ entry
@@ -82,7 +82,7 @@ Program (script) @1:1
│ └─ BindingPattern (object)
│ └─ entry
│ ├─ name
- │ │ └─ Identifier "a" [global] @21:20
+ │ │ └─ Identifier "a" @21:20
│ └─ alias
│ └─ Identifier "renamed" [variable:0] @21:23
└─ body
diff --git a/Tests/LibJS/AST/expected/destructuring.txt b/Tests/LibJS/AST/expected/destructuring.txt
index 2caf75b5661..dd0bf4448e5 100644
--- a/Tests/LibJS/AST/expected/destructuring.txt
+++ b/Tests/LibJS/AST/expected/destructuring.txt
@@ -22,7 +22,7 @@ Program (script) @1:1
│ │ │ └─ Identifier "x" [variable:2] (let) @3:11
│ │ └─ entry
│ │ ├─ name
- │ │ │ └─ Identifier "y" [global] @3:14
+ │ │ │ └─ Identifier "y" @3:14
│ │ └─ alias
│ │ └─ Identifier "z" [variable:3] (let) @3:17
│ └─ ObjectExpression @3:23
diff --git a/Tests/LibJS/AST/expected/multiple-destructuring-parameters.txt b/Tests/LibJS/AST/expected/multiple-destructuring-parameters.txt
index d28bf080acb..0bc02ad7739 100644
--- a/Tests/LibJS/AST/expected/multiple-destructuring-parameters.txt
+++ b/Tests/LibJS/AST/expected/multiple-destructuring-parameters.txt
@@ -7,18 +7,18 @@ Program (script) @1:1
│ │ ├─ BindingPattern (object)
│ │ │ └─ entry
│ │ │ ├─ name
-│ │ │ │ └─ Identifier "a" [global] @1:12
+│ │ │ │ └─ Identifier "a" @1:12
│ │ │ └─ alias
│ │ │ └─ Identifier "b" [variable:0] @1:15
│ │ ├─ BindingPattern (object)
│ │ │ ├─ entry
│ │ │ │ ├─ name
-│ │ │ │ │ └─ Identifier "c" [global] @1:22
+│ │ │ │ │ └─ Identifier "c" @1:22
│ │ │ │ └─ alias
│ │ │ │ └─ Identifier "d" [variable:1] @1:25
│ │ │ └─ entry
│ │ │ ├─ name
-│ │ │ │ └─ Identifier "e" [global] @1:28
+│ │ │ │ └─ Identifier "e" @1:28
│ │ │ └─ alias
│ │ │ └─ Identifier "g" [variable:2] @1:31
│ │ └─ Identifier "h" [argument:2] @1:10
diff --git a/Tests/LibJS/AST/expected/property-key-arguments.txt b/Tests/LibJS/AST/expected/property-key-arguments.txt
index 470a3b02b0c..352378b1d35 100644
--- a/Tests/LibJS/AST/expected/property-key-arguments.txt
+++ b/Tests/LibJS/AST/expected/property-key-arguments.txt
@@ -47,15 +47,15 @@ Program (script) @3:1
│ │ ├─ BindingPattern (object)
│ │ │ └─ entry
│ │ │ ├─ name
-│ │ │ │ └─ Identifier "arguments" [variable:0] @37:11
+│ │ │ │ └─ Identifier "arguments" @37:11
│ │ │ └─ alias
-│ │ │ └─ Identifier "x" [variable:1] (let) @37:22
+│ │ │ └─ Identifier "x" [variable:0] (let) @37:22
│ │ └─ ObjectExpression @37:28
│ │ └─ ObjectProperty @37:28
│ │ ├─ StringLiteral "arguments" @37:30
│ │ └─ NumericLiteral 1 @37:41
│ └─ ReturnStatement @38:5
-│ └─ Identifier "x" [variable:1] (let) @38:12
+│ └─ Identifier "x" [variable:0] (let) @38:12
└─ FunctionDeclaration "method_named_arguments" @42:1
└─ body
└─ FunctionBody @43:5
diff --git a/Tests/LibJS/AST/expected/proto-destructuring-assignment.txt b/Tests/LibJS/AST/expected/proto-destructuring-assignment.txt
index 3f5170b0abf..ab2160d3668 100644
--- a/Tests/LibJS/AST/expected/proto-destructuring-assignment.txt
+++ b/Tests/LibJS/AST/expected/proto-destructuring-assignment.txt
@@ -9,12 +9,12 @@ Program (script) @1:1
├─ BindingPattern (object)
│ ├─ entry
│ │ ├─ name
- │ │ │ └─ Identifier "__proto__" [global] @2:4
+ │ │ │ └─ Identifier "__proto__" @2:4
│ │ └─ alias
│ │ └─ Identifier "x" [global] (var) @2:15
│ └─ entry
│ ├─ name
- │ │ └─ Identifier "__proto__" [global] @2:18
+ │ │ └─ Identifier "__proto__" @2:18
│ └─ alias
│ └─ Identifier "y" [global] (var) @2:29
└─ ObjectExpression @2:35
diff --git a/Tests/LibJS/Bytecode/expected/annex-b-function-in-if.txt b/Tests/LibJS/Bytecode/expected/annex-b-function-in-if.txt
index 15636a537c2..e9858bae570 100644
--- a/Tests/LibJS/Bytecode/expected/annex-b-function-in-if.txt
+++ b/Tests/LibJS/Bytecode/expected/annex-b-function-in-if.txt
@@ -1,5 +1,5 @@
-$80e4413e annex-b-function-in-if.js:13:1
- Registers: 11
+$7e20502e annex-b-function-in-if.js:13:1
+ Registers: 9
Blocks: 1
Constants:
[0] = Undefined
@@ -8,55 +8,44 @@ $80e4413e annex-b-function-in-if.js:13:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `annexBFunctionInIf`
- [ 40] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, annexBFunctionInIf, arguments:[Bool(true)]
- [ 68] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 90] GetGlobal value_feedback:5, dst:reg6, `console`
- [ a0] GetById value_feedback:6, dst:reg8, base:reg6, `log` (console.log)
- [ b8] GetGlobal value_feedback:7, dst:reg10, `annexBFunctionInIf`
- [ c8] Call value_feedback:8, call_feedback:2, dst:reg9, callee:reg10, this_value:Undefined, annexBFunctionInIf, arguments:[Bool(false)]
- [ f0] Call value_feedback:9, call_feedback:3, dst:reg7, callee:reg8, this_value:reg6, console.log, arguments:[reg9]
- [ 118] End value:reg7
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `annexBFunctionInIf`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined, arguments:[Bool(true)]
+ [ 78] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ a0] GetGlobal value_feedback:5, dst:reg6, `console`
+ [ b0] GetById value_feedback:6, dst:reg7, base:reg6, `log`
+ [ c8] GetGlobal value_feedback:7, dst:reg8, `annexBFunctionInIf`
+ [ d8] Call value_feedback:8, call_feedback:2, dst:reg8, callee:reg8, this_value:Undefined, arguments:[Bool(false)]
+ [ 100] Call value_feedback:9, call_feedback:3, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 128] End value:reg5
-annexBFunctionInIf$6dccc7b1 annex-b-function-in-if.js:2:5
- Registers: 8
+annexBFunctionInIf$c86c2a51 annex-b-function-in-if.js:2:10
+ Registers: 6
Blocks: 4
+ Locals: inner~0, inner~1, inner~2
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateVariable `inner`, is_immutable:false, is_global:false, is_strict:false
- [ 20] InitializeVariableBinding `inner`, src:Undefined
- [ 38] JumpFalse condition:arg0, target:block2
+ [ 8] Mov dst:inner~0, src:Undefined
+ [ 18] JumpFalse condition:arg0, target:block2
block1:
- [ 48] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 60] CreateMutableBinding environment:reg5, `inner`, can_be_deleted:false
- [ 70] NewFunction dst:reg6, shared_function_data_index:0
- [ 88] InitializeLexicalBinding `inner`, src:reg6
- [ a0] GetBinding value_feedback:0, dst:reg6, `inner`
- [ b8] SetVariableBinding `inner`, src:reg6
- [ d0] SetLexicalEnvironment environment:reg4
- [ d8] Jump target:block3
+ [ 28] NewFunction dst:inner~1, shared_function_data_index:0
+ [ 40] Mov dst:inner~0, src:inner~1
+ [ 50] Jump target:block3
block2:
- [ e0] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ f8] CreateMutableBinding environment:reg5, `inner`, can_be_deleted:false
- [ 108] NewFunction dst:reg6, shared_function_data_index:1
- [ 120] InitializeLexicalBinding `inner`, src:reg6
- [ 138] GetBinding value_feedback:1, dst:reg6, `inner`
- [ 150] SetVariableBinding `inner`, src:reg6
- [ 168] SetLexicalEnvironment environment:reg4
+ [ 58] NewFunction dst:inner~2, shared_function_data_index:1
+ [ 70] Mov dst:inner~0, src:inner~2
block3:
- [ 170] GetCalleeAndThisFromEnvironment value_feedback:2, callee:reg6, this_value:reg7, `inner`
- [ 188] Call value_feedback:3, call_feedback:0, dst:reg5, callee:reg6, this_value:reg7, inner
- [ 1a8] Return value:reg5
+ [ 80] Call value_feedback:0, call_feedback:0, dst:reg5, callee:inner~0, this_value:Undefined
+ [ a0] Return value:reg5
inner$3192ffc2 annex-b-function-in-if.js:4:13
diff --git a/Tests/LibJS/Bytecode/expected/annexb-function-existing-var.txt b/Tests/LibJS/Bytecode/expected/annexb-function-existing-var.txt
index 9a08ad3f445..66b41861248 100644
--- a/Tests/LibJS/Bytecode/expected/annexb-function-existing-var.txt
+++ b/Tests/LibJS/Bytecode/expected/annexb-function-existing-var.txt
@@ -1,4 +1,4 @@
-$d36729be annexb-function-existing-var.js:10:1
+$d0a338ae annexb-function-existing-var.js:10:1
Registers: 7
Blocks: 1
Constants:
@@ -6,14 +6,16 @@ $d36729be annexb-function-existing-var.js:10:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `test`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, test
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `test`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-test$aa255e47 annexb-function-existing-var.js:2:5
- Registers: 7
+test$7e3c78a8 annexb-function-existing-var.js:2:9
+ Registers: 5
Blocks: 1
+ Locals: f~0, f~1
Constants:
[0] = Undefined
[1] = Int32(123)
@@ -21,16 +23,8 @@ test$aa255e47 annexb-function-existing-var.js:2:5
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateVariable `f`, is_immutable:false, is_global:false, is_strict:false
- [ 20] InitializeVariableBinding `f`, src:Undefined
- [ 38] SetLexicalBinding `f`, src:Int32(123)
- [ 50] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 68] CreateMutableBinding environment:reg5, `f`, can_be_deleted:false
- [ 78] NewFunction dst:reg6, shared_function_data_index:0
- [ 90] InitializeLexicalBinding `f`, src:reg6
- [ a8] GetBinding value_feedback:0, dst:reg6, `f`
- [ c0] SetVariableBinding `f`, src:reg6
- [ d8] SetLexicalEnvironment environment:reg4
- [ e0] GetInitializedBinding value_feedback:1, dst:reg5, `f`
- [ f8] Return value:reg5
+ [ 8] Mov dst:f~0, src:Undefined
+ [ 18] Mov dst:f~0, src:Int32(123)
+ [ 28] NewFunction dst:f~1, shared_function_data_index:0
+ [ 40] Mov dst:f~0, src:f~1
+ [ 50] Return value:f~0
diff --git a/Tests/LibJS/Bytecode/expected/annexb-var-coordinate-with-default-param.txt b/Tests/LibJS/Bytecode/expected/annexb-var-coordinate-with-default-param.txt
index c77f0afd6c9..40eba95a136 100644
--- a/Tests/LibJS/Bytecode/expected/annexb-var-coordinate-with-default-param.txt
+++ b/Tests/LibJS/Bytecode/expected/annexb-var-coordinate-with-default-param.txt
@@ -1,4 +1,4 @@
-$c7fd0018 annexb-var-coordinate-with-default-param.js:12:1
+$c5390f08 annexb-var-coordinate-with-default-param.js:12:1
Registers: 7
Blocks: 1
Constants:
@@ -6,14 +6,16 @@ $c7fd0018 annexb-var-coordinate-with-default-param.js:12:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-f$bf4d852d annexb-var-coordinate-with-default-param.js:4:5
- Registers: 10
+f$7d6f9ea4 annexb-var-coordinate-with-default-param.js:3:12
+ Registers: 7
Blocks: 3
+ Locals: g~0, g~1
Constants:
[0] = Int32(1)
[1] = Undefined
@@ -22,40 +24,33 @@ f$bf4d852d annexb-var-coordinate-with-default-param.js:4:5
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
- [ 38] JumpUndefined condition:arg0, true_target:block1, false_target:block2
+ [ 8] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
+ [ 18] GetLexicalEnvironment dst:reg4
+ [ 20] JumpUndefined condition:arg0, true_target:block1, false_target:block2
block1:
- [ 48] Mov dst:arg0, src:Int32(1)
+ [ 30] Mov dst:arg0, src:Int32(1)
block2:
- [ 58] InitializeLexicalBinding `x`, src:arg0
- [ 70] CreateVariable `g`, is_immutable:false, is_global:false, is_strict:false
- [ 80] InitializeVariableBinding `g`, src:Undefined
- [ 98] CreateLexicalEnvironment dst:reg6, parent:reg5, capacity:1, is_catch_environment:false
- [ b0] CreateVariable `y`, is_immutable:false, is_global:false, is_strict:false
- [ c0] InitializeLexicalBinding `y`, src:Int32(2)
- [ d8] CreateLexicalEnvironment dst:reg7, parent:reg6, capacity:1, is_catch_environment:false
- [ f0] CreateMutableBinding environment:reg7, `g`, can_be_deleted:false
- [ 100] NewFunction dst:reg8, shared_function_data_index:0
- [ 118] InitializeLexicalBinding `g`, src:reg8
- [ 130] GetBinding value_feedback:0, dst:reg8, `g`
- [ 148] SetVariableBinding `g`, src:reg8
- [ 160] SetLexicalEnvironment environment:reg6
- [ 168] GetCalleeAndThisFromEnvironment value_feedback:1, callee:reg8, this_value:reg9, `g`
- [ 180] Call value_feedback:2, call_feedback:0, dst:reg7, callee:reg8, this_value:reg9, g
- [ 1a0] Return value:reg7
+ [ 40] InitializeLexicalBinding `x`, src:arg0
+ [ 58] CreateVariableEnvironment capacity:1
+ [ 60] GetLexicalEnvironment dst:reg5
+ [ 68] Mov dst:g~0, src:Undefined
+ [ 78] CreateVariable `y`, is_immutable:false, is_global:false, is_strict:false
+ [ 88] InitializeLexicalBinding `y`, src:Int32(2)
+ [ a0] NewFunction dst:g~1, shared_function_data_index:0
+ [ b8] Mov dst:g~0, src:g~1
+ [ c8] Call value_feedback:0, call_feedback:0, dst:reg6, callee:g~0, this_value:Undefined
+ [ e8] Return value:reg6
g$27f07b98 annexb-var-coordinate-with-default-param.js:7:13
- Registers: 8
+ Registers: 7
Blocks: 1
block0:
[ 0] Enter
[ 8] GetBinding value_feedback:0, dst:reg5, `x`
[ 20] GetBinding value_feedback:1, dst:reg6, `y`
- [ 38] Add arith_feedback:0, dst:reg7, lhs:reg5, rhs:reg6
- [ 48] Return value:reg7
+ [ 38] Add arith_feedback:0, dst:reg5, lhs:reg5, rhs:reg6
+ [ 48] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/argument-postfix-self-move.txt b/Tests/LibJS/Bytecode/expected/argument-postfix-self-move.txt
index 5091a00967f..afe664e93cd 100644
--- a/Tests/LibJS/Bytecode/expected/argument-postfix-self-move.txt
+++ b/Tests/LibJS/Bytecode/expected/argument-postfix-self-move.txt
@@ -1,4 +1,4 @@
-$9431c529 argument-postfix-self-move.js:5:1
+$916dd419 argument-postfix-self-move.js:5:1
Registers: 7
Blocks: 1
Constants:
@@ -7,16 +7,17 @@ $9431c529 argument-postfix-self-move.js:5:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[Int32(10)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(10)]
+ [ 50] End value:reg5
-f$049d7b6f argument-postfix-self-move.js:2:6
- Registers: 6
+f$7aefafb7 argument-postfix-self-move.js:2:6
+ Registers: 5
Blocks: 1
block0:
[ 0] Enter
- [ 8] PostfixDecrement arith_feedback:0, dst:reg5, src:arg0
- [ 18] Return value:arg0
+ [ 8] Decrement arith_feedback:0, dst:arg0
+ [ 10] Return value:arg0
diff --git a/Tests/LibJS/Bytecode/expected/argument-variables.txt b/Tests/LibJS/Bytecode/expected/argument-variables.txt
index fc3ad9fe99e..214c6ebf405 100644
--- a/Tests/LibJS/Bytecode/expected/argument-variables.txt
+++ b/Tests/LibJS/Bytecode/expected/argument-variables.txt
@@ -1,5 +1,5 @@
-$bced3bd8 argument-variables.js:12:1
- Registers: 8
+$ba294ac8 argument-variables.js:12:1
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
@@ -8,11 +8,12 @@ $bced3bd8 argument-variables.js:12:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `identity`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, identity, arguments:[Int32(1)]
- [ 40] GetGlobal value_feedback:2, dst:reg7, `swap`
- [ 50] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, swap, arguments:[Int32(1), Int32(2)]
- [ 78] End value:reg6
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `identity`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(1)]
+ [ 50] GetGlobal value_feedback:2, dst:reg6, `swap`
+ [ 60] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(1), Int32(2)]
+ [ 88] End value:reg5
identity$f6a18ea3 argument-variables.js:5:5
diff --git a/Tests/LibJS/Bytecode/expected/arguments-with-arguments-fn.txt b/Tests/LibJS/Bytecode/expected/arguments-with-arguments-fn.txt
index 80a9722c223..32c90bd3c60 100644
--- a/Tests/LibJS/Bytecode/expected/arguments-with-arguments-fn.txt
+++ b/Tests/LibJS/Bytecode/expected/arguments-with-arguments-fn.txt
@@ -1,4 +1,4 @@
-$2b997e90 arguments-with-arguments-fn.js:4:1
+$28d58d80 arguments-with-arguments-fn.js:4:1
Registers: 7
Blocks: 1
Constants:
@@ -6,13 +6,14 @@ $2b997e90 arguments-with-arguments-fn.js:4:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-f$f684b66b
- Registers: 6
+f$a062956e arguments-with-arguments-fn.js:1:12
+ Registers: 5
Blocks: 3
Locals: arguments~0
Constants:
@@ -27,6 +28,6 @@ block1:
[ 18] Mov dst:arg0, src:Int32(1)
block2:
- [ 28] Mov2 c0_dst:reg5, c0_src:Undefined, c1_dst:arguments~0, c1_src:reg5
- [ 40] NewFunction dst:arguments~0, shared_function_data_index:0
- [ 58] End value:Undefined
+ [ 28] Mov dst:arguments~0, src:Undefined
+ [ 38] NewFunction dst:arguments~0, shared_function_data_index:0
+ [ 50] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/assign-to-argument-no-tdz.txt b/Tests/LibJS/Bytecode/expected/assign-to-argument-no-tdz.txt
index ab43ae13025..0472dd23816 100644
--- a/Tests/LibJS/Bytecode/expected/assign-to-argument-no-tdz.txt
+++ b/Tests/LibJS/Bytecode/expected/assign-to-argument-no-tdz.txt
@@ -1,4 +1,4 @@
-$393b7f47 assign-to-argument-no-tdz.js:11:1
+$36778e37 assign-to-argument-no-tdz.js:11:1
Registers: 7
Blocks: 1
Constants:
@@ -7,12 +7,13 @@ $393b7f47 assign-to-argument-no-tdz.js:11:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[Int32(0)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(0)]
+ [ 50] End value:reg5
-f$c32e6900 assign-to-argument-no-tdz.js:6:5
+f$d1ced614 assign-to-argument-no-tdz.js:6:9
Registers: 5
Blocks: 1
Locals: y~0
@@ -21,5 +22,6 @@ f$c32e6900 assign-to-argument-no-tdz.js:6:5
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:y~0, c0_src:Int32(1), c1_dst:arg0, c1_src:y~0
- [ 20] Return value:arg0
+ [ 8] Mov dst:y~0, src:Int32(1)
+ [ 18] Mov dst:arg0, src:y~0
+ [ 28] Return value:arg0
diff --git a/Tests/LibJS/Bytecode/expected/assign-to-let-variable-tdz.txt b/Tests/LibJS/Bytecode/expected/assign-to-let-variable-tdz.txt
index 77a900ddac1..3dd64d367ac 100644
--- a/Tests/LibJS/Bytecode/expected/assign-to-let-variable-tdz.txt
+++ b/Tests/LibJS/Bytecode/expected/assign-to-let-variable-tdz.txt
@@ -1,4 +1,4 @@
-$bced3bd8 assign-to-let-variable-tdz.js:12:1
+$ba294ac8 assign-to-let-variable-tdz.js:12:1
Registers: 8
Blocks: 1
Constants:
@@ -7,41 +7,41 @@ $bced3bd8 assign-to-let-variable-tdz.js:12:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] NewObject dst:reg7
- [ 28] InitObjectLiteralProperty object:reg7, `location`, src:String("hello"), shape_cache_index:0, property_slot:0
- [ 40] CacheObjectShape object:reg7
- [ 50] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[reg7]
- [ 78] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] NewObject dst:reg7
+ [ 38] InitObjectLiteralProperty object:reg7, `location`, src:String("hello"), shape_cache_index:0, property_slot:0
+ [ 50] CacheObjectShape object:reg7
+ [ 60] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 88] End value:reg5
-f$4fb9ed69 assign-to-let-variable-tdz.js:7:5
- Registers: 10
+f$d11be5f1 assign-to-let-variable-tdz.js:7:5
+ Registers: 7
Blocks: 3
Locals: a~0
Constants:
- [0] = String("string")
- [1] = Undefined
+ [0] = <Empty>
+ [1] = String("string")
+ [2] = Undefined
block0:
[ 0] Enter
- [ 8] ThrowIfNullish src:arg0
- [ 10] Mov dst:reg5, src:arg0
- [ 20] GetById value_feedback:0, dst:reg6, base:reg5, `location`
- [ 38] Mov dst:a~0, src:reg6
+ [ 8] Mov dst:a~0, src:<Empty>
+ [ 18] ThrowIfNullish src:arg0
+ [ 20] Mov dst:reg5, src:arg0
+ [ 30] GetById value_feedback:0, dst:a~0, base:reg5, `location`
[ 48] Typeof dst:reg5, src:a~0
- [ 58] LooselyEquals arith_feedback:0, dst:reg6, lhs:String("string"), rhs:reg5
- [ 68] Mov dst:reg5, src:reg6
- [ 78] JumpFalse condition:reg6, target:block2
+ [ 58] LooselyEquals arith_feedback:0, dst:reg5, lhs:String("string"), rhs:reg5
+ [ 68] JumpFalse condition:reg5, target:block2
block1:
- [ 88] GetGlobal value_feedback:1, dst:reg8, `g`
- [ 98] Mov dst:reg9, src:a~0
- [ a8] Call value_feedback:2, call_feedback:0, dst:reg7, callee:reg8, this_value:Undefined, g, arguments:[reg9]
- [ d0] Mov2 c0_dst:a~0, c0_src:reg7, c1_dst:reg5, c1_src:reg7
+ [ 78] GetGlobal value_feedback:1, dst:reg6, `g`
+ [ 88] Call value_feedback:2, call_feedback:0, dst:a~0, callee:reg6, this_value:Undefined, arguments:[a~0]
+ [ b0] Mov dst:reg5, src:a~0
block2:
- [ e8] Return value:a~0
+ [ c0] Return value:a~0
g$702c1d97 assign-to-let-variable-tdz.js:4:17
diff --git a/Tests/LibJS/Bytecode/expected/assign-to-parameter.txt b/Tests/LibJS/Bytecode/expected/assign-to-parameter.txt
index 894d070c258..187d26fdfe2 100644
--- a/Tests/LibJS/Bytecode/expected/assign-to-parameter.txt
+++ b/Tests/LibJS/Bytecode/expected/assign-to-parameter.txt
@@ -1,4 +1,4 @@
-$162ec0dc assign-to-parameter.js:8:1
+$136acfcc assign-to-parameter.js:8:1
Registers: 7
Blocks: 1
Constants:
@@ -6,9 +6,10 @@ $162ec0dc assign-to-parameter.js:8:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `isect`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, isect
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `isect`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
isect$cb769f09 assign-to-parameter.js:5:9
diff --git a/Tests/LibJS/Bytecode/expected/async-await-in-try-catch.txt b/Tests/LibJS/Bytecode/expected/async-await-in-try-catch.txt
index 517e3eb225f..65c7e45ec9e 100644
--- a/Tests/LibJS/Bytecode/expected/async-await-in-try-catch.txt
+++ b/Tests/LibJS/Bytecode/expected/async-await-in-try-catch.txt
@@ -1,4 +1,4 @@
-$793f2555 async-await-in-try-catch.js:9:1
+$818af885 async-await-in-try-catch.js:9:1
Registers: 8
Blocks: 1
Constants:
@@ -6,50 +6,54 @@ $793f2555 async-await-in-try-catch.js:9:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] NewObject dst:reg7
- [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[reg7]
- [ 50] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] NewObject dst:reg7
+ [ 38] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 60] End value:reg5
-f$0ae4b9bc async-await-in-try-catch.js:2:5
+f$055cd79c async-await-in-try-catch.js:2:5
Registers: 10
Blocks: 7
Locals: e~0
Constants:
[0] = Int32(1)
- [1] = Undefined
+ [1] = <Empty>
+ [2] = Undefined
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] Jump target:block3
block1:
- [ 18] Catch value_feedback:0, dst:reg5
- [ 20] SetLexicalEnvironment environment:reg4
- [ 28] Mov dst:e~0, src:reg5
+ [ 10] EnterObjectEnvironment dst:reg5, object:arg0
+ [ 20] Mov dst:reg6, src:reg0
+ [ 30] Await continuation_label:block2, argument:Int32(1)
block2:
- [ 38] Yield value:Undefined
+ [ 40] Mov dst:reg6, src:reg0
+ [ 50] GetCompletionFields type_dst:reg7, value_dst:reg8, completion:reg6
+ [ 60] StrictlyEqualsRhsInt32 arith_feedback:0, dst:reg9, lhs:reg7, rhs:1
+ [ 70] JumpIf condition:reg9, true_target:block4, false_target:block3
block3:
- [ 48] EnterObjectEnvironment dst:reg5, object:arg0
- [ 58] Mov dst:reg6, src:reg0
- [ 68] Await continuation_label:block4, argument:Int32(1)
+ [ 80] Throw src:reg8
block4:
- [ 78] Mov dst:reg6, src:reg0
- [ 88] GetCompletionFields type_dst:reg7, value_dst:reg8, completion:reg6
- [ 98] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg7, rhs:1, true_target:block5, false_target:block6
+ [ 88] Mov dst:reg6, src:reg8
+ [ 98] SetLexicalEnvironment environment:reg4
+ [ a0] Jump target:block6
block5:
+ [ a8] Catch value_feedback:0, dst:reg5
[ b0] SetLexicalEnvironment environment:reg4
- [ b8] JumpLoop target:block2
+ [ b8] Mov dst:e~0, src:<Empty>
+ [ c8] Mov dst:e~0, src:reg5
+ [ d8] Jump target:block6
block6:
- [ c0] SetLexicalEnvironment environment:reg4
- [ c8] Throw src:reg8
+ [ e0] Yield value:Undefined
Exception handlers:
- [ 48 .. d0] => handler block1
+ [ 10 .. a8] => handler block5
diff --git a/Tests/LibJS/Bytecode/expected/async-await.txt b/Tests/LibJS/Bytecode/expected/async-await.txt
index 4e3acd53f63..79d6aff327d 100644
--- a/Tests/LibJS/Bytecode/expected/async-await.txt
+++ b/Tests/LibJS/Bytecode/expected/async-await.txt
@@ -1,4 +1,4 @@
-$fd650eed async-await.js:9:1
+$faa11ddd async-await.js:9:1
Registers: 7
Blocks: 1
Constants:
@@ -6,12 +6,13 @@ $fd650eed async-await.js:9:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-f$d11be5f1 async-await.js:7:5
+f$4cf5fc59 async-await.js:7:5
Registers: 10
Blocks: 4
Constants:
@@ -20,19 +21,21 @@ f$d11be5f1 async-await.js:7:5
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `Promise`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `resolve` (Promise.resolve)
- [ 30] Call value_feedback:2, call_feedback:0, dst:reg5, callee:reg7, this_value:reg6, Promise.resolve, arguments:[Int32(42)]
- [ 58] Mov dst:reg7, src:reg0
+ [ 8] GetGlobal value_feedback:0, dst:reg5, `Promise`
+ [ 18] GetById value_feedback:1, dst:reg6, base:reg5, `resolve`
+ [ 30] Call value_feedback:2, call_feedback:0, dst:reg5, callee:reg6, this_value:reg5, arguments:[Int32(42)]
+ [ 58] Mov dst:reg6, src:reg0
[ 68] Await continuation_label:block1, argument:reg5
block1:
- [ 78] Mov dst:reg7, src:reg0
- [ 88] GetCompletionFields type_dst:reg6, value_dst:reg8, completion:reg7
- [ 98] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg6, rhs:1, true_target:block2, false_target:block3
+ [ 78] Mov dst:reg6, src:reg0
+ [ 88] GetCompletionFields type_dst:reg7, value_dst:reg8, completion:reg6
+ [ 98] StrictlyEqualsRhsInt32 arith_feedback:0, dst:reg9, lhs:reg7, rhs:1
+ [ a8] JumpIf condition:reg9, true_target:block3, false_target:block2
block2:
- [ b0] Yield value:reg8
+ [ b8] Throw src:reg8
block3:
- [ c0] Throw src:reg8
+ [ c0] Mov dst:reg5, src:reg8
+ [ d0] Yield value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/async-generator-yield-await.txt b/Tests/LibJS/Bytecode/expected/async-generator-yield-await.txt
index 4d5c95e41d7..c91e342625c 100644
--- a/Tests/LibJS/Bytecode/expected/async-generator-yield-await.txt
+++ b/Tests/LibJS/Bytecode/expected/async-generator-yield-await.txt
@@ -1,4 +1,4 @@
-$6a33dffa async-generator-yield-await.js:6:1
+$676feeea async-generator-yield-await.js:6:1
Registers: 7
Blocks: 1
Constants:
@@ -7,13 +7,14 @@ $6a33dffa async-generator-yield-await.js:6:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[Int32(1)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(1)]
+ [ 50] End value:reg5
-f$f201c4ec async-generator-yield-await.js:4:5
- Registers: 12
+f$62cc1714 async-generator-yield-await.js:4:5
+ Registers: 15
Blocks: 19
Constants:
[0] = Undefined
@@ -26,67 +27,76 @@ block0:
[ 8] Yield continuation_label:block1, value:Undefined
block1:
- [ 18] Mov dst:reg8, src:reg0
+ [ 18] Mov dst:reg5, src:reg0
[ 28] Await continuation_label:block2, argument:arg0
block2:
- [ 38] Mov dst:reg8, src:reg0
- [ 48] GetCompletionFields type_dst:reg9, value_dst:reg10, completion:reg8
- [ 58] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg9, rhs:1, true_target:block3, false_target:block4
+ [ 38] Mov dst:reg5, src:reg0
+ [ 48] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
+ [ 58] StrictlyEqualsRhsInt32 arith_feedback:0, dst:reg8, lhs:reg6, rhs:1
+ [ 68] JumpIf condition:reg8, true_target:block4, false_target:block3
block3:
- [ 70] Await continuation_label:block6, argument:reg10
+ [ 78] Throw src:reg7
block4:
- [ 80] Throw src:reg10
+ [ 80] Mov dst:reg5, src:reg7
+ [ 90] Await continuation_label:block5, argument:reg5
block5:
- [ 88] Mov dst:reg5, src:reg0
- [ 98] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
- [ a8] JumpStrictlyEqualsRhsInt32 arith_feedback:5, lhs:reg6, rhs:1, true_target:block15, false_target:block16
+ [ a0] Mov dst:reg6, src:reg0
+ [ b0] GetCompletionFields type_dst:reg7, value_dst:reg8, completion:reg6
+ [ c0] StrictlyEqualsRhsInt32 arith_feedback:1, dst:reg9, lhs:reg7, rhs:1
+ [ d0] JumpIf condition:reg9, true_target:block7, false_target:block6
block6:
- [ c0] Mov dst:reg5, src:reg0
- [ d0] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
- [ e0] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg6, rhs:1, true_target:block7, false_target:block8
+ [ e0] Throw src:reg8
block7:
- [ f8] Yield continuation_label:block9, value:reg7
+ [ e8] Yield continuation_label:block8, value:reg8
block8:
- [ 108] Throw src:reg7
+ [ f8] Mov dst:reg6, src:reg0
+ [ 108] GetCompletionFields type_dst:reg7, value_dst:reg8, completion:reg6
+ [ 118] StrictlyInequalsRhsInt32 arith_feedback:2, dst:reg10, lhs:reg7, rhs:4
+ [ 128] JumpIf condition:reg10, true_target:block14, false_target:block9
block9:
- [ 110] Mov dst:reg5, src:reg0
- [ 120] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
- [ 130] JumpStrictlyInequalsLoopRhsInt32 arith_feedback:2, lhs:reg6, rhs:4, true_target:block5, false_target:block10
+ [ 138] Await continuation_label:block10, argument:reg8
block10:
- [ 148] Await continuation_label:block11, argument:reg7
+ [ 148] Mov dst:reg6, src:reg0
+ [ 158] GetCompletionFields type_dst:reg7, value_dst:reg8, completion:reg6
+ [ 168] StrictlyEqualsRhsInt32 arith_feedback:3, dst:reg11, lhs:reg7, rhs:1
+ [ 178] JumpIf condition:reg11, true_target:block12, false_target:block11
block11:
- [ 158] Mov dst:reg5, src:reg0
- [ 168] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
- [ 178] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg6, rhs:1, true_target:block12, false_target:block13
+ [ 188] Throw src:reg8
block12:
- [ 190] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:4, lhs:reg6, rhs:5, true_target:block5, false_target:block14
+ [ 190] StrictlyEqualsRhsInt32 arith_feedback:4, dst:reg12, lhs:reg7, rhs:5
+ [ 1a0] JumpIf condition:reg12, true_target:block14, false_target:block13
block13:
- [ 1a8] Throw src:reg7
+ [ 1b0] SetCompletionType completion:reg6
+ [ 1c0] Jump target:block14
block14:
- [ 1b0] SetCompletionType completion:reg5
- [ 1c0] JumpLoop target:block5
+ [ 1c8] Mov dst:reg6, src:reg0
+ [ 1d8] GetCompletionFields type_dst:reg7, value_dst:reg8, completion:reg6
+ [ 1e8] StrictlyEqualsRhsInt32 arith_feedback:5, dst:reg13, lhs:reg7, rhs:1
+ [ 1f8] JumpIf condition:reg13, true_target:block18, false_target:block15
block15:
- [ 1c8] Yield value:Undefined
+ [ 208] StrictlyEqualsRhsInt32 arith_feedback:6, dst:reg14, lhs:reg7, rhs:5
+ [ 218] JumpIf condition:reg14, true_target:block16, false_target:block17
block16:
- [ 1d8] JumpStrictlyEqualsRhsInt32 arith_feedback:6, lhs:reg6, rhs:5, true_target:block17, false_target:block18
+ [ 228] Throw src:reg8
block17:
- [ 1f0] Throw src:reg7
+ [ 230] Yield value:reg8
block18:
- [ 1f8] Yield value:reg7
+ [ 240] Mov dst:reg5, src:reg8
+ [ 250] Yield value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/async-generator-yield.txt b/Tests/LibJS/Bytecode/expected/async-generator-yield.txt
index 6683e0c3055..3dcb9f60ac0 100644
--- a/Tests/LibJS/Bytecode/expected/async-generator-yield.txt
+++ b/Tests/LibJS/Bytecode/expected/async-generator-yield.txt
@@ -1,4 +1,4 @@
-$516a2e0b async-generator-yield.js:7:1
+$4ea63cfb async-generator-yield.js:7:1
Registers: 7
Blocks: 1
Constants:
@@ -7,13 +7,14 @@ $516a2e0b async-generator-yield.js:7:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[Int32(1)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(1)]
+ [ 50] End value:reg5
-f$28b66ca8 async-generator-yield.js:5:5
- Registers: 10
+f$1da6a868 async-generator-yield.js:5:5
+ Registers: 14
Blocks: 16
Constants:
[0] = Undefined
@@ -26,55 +27,62 @@ block0:
[ 8] Yield continuation_label:block1, value:Undefined
block1:
- [ 18] Await continuation_label:block3, argument:arg0
+ [ 18] Await continuation_label:block2, argument:arg0
block2:
[ 28] Mov dst:reg5, src:reg0
[ 38] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
- [ 48] JumpStrictlyEqualsRhsInt32 arith_feedback:4, lhs:reg6, rhs:1, true_target:block12, false_target:block13
+ [ 48] StrictlyEqualsRhsInt32 arith_feedback:0, dst:reg8, lhs:reg6, rhs:1
+ [ 58] JumpIf condition:reg8, true_target:block4, false_target:block3
block3:
- [ 60] Mov dst:reg5, src:reg0
- [ 70] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
- [ 80] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg6, rhs:1, true_target:block4, false_target:block5
+ [ 68] Throw src:reg7
block4:
- [ 98] Yield continuation_label:block6, value:reg7
+ [ 70] Yield continuation_label:block5, value:reg7
block5:
- [ a8] Throw src:reg7
+ [ 80] Mov dst:reg5, src:reg0
+ [ 90] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
+ [ a0] StrictlyInequalsRhsInt32 arith_feedback:1, dst:reg9, lhs:reg6, rhs:4
+ [ b0] JumpIf condition:reg9, true_target:block11, false_target:block6
block6:
- [ b0] Mov dst:reg5, src:reg0
- [ c0] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
- [ d0] JumpStrictlyInequalsLoopRhsInt32 arith_feedback:1, lhs:reg6, rhs:4, true_target:block2, false_target:block7
+ [ c0] Await continuation_label:block7, argument:reg7
block7:
- [ e8] Await continuation_label:block8, argument:reg7
+ [ d0] Mov dst:reg5, src:reg0
+ [ e0] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
+ [ f0] StrictlyEqualsRhsInt32 arith_feedback:2, dst:reg10, lhs:reg6, rhs:1
+ [ 100] JumpIf condition:reg10, true_target:block9, false_target:block8
block8:
- [ f8] Mov dst:reg5, src:reg0
- [ 108] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
- [ 118] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:reg6, rhs:1, true_target:block9, false_target:block10
+ [ 110] Throw src:reg7
block9:
- [ 130] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:3, lhs:reg6, rhs:5, true_target:block2, false_target:block11
+ [ 118] StrictlyEqualsRhsInt32 arith_feedback:3, dst:reg11, lhs:reg6, rhs:5
+ [ 128] JumpIf condition:reg11, true_target:block11, false_target:block10
block10:
- [ 148] Throw src:reg7
+ [ 138] SetCompletionType completion:reg5
+ [ 148] Jump target:block11
block11:
- [ 150] SetCompletionType completion:reg5
- [ 160] JumpLoop target:block2
+ [ 150] Mov dst:reg5, src:reg0
+ [ 160] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
+ [ 170] StrictlyEqualsRhsInt32 arith_feedback:4, dst:reg12, lhs:reg6, rhs:1
+ [ 180] JumpIf condition:reg12, true_target:block15, false_target:block12
block12:
- [ 168] Yield value:Undefined
+ [ 190] StrictlyEqualsRhsInt32 arith_feedback:5, dst:reg13, lhs:reg6, rhs:5
+ [ 1a0] JumpIf condition:reg13, true_target:block13, false_target:block14
block13:
- [ 178] JumpStrictlyEqualsRhsInt32 arith_feedback:5, lhs:reg6, rhs:5, true_target:block14, false_target:block15
+ [ 1b0] Throw src:reg7
block14:
- [ 190] Throw src:reg7
+ [ 1b8] Yield value:reg7
block15:
- [ 198] Yield value:reg7
+ [ 1c8] Mov dst:reg5, src:reg7
+ [ 1d8] Yield value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/async-return-bare.txt b/Tests/LibJS/Bytecode/expected/async-return-bare.txt
index ef12578fe97..4e4527deab2 100644
--- a/Tests/LibJS/Bytecode/expected/async-return-bare.txt
+++ b/Tests/LibJS/Bytecode/expected/async-return-bare.txt
@@ -1,4 +1,4 @@
-$2b997e90 async-return-bare.js:4:1
+$28d58d80 async-return-bare.js:4:1
Registers: 7
Blocks: 1
Constants:
@@ -6,9 +6,10 @@ $2b997e90 async-return-bare.js:4:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
f$68537474 async-return-bare.js:2:5
diff --git a/Tests/LibJS/Bytecode/expected/baseline.txt b/Tests/LibJS/Bytecode/expected/baseline.txt
index 36856f9c5d9..ef5342160ae 100644
--- a/Tests/LibJS/Bytecode/expected/baseline.txt
+++ b/Tests/LibJS/Bytecode/expected/baseline.txt
@@ -1,5 +1,5 @@
-$865e0fd9 baseline.js:5:1
- Registers: 10
+$8ea9e309 baseline.js:5:1
+ Registers: 9
Blocks: 1
Constants:
[0] = Undefined
@@ -8,12 +8,13 @@ $865e0fd9 baseline.js:5:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `add`
- [ 40] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, add, arguments:[Int32(1), Int32(2)]
- [ 68] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 90] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `add`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined, arguments:[Int32(1), Int32(2)]
+ [ 78] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ a0] End value:reg5
add$1b0f3483 baseline.js:2:5
diff --git a/Tests/LibJS/Bytecode/expected/bigint-binary-literal-fold.txt b/Tests/LibJS/Bytecode/expected/bigint-binary-literal-fold.txt
index 9cfccc5d5f3..64482086493 100644
--- a/Tests/LibJS/Bytecode/expected/bigint-binary-literal-fold.txt
+++ b/Tests/LibJS/Bytecode/expected/bigint-binary-literal-fold.txt
@@ -1,11 +1,14 @@
-$4e59e625
- Registers: 5
+$6ed542b5 bigint-binary-literal-fold.js:1:1
+ Registers: 6
Blocks: 1
Constants:
- [0] = BigInt(3n)
- [1] = BigInt(1n)
+ [0] = Undefined
+ [1] = BigInt(3n)
[2] = BigInt(1n)
+ [3] = BigInt(1n)
block0:
[ 0] Enter
- [ 8] End value:BigInt(1n)
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:BigInt(1n)
+ [ 28] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/bigint-constant-folding.txt b/Tests/LibJS/Bytecode/expected/bigint-constant-folding.txt
index 80759b7113c..24e02d6f23f 100644
--- a/Tests/LibJS/Bytecode/expected/bigint-constant-folding.txt
+++ b/Tests/LibJS/Bytecode/expected/bigint-constant-folding.txt
@@ -1,43 +1,44 @@
-$87b8bc45 bigint-constant-folding.js:1:1
- Registers: 5
+$0f6f4eb1 bigint-constant-folding.js:1:5
+ Registers: 6
Blocks: 1
Constants:
- [0] = BigInt(1n)
- [1] = BigInt(2n)
- [2] = BigInt(3n)
- [3] = BigInt(10n)
- [4] = BigInt(3n)
- [5] = BigInt(7n)
- [6] = BigInt(2n)
- [7] = BigInt(3n)
- [8] = BigInt(6n)
- [9] = BigInt(10n)
- [10] = BigInt(3n)
+ [0] = Undefined
+ [1] = BigInt(1n)
+ [2] = BigInt(2n)
+ [3] = BigInt(3n)
+ [4] = BigInt(10n)
+ [5] = BigInt(3n)
+ [6] = BigInt(7n)
+ [7] = BigInt(2n)
+ [8] = BigInt(3n)
+ [9] = BigInt(6n)
+ [10] = BigInt(10n)
[11] = BigInt(3n)
- [12] = BigInt(10n)
- [13] = BigInt(3n)
- [14] = BigInt(1n)
- [15] = BigInt(2n)
- [16] = BigInt(3n)
- [17] = BigInt(8n)
- [18] = BigInt(1n)
+ [12] = BigInt(3n)
+ [13] = BigInt(10n)
+ [14] = BigInt(3n)
+ [15] = BigInt(1n)
+ [16] = BigInt(2n)
+ [17] = BigInt(3n)
+ [18] = BigInt(8n)
[19] = BigInt(1n)
- [20] = Bool(true)
- [21] = BigInt(1n)
- [22] = Int32(1)
- [23] = BigInt(1n)
- [24] = BigInt(-2n)
- [25] = Undefined
+ [20] = BigInt(1n)
+ [21] = Bool(true)
+ [22] = BigInt(1n)
+ [23] = Int32(1)
+ [24] = BigInt(1n)
+ [25] = BigInt(-2n)
block0:
[ 0] Enter
- [ 8] SetGlobal `a`, src:BigInt(3n)
- [ 18] SetGlobal `b`, src:BigInt(7n)
- [ 28] SetGlobal `c`, src:BigInt(6n)
- [ 38] SetGlobal `d`, src:BigInt(3n)
- [ 48] SetGlobal `e`, src:BigInt(1n)
- [ 58] SetGlobal `f`, src:BigInt(8n)
- [ 68] SetGlobal `g`, src:Bool(true)
- [ 78] SetGlobal `h`, src:Bool(true)
- [ 88] SetGlobal `i`, src:BigInt(-2n)
- [ 98] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] SetGlobal `a`, src:BigInt(3n)
+ [ 28] SetGlobal `b`, src:BigInt(7n)
+ [ 38] SetGlobal `c`, src:BigInt(6n)
+ [ 48] SetGlobal `d`, src:BigInt(3n)
+ [ 58] SetGlobal `e`, src:BigInt(1n)
+ [ 68] SetGlobal `f`, src:BigInt(8n)
+ [ 78] SetGlobal `g`, src:Bool(true)
+ [ 88] SetGlobal `h`, src:Bool(true)
+ [ 98] SetGlobal `i`, src:BigInt(-2n)
+ [ a8] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/bigint-large-constant-folding.txt b/Tests/LibJS/Bytecode/expected/bigint-large-constant-folding.txt
index d8e9f00de76..0a7873ec8bf 100644
--- a/Tests/LibJS/Bytecode/expected/bigint-large-constant-folding.txt
+++ b/Tests/LibJS/Bytecode/expected/bigint-large-constant-folding.txt
@@ -1,21 +1,22 @@
-$3703a836 bigint-large-constant-folding.js:2:1
- Registers: 5
+$a89ab222 bigint-large-constant-folding.js:2:5
+ Registers: 6
Blocks: 1
Constants:
- [0] = BigInt(18364758544493064720n)
+ [0] = Undefined
[1] = BigInt(18364758544493064720n)
- [2] = BigInt(337264356397531028994973048178108678400n)
- [3] = BigInt(340282366920938463463374607431768211455n)
- [4] = BigInt(1n)
- [5] = BigInt(340282366920938463463374607431768211456n)
- [6] = BigInt(18364758544493064720n)
- [7] = BigInt(3n)
- [8] = BigInt(6193778470904512180693671865081363252814433915244866048000n)
- [9] = Undefined
+ [2] = BigInt(18364758544493064720n)
+ [3] = BigInt(337264356397531028994973048178108678400n)
+ [4] = BigInt(340282366920938463463374607431768211455n)
+ [5] = BigInt(1n)
+ [6] = BigInt(340282366920938463463374607431768211456n)
+ [7] = BigInt(18364758544493064720n)
+ [8] = BigInt(3n)
+ [9] = BigInt(6193778470904512180693671865081363252814433915244866048000n)
block0:
[ 0] Enter
- [ 8] SetGlobal `a`, src:BigInt(337264356397531028994973048178108678400n)
- [ 18] SetGlobal `b`, src:BigInt(340282366920938463463374607431768211456n)
- [ 28] SetGlobal `c`, src:BigInt(6193778470904512180693671865081363252814433915244866048000n)
- [ 38] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] SetGlobal `a`, src:BigInt(337264356397531028994973048178108678400n)
+ [ 28] SetGlobal `b`, src:BigInt(340282366920938463463374607431768211456n)
+ [ 38] SetGlobal `c`, src:BigInt(6193778470904512180693671865081363252814433915244866048000n)
+ [ 48] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/bigint-truthiness.txt b/Tests/LibJS/Bytecode/expected/bigint-truthiness.txt
index c014cc74c01..1ce753c3e7e 100644
--- a/Tests/LibJS/Bytecode/expected/bigint-truthiness.txt
+++ b/Tests/LibJS/Bytecode/expected/bigint-truthiness.txt
@@ -1,31 +1,48 @@
-$1b5c3d96 bigint-truthiness.js:2:1
- Registers: 6
- Blocks: 1
+$797b0455 bigint-truthiness.js:2:5
+ Registers: 7
+ Blocks: 4
Constants:
- [0] = BigInt(0n)
- [1] = String("falsy")
- [2] = BigInt(0n)
- [3] = BigInt(0n)
+ [0] = Undefined
+ [1] = BigInt(0n)
+ [2] = String("truthy")
+ [3] = String("falsy")
[4] = BigInt(0n)
- [5] = BigInt(1n)
- [6] = String("truthy")
+ [5] = BigInt(0n)
+ [6] = BigInt(0n)
[7] = BigInt(1n)
[8] = BigInt(1n)
- [9] = BigInt(0n)
- [10] = Bool(true)
- [11] = BigInt(0n)
- [12] = Bool(false)
- [13] = Undefined
+ [9] = BigInt(1n)
+ [10] = BigInt(0n)
+ [11] = Bool(true)
+ [12] = BigInt(0n)
+ [13] = Bool(false)
block0:
[ 0] Enter
- [ 8] SetGlobal `a`, src:String("falsy")
- [ 18] SetGlobal `b`, src:String("falsy")
- [ 28] SetGlobal `c`, src:String("falsy")
- [ 38] SetGlobal `d`, src:String("falsy")
- [ 48] SetGlobal `e`, src:String("truthy")
- [ 58] SetGlobal `f`, src:String("truthy")
- [ 68] SetGlobal `g`, src:String("truthy")
- [ 78] SetGlobal `h`, src:Bool(true)
- [ 88] SetGlobal `i`, src:Bool(false)
- [ 98] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg6, src:String("falsy")
+ [ 28] SetGlobal `a`, src:reg6
+ [ 38] Mov dst:reg6, src:String("falsy")
+ [ 48] SetGlobal `b`, src:reg6
+ [ 58] Mov dst:reg6, src:String("falsy")
+ [ 68] SetGlobal `c`, src:reg6
+ [ 78] Mov dst:reg6, src:String("falsy")
+ [ 88] SetGlobal `d`, src:reg6
+ [ 98] Mov dst:reg6, src:String("truthy")
+ [ a8] Jump target:block1
+
+block1:
+ [ b0] SetGlobal `e`, src:reg6
+ [ c0] Mov dst:reg6, src:String("truthy")
+ [ d0] Jump target:block2
+
+block2:
+ [ d8] SetGlobal `f`, src:reg6
+ [ e8] Mov dst:reg6, src:String("truthy")
+ [ f8] Jump target:block3
+
+block3:
+ [ 100] SetGlobal `g`, src:reg6
+ [ 110] SetGlobal `h`, src:Bool(true)
+ [ 120] SetGlobal `i`, src:Bool(false)
+ [ 130] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/bitwise-numeric-preconvert.txt b/Tests/LibJS/Bytecode/expected/bitwise-numeric-preconvert.txt
index 85a6b603212..68a57874287 100644
--- a/Tests/LibJS/Bytecode/expected/bitwise-numeric-preconvert.txt
+++ b/Tests/LibJS/Bytecode/expected/bitwise-numeric-preconvert.txt
@@ -1,4 +1,4 @@
-$acfb7718 bitwise-numeric-preconvert.js:4:1
+$aa378608 bitwise-numeric-preconvert.js:4:1
Registers: 7
Blocks: 1
Constants:
@@ -7,18 +7,19 @@ $acfb7718 bitwise-numeric-preconvert.js:4:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `test`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, test, arguments:[Int32(1)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `test`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(1)]
+ [ 50] End value:reg5
test$65b6c8dc bitwise-numeric-preconvert.js:2:5
Registers: 6
Blocks: 1
Constants:
- [0] = Int32(-2147483648)
+ [0] = Double(2147483648)
block0:
[ 0] Enter
- [ 8] RightShift arith_feedback:0, dst:reg5, lhs:Int32(-2147483648), rhs:arg0
+ [ 8] RightShift arith_feedback:0, dst:reg5, lhs:Double(2147483648), rhs:arg0
[ 18] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/block-function-declaration-order.txt b/Tests/LibJS/Bytecode/expected/block-function-declaration-order.txt
index c339668375c..7f54c888d35 100644
--- a/Tests/LibJS/Bytecode/expected/block-function-declaration-order.txt
+++ b/Tests/LibJS/Bytecode/expected/block-function-declaration-order.txt
@@ -1,22 +1,15 @@
-$ae8c96e2 block-function-declaration-order.js:1:1
- Registers: 7
+$63c57e75 block-function-declaration-order.js:1:1
+ Registers: 6
Blocks: 1
+ Locals: f1~0, f2~1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:2, is_catch_environment:false
- [ 28] CreateMutableBinding environment:reg5, `f1`, can_be_deleted:false
- [ 38] CreateMutableBinding environment:reg5, `f2`, can_be_deleted:false
- [ 48] NewFunction dst:reg6, shared_function_data_index:0
- [ 60] InitializeLexicalBinding `f1`, src:reg6
- [ 78] NewFunction dst:reg6, shared_function_data_index:1
- [ 90] InitializeLexicalBinding `f2`, src:reg6
- [ a8] GetBinding value_feedback:0, dst:reg6, `f1`
- [ c0] DynamicSetVariableBinding `f1`, src:reg6
- [ d0] GetBinding value_feedback:1, dst:reg6, `f2`
- [ e8] DynamicSetVariableBinding `f2`, src:reg6
- [ f8] SetLexicalEnvironment environment:reg4
- [ 100] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] NewFunction dst:f1~0, shared_function_data_index:0
+ [ 30] NewFunction dst:f2~1, shared_function_data_index:1
+ [ 48] DynamicSetVariableBinding `f1`, src:f1~0
+ [ 58] DynamicSetVariableBinding `f2`, src:f2~1
+ [ 68] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/block-scoped-function-no-tdz.txt b/Tests/LibJS/Bytecode/expected/block-scoped-function-no-tdz.txt
index 031a229c4f1..c5319185e81 100644
--- a/Tests/LibJS/Bytecode/expected/block-scoped-function-no-tdz.txt
+++ b/Tests/LibJS/Bytecode/expected/block-scoped-function-no-tdz.txt
@@ -1,35 +1,32 @@
-$d36729be block-scoped-function-no-tdz.js:10:1
+$66896f85 block-scoped-function-no-tdz.js:1:1
Registers: 7
Blocks: 1
Constants:
- [0] = String("use strict")
- [1] = Undefined
+ [0] = Undefined
+ [1] = String("use strict")
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `test`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, test
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:String("use strict")
+ [ 28] GetGlobal value_feedback:0, dst:reg6, `test`
+ [ 38] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 58] End value:reg5
-test$e46e97f5 block-scoped-function-no-tdz.js:3:5
- Registers: 7
+test$6572c6b9 block-scoped-function-no-tdz.js:3:9
+ Registers: 6
Blocks: 1
- Locals: foo~0, result~1
+ Locals: result~0, foo~1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] MovSrcUndefined dst:result~1
- [ 18] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:0, is_catch_environment:false
- [ 30] NewFunction dst:reg6, shared_function_data_index:0
- [ 48] Mov dst:foo~0, src:reg6
- [ 58] Call value_feedback:0, call_feedback:0, dst:reg6, callee:foo~0, this_value:Undefined, foo
- [ 78] Mov dst:result~1, src:reg6
- [ 88] SetLexicalEnvironment environment:reg4
- [ 90] Return value:result~1
+ [ 8] Mov dst:result~0, src:Undefined
+ [ 18] NewFunction dst:foo~1, shared_function_data_index:0
+ [ 30] Call value_feedback:0, call_feedback:0, dst:result~0, callee:foo~1, this_value:Undefined
+ [ 50] Return value:result~0
foo$7890849c block-scoped-function-no-tdz.js:5:26
diff --git a/Tests/LibJS/Bytecode/expected/block-scoping.txt b/Tests/LibJS/Bytecode/expected/block-scoping.txt
index 4420016bbd6..eec5d42c8bb 100644
--- a/Tests/LibJS/Bytecode/expected/block-scoping.txt
+++ b/Tests/LibJS/Bytecode/expected/block-scoping.txt
@@ -1,26 +1,27 @@
-$78986e0e block-scoping.js:13:1
- Registers: 11
+$80e4413e block-scoping.js:13:1
+ Registers: 9
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `closureOverBlockScope`
- [ 40] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, closureOverBlockScope
- [ 60] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 88] GetGlobal value_feedback:5, dst:reg6, `console`
- [ 98] GetById value_feedback:6, dst:reg8, base:reg6, `log` (console.log)
- [ b0] GetGlobal value_feedback:7, dst:reg10, `breakThroughBlockScopes`
- [ c0] Call value_feedback:8, call_feedback:2, dst:reg9, callee:reg10, this_value:Undefined, breakThroughBlockScopes
- [ e0] Call value_feedback:9, call_feedback:3, dst:reg7, callee:reg8, this_value:reg6, console.log, arguments:[reg9]
- [ 108] End value:reg7
-
-
-closureOverBlockScope$dcea615a block-scoping.js:2:15
- Registers: 10
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `closureOverBlockScope`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined
+ [ 70] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 98] GetGlobal value_feedback:5, dst:reg6, `console`
+ [ a8] GetById value_feedback:6, dst:reg7, base:reg6, `log`
+ [ c0] GetGlobal value_feedback:7, dst:reg8, `breakThroughBlockScopes`
+ [ d0] Call value_feedback:8, call_feedback:2, dst:reg8, callee:reg8, this_value:Undefined
+ [ f0] Call value_feedback:9, call_feedback:3, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 118] End value:reg5
+
+
+closureOverBlockScope$987bcbef block-scoping.js:2:15
+ Registers: 8
Blocks: 1
Locals: fns~0
Constants:
@@ -33,27 +34,25 @@ block0:
[ 8] GetLexicalEnvironment dst:reg4
[ 10] NewArray dst:fns~0
[ 20] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 38] CreateMutableBinding environment:reg5, `x`, can_be_deleted:false
+ [ 38] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
[ 48] InitializeLexicalBinding `x`, src:Int32(1)
- [ 60] GetById value_feedback:0, dst:reg7, base:fns~0, `push` (fns.push)
- [ 78] Mov dst:reg8, src:fns~0
- [ 88] NewFunction dst:reg9, shared_function_data_index:0
- [ a0] Call value_feedback:1, call_feedback:0, dst:reg6, callee:reg7, this_value:reg8, fns.push, arguments:[reg9]
- [ c8] SetLexicalEnvironment environment:reg4
- [ d0] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ e8] CreateMutableBinding environment:reg5, `y`, can_be_deleted:false
- [ f8] InitializeLexicalBinding `y`, src:Int32(2)
- [ 110] GetById value_feedback:2, dst:reg7, base:fns~0, `push` (fns.push)
- [ 128] Mov dst:reg8, src:fns~0
- [ 138] NewFunction dst:reg9, shared_function_data_index:1
- [ 150] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:reg8, fns.push, arguments:[reg9]
- [ 178] SetLexicalEnvironment environment:reg4
- [ 180] GetByValue value_feedback:4, keyed_feedback:0, dst:reg6, base:fns~0, property:Int32(0)
- [ 1a0] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:fns~0, fns[0]
- [ 1c0] GetByValue value_feedback:6, keyed_feedback:1, dst:reg7, base:fns~0, property:Int32(1)
- [ 1e0] Call value_feedback:7, call_feedback:3, dst:reg6, callee:reg7, this_value:fns~0, fns[1]
- [ 200] Add arith_feedback:0, dst:reg7, lhs:reg5, rhs:reg6
- [ 210] Return value:reg7
+ [ 60] GetById value_feedback:0, dst:reg6, base:fns~0, `push`
+ [ 78] NewFunction dst:reg7, shared_function_data_index:0
+ [ 90] Call value_feedback:1, call_feedback:0, dst:reg6, callee:reg6, this_value:fns~0, arguments:[reg7]
+ [ b8] SetLexicalEnvironment environment:reg4
+ [ c0] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
+ [ d8] CreateVariable `y`, is_immutable:false, is_global:false, is_strict:false
+ [ e8] InitializeLexicalBinding `y`, src:Int32(2)
+ [ 100] GetById value_feedback:2, dst:reg6, base:fns~0, `push`
+ [ 118] NewFunction dst:reg7, shared_function_data_index:1
+ [ 130] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg6, this_value:fns~0, arguments:[reg7]
+ [ 158] SetLexicalEnvironment environment:reg4
+ [ 160] GetByValue value_feedback:4, keyed_feedback:0, dst:reg5, base:fns~0, property:Int32(0)
+ [ 180] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg5, this_value:fns~0
+ [ 1a0] GetByValue value_feedback:6, keyed_feedback:1, dst:reg6, base:fns~0, property:Int32(1)
+ [ 1c0] Call value_feedback:7, call_feedback:3, dst:reg6, callee:reg6, this_value:fns~0
+ [ 1e0] Add arith_feedback:0, dst:reg5, lhs:reg5, rhs:reg6
+ [ 1f0] Return value:reg5
$cd30f87a block-scoping.js:5:18
@@ -76,48 +75,46 @@ block0:
[ 20] Return value:reg5
-breakThroughBlockScopes$be53e73f block-scoping.js:16:5
- Registers: 8
- Blocks: 7
- Locals: f~0, i~1, result~2
+breakThroughBlockScopes$df256a3b block-scoping.js:16:9
+ Registers: 7
+ Blocks: 6
+ Locals: result~0, i~1, f~2
Constants:
[0] = Undefined
[1] = Int32(0)
- [2] = Int32(3)
- [3] = Int32(1)
+ [2] = Int32(1)
+ [3] = Int32(3)
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] Mov2 c0_dst:result~2, c0_src:Undefined, c1_dst:i~1, c1_src:Int32(0)
- [ 28] Jump target:block3
+ [ 10] Mov dst:result~0, src:Undefined
+ [ 20] Mov dst:i~1, src:Int32(0)
+ [ 30] Jump target:block4
block1:
- [ 30] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 48] CreateMutableBinding environment:reg5, `x`, can_be_deleted:false
- [ 58] InitializeLexicalBinding `x`, src:i~1
- [ 70] NewFunction dst:f~0, shared_function_data_index:0 (f)
- [ 88] GetBinding value_feedback:0, dst:reg6, `x`
- [ a0] JumpGreaterThanRhsInt32 arith_feedback:2, lhs:reg6, rhs:1, true_target:block5, false_target:block6
+ [ 38] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
+ [ 50] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
+ [ 60] InitializeLexicalBinding `x`, src:i~1
+ [ 78] NewFunction dst:f~2, shared_function_data_index:0 (f)
+ [ 90] GetBinding value_feedback:0, dst:reg6, `x`
+ [ a8] JumpGreaterThanRhsInt32 arith_feedback:0, lhs:reg6, rhs:1, true_target:block2, false_target:block3
block2:
- [ b8] PostfixIncrement arith_feedback:1, dst:reg5, src:i~1
+ [ c0] Mov dst:result~0, src:f~2
+ [ d0] SetLexicalEnvironment environment:reg4
+ [ d8] Jump target:block5
block3:
- [ c8] JumpLessThanLoopRhsInt32 arith_feedback:0, lhs:i~1, rhs:3, true_target:block1, false_target:block4
+ [ e0] SetLexicalEnvironment environment:reg4
+ [ e8] Increment arith_feedback:1, dst:i~1
block4:
- [ e0] Call value_feedback:1, call_feedback:0, dst:reg5, callee:result~2, this_value:Undefined, result
- [ 100] Return value:reg5
+ [ f0] JumpLessThanLoopRhsInt32 arith_feedback:2, lhs:i~1, rhs:3, true_target:block1, false_target:block5
block5:
- [ 108] Mov dst:result~2, src:f~0
- [ 118] SetLexicalEnvironment environment:reg4
- [ 120] JumpLoop target:block4
-
-block6:
- [ 128] SetLexicalEnvironment environment:reg4
- [ 130] JumpLoop target:block2
+ [ 108] Call value_feedback:1, call_feedback:0, dst:reg5, callee:result~0, this_value:Undefined
+ [ 128] Return value:reg5
f$667a1882 block-scoping.js:20:21
diff --git a/Tests/LibJS/Bytecode/expected/call-spread-register-order.txt b/Tests/LibJS/Bytecode/expected/call-spread-register-order.txt
index 62e6b1031d9..2630d38b2d0 100644
--- a/Tests/LibJS/Bytecode/expected/call-spread-register-order.txt
+++ b/Tests/LibJS/Bytecode/expected/call-spread-register-order.txt
@@ -1,18 +1,19 @@
$13106a66 call-spread-register-order.js:2:1
- Registers: 10
+ Registers: 9
Blocks: 1
Constants:
[0] = Undefined
[1] = Int32(42)
+ [2] = Int32(1)
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Mov dst:reg8, src:Int32(42)
- [ 28] NewArray dst:reg7, elements:[reg8]
- [ 40] NewPrimitiveArray dst:reg9, elements:[1]
- [ 58] ArrayAppend dst:reg7, src:reg9, is_spread:true
- [ 68] CallWithArgumentArray value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:reg7, f
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] NewArray dst:reg7, elements:[Int32(42)]
+ [ 40] NewPrimitiveArray dst:reg8, elements:[1]
+ [ 58] ArrayAppend dst:reg7, src:reg8, is_spread:true
+ [ 68] CallWithArgumentArray value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:reg7
[ 88] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/captured-variables.txt b/Tests/LibJS/Bytecode/expected/captured-variables.txt
index fc2376e0b82..b862aa724bc 100644
--- a/Tests/LibJS/Bytecode/expected/captured-variables.txt
+++ b/Tests/LibJS/Bytecode/expected/captured-variables.txt
@@ -1,4 +1,4 @@
-$c7fd0018 captured-variables.js:12:1
+$c5390f08 captured-variables.js:12:1
Registers: 7
Blocks: 1
Constants:
@@ -6,29 +6,28 @@ $c7fd0018 captured-variables.js:12:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `outer`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, outer
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `outer`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-outer$65f64384 captured-variables.js:5:5
- Registers: 7
+outer$b5cac890 captured-variables.js:5:9
+ Registers: 6
Blocks: 1
Locals: inner~0
Constants:
- [0] = Undefined
- [1] = Int32(1)
+ [0] = Int32(1)
+ [1] = Undefined
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] MovSrcUndefined dst:inner~0
- [ 18] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 30] CreateVariable `captured`, is_immutable:false, is_global:false, is_strict:false
- [ 40] NewFunction dst:inner~0, shared_function_data_index:0
- [ 58] InitializeLexicalBinding `captured`, src:Int32(1)
- [ 70] Call value_feedback:0, call_feedback:0, dst:reg6, callee:inner~0, this_value:Undefined, inner
- [ 90] Return value:reg6
+ [ 8] CreateVariable `captured`, is_immutable:false, is_global:false, is_strict:false
+ [ 18] Mov dst:inner~0, src:Undefined
+ [ 28] NewFunction dst:inner~0, shared_function_data_index:0
+ [ 40] InitializeLexicalBinding `captured`, src:Int32(1)
+ [ 58] Call value_feedback:0, call_feedback:0, dst:reg5, callee:inner~0, this_value:Undefined
+ [ 78] Return value:reg5
inner$65d3f16d captured-variables.js:7:9
diff --git a/Tests/LibJS/Bytecode/expected/catch-scope-boundary.txt b/Tests/LibJS/Bytecode/expected/catch-scope-boundary.txt
index 90e260b05a8..42931357dbf 100644
--- a/Tests/LibJS/Bytecode/expected/catch-scope-boundary.txt
+++ b/Tests/LibJS/Bytecode/expected/catch-scope-boundary.txt
@@ -1,103 +1,110 @@
-$b64866f5 catch-scope-boundary.js:14:1
- Registers: 11
+$be943a25 catch-scope-boundary.js:14:1
+ Registers: 9
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `throwInCatch`
- [ 40] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, throwInCatch
- [ 60] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 88] GetGlobal value_feedback:5, dst:reg6, `console`
- [ 98] GetById value_feedback:6, dst:reg8, base:reg6, `log` (console.log)
- [ b0] GetGlobal value_feedback:7, dst:reg10, `throwInCatchWithLocals`
- [ c0] Call value_feedback:8, call_feedback:2, dst:reg9, callee:reg10, this_value:Undefined, throwInCatchWithLocals
- [ e0] Call value_feedback:9, call_feedback:3, dst:reg7, callee:reg8, this_value:reg6, console.log, arguments:[reg9]
- [ 108] End value:reg7
-
-
-throwInCatch$9784c856 catch-scope-boundary.js:2:5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `throwInCatch`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined
+ [ 70] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 98] GetGlobal value_feedback:5, dst:reg6, `console`
+ [ a8] GetById value_feedback:6, dst:reg7, base:reg6, `log`
+ [ c0] GetGlobal value_feedback:7, dst:reg8, `throwInCatchWithLocals`
+ [ d0] Call value_feedback:8, call_feedback:2, dst:reg8, callee:reg8, this_value:Undefined
+ [ f0] Call value_feedback:9, call_feedback:3, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 118] End value:reg5
+
+
+throwInCatch$db4351ba catch-scope-boundary.js:2:9
Registers: 7
- Blocks: 6
- Locals: e2~0, e~1, result~2
+ Blocks: 7
+ Locals: result~0, e~1, e2~2
Constants:
[0] = String("bad")
- [1] = String("good")
- [2] = Int32(2)
- [3] = Int32(1)
+ [1] = Int32(1)
+ [2] = <Empty>
+ [3] = Int32(2)
+ [4] = String("good")
block0:
[ 0] Enter
- [ 8] Mov dst:result~2, src:String("bad")
- [ 18] Jump target:block5
+ [ 8] Mov dst:result~0, src:String("bad")
block1:
- [ 20] Catch value_feedback:0, dst:reg5
- [ 28] Mov dst:e~1, src:reg5
- [ 38] Jump target:block3
+ [ 18] Throw src:Int32(1)
block2:
- [ 40] Catch value_feedback:1, dst:reg6
- [ 48] Mov2 c0_dst:e2~0, c0_src:reg6, c1_dst:result~2, c1_src:String("good")
- [ 60] Return value:result~2
+ [ 20] Catch value_feedback:0, dst:reg5
+ [ 28] Mov dst:e~1, src:<Empty>
+ [ 38] Mov dst:e~1, src:reg5
block3:
- [ 68] Throw src:Int32(2)
+ [ 48] Throw src:Int32(2)
block4:
- [ 70] Return value:result~2
+ [ 50] Catch value_feedback:1, dst:reg6
+ [ 58] Mov dst:e2~2, src:<Empty>
+ [ 68] Mov dst:e2~2, src:reg6
+ [ 78] Mov dst:result~0, src:String("good")
+ [ 88] Jump target:block5
block5:
- [ 78] Throw src:Int32(1)
+ [ 90] Jump target:block6
+
+block6:
+ [ 98] Return value:result~0
Exception handlers:
- [ 68 .. 70] => handler block2
- [ 78 .. 80] => handler block1
+ [ 18 .. 20] => handler block2
+ [ 48 .. 50] => handler block4
-throwInCatchWithLocals$32ece8d9 catch-scope-boundary.js:17:5
- Registers: 9
+throwInCatchWithLocals$d64ae5e5 catch-scope-boundary.js:17:9
+ Registers: 8
Blocks: 5
- Locals: inner~0, catchLocal~1, e~2, outerVar~3
+ Locals: outerVar~0, e~1, catchLocal~2, inner~3
Constants:
[0] = String("outer")
- [1] = String("local:")
- [2] = String(",")
- [3] = String("second")
- [4] = String("first")
+ [1] = String("first")
+ [2] = <Empty>
+ [3] = String("local:")
+ [4] = String("second")
+ [5] = String(",")
block0:
[ 0] Enter
- [ 8] Mov dst:outerVar~3, src:String("outer")
- [ 18] Jump target:block4
+ [ 8] Mov dst:outerVar~0, src:String("outer")
block1:
- [ 20] Catch value_feedback:0, dst:reg5
- [ 28] Mov dst:e~2, src:reg5
- [ 38] Add arith_feedback:0, dst:catchLocal~1, lhs:String("local:"), rhs:e~2
- [ 48] Jump target:block3
+ [ 18] Throw src:String("first")
block2:
- [ 50] Catch value_feedback:1, dst:reg6
- [ 58] Mov dst:inner~0, src:reg6
- [ 68] Add arith_feedback:1, dst:reg7, lhs:outerVar~3, rhs:String(",")
- [ 78] Add arith_feedback:2, dst:reg8, lhs:reg7, rhs:catchLocal~1
- [ 88] Add arith_feedback:3, dst:reg7, lhs:reg8, rhs:String(",")
- [ 98] Add arith_feedback:4, dst:reg8, lhs:reg7, rhs:inner~0
- [ a8] Return value:reg8
+ [ 20] Catch value_feedback:0, dst:reg5
+ [ 28] Mov dst:e~1, src:<Empty>
+ [ 38] Mov dst:e~1, src:reg5
+ [ 48] Add arith_feedback:0, dst:catchLocal~2, lhs:String("local:"), rhs:e~1
block3:
- [ b0] Throw src:String("second")
+ [ 58] Throw src:String("second")
block4:
- [ b8] Throw src:String("first")
+ [ 60] Catch value_feedback:1, dst:reg6
+ [ 68] Mov dst:inner~3, src:<Empty>
+ [ 78] Mov dst:inner~3, src:reg6
+ [ 88] Add arith_feedback:1, dst:reg7, lhs:outerVar~0, rhs:String(",")
+ [ 98] Add arith_feedback:2, dst:reg7, lhs:reg7, rhs:catchLocal~2
+ [ a8] Add arith_feedback:3, dst:reg7, lhs:reg7, rhs:String(",")
+ [ b8] Add arith_feedback:4, dst:reg7, lhs:reg7, rhs:inner~3
+ [ c8] Return value:reg7
Exception handlers:
- [ b0 .. b8] => handler block2
- [ b8 .. c0] => handler block1
+ [ 18 .. 20] => handler block2
+ [ 58 .. 60] => handler block4
"good"
diff --git a/Tests/LibJS/Bytecode/expected/chained-member-call.txt b/Tests/LibJS/Bytecode/expected/chained-member-call.txt
index 805486ce19c..a0ae405cc06 100644
--- a/Tests/LibJS/Bytecode/expected/chained-member-call.txt
+++ b/Tests/LibJS/Bytecode/expected/chained-member-call.txt
@@ -1,68 +1,67 @@
-$9355702b chained-member-call.js:12:1
- Registers: 10
- Blocks: 6
+$90917f1b chained-member-call.js:12:1
+ Registers: 7
+ Blocks: 7
Constants:
[0] = Undefined
[1] = Int32(0)
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:reg5
- [ 10] Jump target:block3
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:Undefined
block1:
- [ 18] Catch value_feedback:0, dst:reg6
- [ 20] Mov2 c0_dst:reg7, c0_src:Undefined, c1_dst:reg5, c1_src:reg7
+ [ 28] GetGlobal value_feedback:0, dst:reg6, `chained_computed_call`
+ [ 38] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(0), Int32(0), Int32(0)]
+ [ 68] Jump target:block3
block2:
- [ 38] MovSrcUndefined dst:reg6
- [ 40] Jump target:block5
+ [ 70] Catch value_feedback:2, dst:reg6
+ [ 78] Mov dst:reg5, src:Undefined
+ [ 88] Jump target:block3
block3:
- [ 48] MovSrcUndefined dst:reg6
- [ 50] GetGlobal value_feedback:1, dst:reg8, `chained_computed_call`
- [ 60] Call value_feedback:2, call_feedback:0, dst:reg7, callee:reg8, this_value:Undefined, chained_computed_call, arguments:[Int32(0), Int32(0), Int32(0)]
- [ 90] Mov2 c0_dst:reg6, c0_src:reg7, c1_dst:reg5, c1_src:reg6
- [ a8] JumpLoop target:block2
+ [ 90] Mov dst:reg5, src:Undefined
block4:
- [ b0] Catch value_feedback:3, dst:reg7
- [ b8] Mov2 c0_dst:reg8, c0_src:Undefined, c1_dst:reg6, c1_src:reg8
- [ d0] End value:reg6
+ [ a0] GetGlobal value_feedback:3, dst:reg6, `chained_dot_call`
+ [ b0] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(0)]
+ [ d8] Jump target:block6
block5:
- [ d8] MovSrcUndefined dst:reg7
- [ e0] GetGlobal value_feedback:4, dst:reg9, `chained_dot_call`
- [ f0] Call value_feedback:5, call_feedback:1, dst:reg8, callee:reg9, this_value:Undefined, chained_dot_call, arguments:[Int32(0)]
- [ 118] Mov2 c0_dst:reg7, c0_src:reg8, c1_dst:reg6, c1_src:reg7
- [ 130] End value:reg6
+ [ e0] Catch value_feedback:5, dst:reg6
+ [ e8] Mov dst:reg5, src:Undefined
+ [ f8] Jump target:block6
+
+block6:
+ [ 100] End value:reg5
Exception handlers:
- [ 48 .. b0] => handler block1
- [ d8 .. 138] => handler block4
+ [ 28 .. 70] => handler block2
+ [ a0 .. e0] => handler block5
chained_computed_call$78bf026a chained-member-call.js:5:5
- Registers: 8
+ Registers: 7
Blocks: 1
block0:
[ 0] Enter
- [ 8] GetByValue value_feedback:0, keyed_feedback:0, dst:reg6, base:arg0, property:arg1 (a[arg1])
- [ 28] GetByValue value_feedback:1, keyed_feedback:1, dst:reg7, base:reg6, property:arg2 (a[j][arg2])
- [ 48] GetById value_feedback:2, dst:reg6, base:reg7, `foo` (a[j][k].foo)
- [ 60] Call value_feedback:3, call_feedback:0, dst:reg5, callee:reg6, this_value:reg7, a[j][k].foo
+ [ 8] GetByValue value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0, property:arg1
+ [ 28] GetByValue value_feedback:1, keyed_feedback:1, dst:reg5, base:reg5, property:arg2
+ [ 48] GetById value_feedback:2, dst:reg6, base:reg5, `foo`
+ [ 60] Call value_feedback:3, call_feedback:0, dst:reg5, callee:reg6, this_value:reg5
[ 80] Return value:reg5
chained_dot_call$5f87afa0 chained-member-call.js:9:5
- Registers: 8
+ Registers: 7
Blocks: 1
block0:
[ 0] Enter
- [ 8] GetById value_feedback:0, dst:reg6, base:arg0, `b` (a.b)
- [ 20] GetById value_feedback:1, dst:reg7, base:reg6, `c` (a.b.c)
- [ 38] GetById value_feedback:2, dst:reg6, base:reg7, `bar` (a.b.c.bar)
- [ 50] Call value_feedback:3, call_feedback:0, dst:reg5, callee:reg6, this_value:reg7, a.b.c.bar
+ [ 8] GetById value_feedback:0, dst:reg5, base:arg0, `b`
+ [ 20] GetById value_feedback:1, dst:reg5, base:reg5, `c`
+ [ 38] GetById value_feedback:2, dst:reg6, base:reg5, `bar`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg5, callee:reg6, this_value:reg5
[ 70] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/class-computed-field-lhs-name.txt b/Tests/LibJS/Bytecode/expected/class-computed-field-lhs-name.txt
index 7b80e82caa9..a8515bf1c1f 100644
--- a/Tests/LibJS/Bytecode/expected/class-computed-field-lhs-name.txt
+++ b/Tests/LibJS/Bytecode/expected/class-computed-field-lhs-name.txt
@@ -1,22 +1,23 @@
-$091ab4cd class-computed-field-lhs-name.js:1:1
- Registers: 7
+$90d14739 class-computed-field-lhs-name.js:1:5
+ Registers: 8
Blocks: 1
Constants:
- [0] = Int32(1)
- [1] = Int32(2)
- [2] = Int32(3)
- [3] = Undefined
+ [0] = Undefined
+ [1] = Int32(1)
+ [2] = Int32(2)
+ [3] = Int32(3)
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:0, is_catch_environment:false
- [ 28] SetLexicalEnvironment environment:reg4
- [ 30] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0 (C), element_keys:[element_keys:Int32(3)]
- [ 60] SetGlobal `C`, src:reg6
- [ 70] GetGlobal value_feedback:0, dst:reg5, `C`
- [ 80] CallConstruct value_feedback:1, call_feedback:0, dst:reg6, callee:reg5, C
- [ a0] End value:reg6
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:0, is_catch_environment:false
+ [ 38] SetLexicalEnvironment environment:reg4
+ [ 40] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0 (C), element_keys:[element_keys:Int32(3)]
+ [ 70] SetGlobal `C`, src:reg6
+ [ 80] GetGlobal value_feedback:0, dst:reg6, `C`
+ [ 90] CallConstruct value_feedback:1, call_feedback:0, dst:reg5, callee:reg6
+ [ b0] End value:reg5
C$638b9046
diff --git a/Tests/LibJS/Bytecode/expected/class-computed-key.txt b/Tests/LibJS/Bytecode/expected/class-computed-key.txt
index a24dfc5178f..c14f013567b 100644
--- a/Tests/LibJS/Bytecode/expected/class-computed-key.txt
+++ b/Tests/LibJS/Bytecode/expected/class-computed-key.txt
@@ -1,4 +1,4 @@
-$d36729be class-computed-key.js:10:1
+$d0a338ae class-computed-key.js:10:1
Registers: 7
Blocks: 1
Constants:
@@ -6,23 +6,24 @@ $d36729be class-computed-key.js:10:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
f$048cbb7a class-computed-key.js:4:5
- Registers: 8
+ Registers: 9
Blocks: 1
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:0, is_catch_environment:false
+ [ 10] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:0, is_catch_environment:false
[ 28] CreateVariable ``, is_immutable:true, is_global:false, is_strict:true
- [ 38] GetGlobal value_feedback:0, dst:reg6, `Symbol`
- [ 48] GetById value_feedback:1, dst:reg7, base:reg6, `iterator` (Symbol.iterator)
- [ 60] ToPrimitiveWithStringHint dst:reg6, value:reg7
+ [ 38] GetGlobal value_feedback:0, dst:reg7, `Symbol`
+ [ 48] GetById value_feedback:1, dst:reg7, base:reg7, `iterator`
+ [ 60] ToPrimitiveWithStringHint dst:reg8, value:reg7
[ 70] SetLexicalEnvironment environment:reg4
- [ 78] NewClass dst:reg7, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:reg6]
- [ a8] Return value:reg7
+ [ 78] NewClass dst:reg5, class_environment:reg6, class_blueprint_index:0, element_keys:[element_keys:reg8]
+ [ a8] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/class-environment.txt b/Tests/LibJS/Bytecode/expected/class-environment.txt
index 990d340f308..b22ca740ec6 100644
--- a/Tests/LibJS/Bytecode/expected/class-environment.txt
+++ b/Tests/LibJS/Bytecode/expected/class-environment.txt
@@ -1,39 +1,40 @@
-$1bd06a9d class-environment.js:9:1
- Registers: 10
+$241c3dcd class-environment.js:9:1
+ Registers: 9
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `classWithName`
- [ 40] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, classWithName
- [ 60] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 88] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `classWithName`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined
+ [ 70] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 98] End value:reg5
-classWithName$91377959 class-environment.js:2:13
- Registers: 8
+classWithName$f3615e6d class-environment.js:2:9
+ Registers: 7
Blocks: 1
Locals: C~0
Constants:
[0] = String("method")
- [1] = Undefined
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
+ [ 10] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:1, is_catch_environment:false
[ 28] CreateVariable `Foo`, is_immutable:true, is_global:false, is_strict:true
[ 38] SetLexicalEnvironment environment:reg4
- [ 40] NewClass dst:C~0, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:String("method")]
- [ 70] CallConstruct value_feedback:0, call_feedback:0, dst:reg6, callee:C~0, C
- [ 90] GetById value_feedback:1, dst:reg7, base:reg6, `method`
- [ a8] Call value_feedback:2, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, <object>.method
- [ c8] StrictlyEquals arith_feedback:0, dst:reg7, lhs:reg5, rhs:C~0
- [ d8] Return value:reg7
+ [ 40] NewClass dst:reg5, class_environment:reg6, class_blueprint_index:0, element_keys:[element_keys:String("method")]
+ [ 70] Mov dst:C~0, src:reg5
+ [ 80] CallConstruct value_feedback:0, call_feedback:0, dst:reg5, callee:C~0
+ [ a0] GetById value_feedback:1, dst:reg6, base:reg5, `method`
+ [ b8] Call value_feedback:2, call_feedback:1, dst:reg5, callee:reg6, this_value:reg5
+ [ d8] StrictlyEquals arith_feedback:0, dst:reg5, lhs:reg5, rhs:C~0
+ [ e8] Return value:reg5
Foo$cf27a8b3
diff --git a/Tests/LibJS/Bytecode/expected/class-lhs-name-no-createvariable.txt b/Tests/LibJS/Bytecode/expected/class-lhs-name-no-createvariable.txt
index 57400daeca3..7bb24c650fa 100644
--- a/Tests/LibJS/Bytecode/expected/class-lhs-name-no-createvariable.txt
+++ b/Tests/LibJS/Bytecode/expected/class-lhs-name-no-createvariable.txt
@@ -1,15 +1,16 @@
-$e52776fd class-lhs-name-no-createvariable.js:1:1
- Registers: 7
+$8e0d5629 class-lhs-name-no-createvariable.js:1:5
+ Registers: 8
Blocks: 1
Constants:
- [0] = String("method")
- [1] = Undefined
+ [0] = Undefined
+ [1] = String("method")
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:0, is_catch_environment:false
- [ 28] SetLexicalEnvironment environment:reg4
- [ 30] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0 (x), element_keys:[element_keys:String("method")]
- [ 60] SetGlobal `x`, src:reg6
- [ 70] End value:Undefined
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:0, is_catch_environment:false
+ [ 38] SetLexicalEnvironment environment:reg4
+ [ 40] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0 (x), element_keys:[element_keys:String("method")]
+ [ 70] SetGlobal `x`, src:reg6
+ [ 80] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/class-literal-fields.txt b/Tests/LibJS/Bytecode/expected/class-literal-fields.txt
index 61e5628e813..169b7663e07 100644
--- a/Tests/LibJS/Bytecode/expected/class-literal-fields.txt
+++ b/Tests/LibJS/Bytecode/expected/class-literal-fields.txt
@@ -1,30 +1,31 @@
-$015bd143 class-literal-fields.js:12:1
- Registers: 15
+$a05c6db7 class-literal-fields.js:12:5
+ Registers: 14
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `test`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, test
- [ 38] DynamicInitializeLexicalBinding `a`, src:reg5
- [ 48] GetGlobal value_feedback:2, dst:reg6, `console`
- [ 58] GetById value_feedback:3, dst:reg7, base:reg6, `log` (console.log)
- [ 70] GetGlobal value_feedback:4, dst:reg8, `a`
- [ 80] GetById value_feedback:5, dst:reg9, base:reg8, `x` (a.x)
- [ 98] GetGlobal value_feedback:6, dst:reg8, `a`
- [ a8] GetById value_feedback:7, dst:reg10, base:reg8, `y` (a.y)
- [ c0] GetGlobal value_feedback:8, dst:reg8, `a`
- [ d0] GetById value_feedback:9, dst:reg11, base:reg8, `z` (a.z)
- [ e8] GetGlobal value_feedback:10, dst:reg8, `a`
- [ f8] GetById value_feedback:11, dst:reg12, base:reg8, `w` (a.w)
- [ 110] GetGlobal value_feedback:12, dst:reg8, `a`
- [ 120] GetById value_feedback:13, dst:reg13, base:reg8, `s` (a.s)
- [ 138] GetGlobal value_feedback:14, dst:reg8, `a`
- [ 148] GetById value_feedback:15, dst:reg14, base:reg8, `computed` (a.computed)
- [ 160] Call value_feedback:16, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg9, reg10, reg11, reg12, reg13, reg14]
- [ 198] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `test`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg6, callee:reg6, this_value:Undefined
+ [ 48] DynamicInitializeLexicalBinding `a`, src:reg6
+ [ 58] GetGlobal value_feedback:2, dst:reg6, `console`
+ [ 68] GetById value_feedback:3, dst:reg7, base:reg6, `log`
+ [ 80] GetGlobal value_feedback:4, dst:reg8, `a`
+ [ 90] GetById value_feedback:5, dst:reg8, base:reg8, `x`
+ [ a8] GetGlobal value_feedback:6, dst:reg9, `a`
+ [ b8] GetById value_feedback:7, dst:reg9, base:reg9, `y`
+ [ d0] GetGlobal value_feedback:8, dst:reg10, `a`
+ [ e0] GetById value_feedback:9, dst:reg10, base:reg10, `z`
+ [ f8] GetGlobal value_feedback:10, dst:reg11, `a`
+ [ 108] GetById value_feedback:11, dst:reg11, base:reg11, `w`
+ [ 120] GetGlobal value_feedback:12, dst:reg12, `a`
+ [ 130] GetById value_feedback:13, dst:reg12, base:reg12, `s`
+ [ 148] GetGlobal value_feedback:14, dst:reg13, `a`
+ [ 158] GetById value_feedback:15, dst:reg13, base:reg13, `computed`
+ [ 170] Call value_feedback:16, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8, reg9, reg10, reg11, reg12, reg13]
+ [ 1a8] End value:reg5
test$8c6df7bc class-literal-fields.js:2:5
@@ -38,19 +39,18 @@ test$8c6df7bc class-literal-fields.js:2:5
[3] = String("w")
[4] = String("s")
[5] = String("computed")
- [6] = Undefined
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
+ [ 10] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:1, is_catch_environment:false
[ 28] CreateVariable `A`, is_immutable:true, is_global:false, is_strict:true
[ 38] SetLexicalEnvironment environment:reg4
- [ 40] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:String("x"), element_keys:String("y"), element_keys:String("z"), element_keys:String("w"), element_keys:String("s"), element_keys:String("computed")]
- [ 80] Mov dst:A~0, src:reg6
+ [ 40] NewClass dst:reg5, class_environment:reg6, class_blueprint_index:0, element_keys:[element_keys:String("x"), element_keys:String("y"), element_keys:String("z"), element_keys:String("w"), element_keys:String("s"), element_keys:String("computed")]
+ [ 80] Mov dst:A~0, src:reg5
[ 90] ThrowIfTDZ src:A~0
- [ 98] CallConstruct value_feedback:0, call_feedback:0, dst:reg6, callee:A~0, A
- [ b8] Return value:reg6
+ [ 98] CallConstruct value_feedback:0, call_feedback:0, dst:reg5, callee:A~0
+ [ b8] Return value:reg5
A$70678274
diff --git a/Tests/LibJS/Bytecode/expected/computed-compound-assign-register-reuse.txt b/Tests/LibJS/Bytecode/expected/computed-compound-assign-register-reuse.txt
index e9e25db4b98..f0c4a6d7286 100644
--- a/Tests/LibJS/Bytecode/expected/computed-compound-assign-register-reuse.txt
+++ b/Tests/LibJS/Bytecode/expected/computed-compound-assign-register-reuse.txt
@@ -1,20 +1,25 @@
-$9d326325 computed-compound-assign-register-reuse.js:9:1
+$9a6e7215 computed-compound-assign-register-reuse.js:9:1
Registers: 9
Blocks: 1
Constants:
[0] = Undefined
+ [1] = Int32(1)
+ [2] = Int32(2)
+ [3] = Int32(3)
+ [4] = Int32(4)
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `subVector`
- [ 18] NewPrimitiveArray dst:reg7, elements:[1, 2]
- [ 38] NewPrimitiveArray dst:reg8, elements:[3, 4]
- [ 58] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, subVector, arguments:[reg7, reg8]
- [ 80] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `subVector`
+ [ 28] NewPrimitiveArray dst:reg7, elements:[1, 2]
+ [ 48] NewPrimitiveArray dst:reg8, elements:[3, 4]
+ [ 68] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7, reg8]
+ [ 90] End value:reg5
-subVector$19d5c5b3 computed-compound-assign-register-reuse.js:5:13
- Registers: 9
+subVector$b437e388 computed-compound-assign-register-reuse.js:5:13
+ Registers: 8
Blocks: 1
Constants:
[0] = Int32(0)
@@ -23,14 +28,12 @@ subVector$19d5c5b3 computed-compound-assign-register-reuse.js:5:13
block0:
[ 0] Enter
- [ 8] Mov dst:reg5, src:arg0
- [ 18] GetByValue value_feedback:0, keyed_feedback:0, dst:reg6, base:reg5, property:Int32(0) (self[Int32(0)])
- [ 38] GetByValue value_feedback:1, keyed_feedback:1, dst:reg7, base:arg1, property:Int32(0) (v[Int32(0)])
- [ 58] Sub arith_feedback:0, dst:reg8, lhs:reg6, rhs:reg7
- [ 68] PutByValue keyed_feedback:2, base:reg5, property:Int32(0), src:reg8, kind:Normal
- [ 88] Mov dst:reg8, src:arg0
- [ 98] GetByValue value_feedback:2, keyed_feedback:3, dst:reg5, base:reg8, property:Int32(1) (self[Int32(1)])
- [ b8] GetByValue value_feedback:3, keyed_feedback:4, dst:reg6, base:arg1, property:Int32(1) (v[Int32(1)])
- [ d8] Sub arith_feedback:1, dst:reg7, lhs:reg5, rhs:reg6
- [ e8] PutByValue keyed_feedback:5, base:reg8, property:Int32(1), src:reg7, kind:Normal
- [ 108] End value:Undefined
+ [ 8] GetByValue value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0, property:Int32(0)
+ [ 28] GetByValue value_feedback:1, keyed_feedback:1, dst:reg6, base:arg1, property:Int32(0)
+ [ 48] Sub arith_feedback:0, dst:reg7, lhs:reg5, rhs:reg6
+ [ 58] PutByValue keyed_feedback:2, base:arg0, property:Int32(0), src:reg7, kind:Normal
+ [ 78] GetByValue value_feedback:2, keyed_feedback:3, dst:reg5, base:arg0, property:Int32(1)
+ [ 98] GetByValue value_feedback:3, keyed_feedback:4, dst:reg6, base:arg1, property:Int32(1)
+ [ b8] Sub arith_feedback:1, dst:reg7, lhs:reg5, rhs:reg6
+ [ c8] PutByValue keyed_feedback:5, base:arg0, property:Int32(1), src:reg7, kind:Normal
+ [ e8] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/computed-member-access.txt b/Tests/LibJS/Bytecode/expected/computed-member-access.txt
index 123946eeafc..a9de0c5b0fc 100644
--- a/Tests/LibJS/Bytecode/expected/computed-member-access.txt
+++ b/Tests/LibJS/Bytecode/expected/computed-member-access.txt
@@ -1,19 +1,21 @@
-$bfb12ce8 computed-member-access.js:12:1
- Registers: 9
+$b1dd7798 computed-member-access.js:12:1
+ Registers: 8
Blocks: 1
Constants:
[0] = Undefined
- [1] = Int32(0)
+ [1] = Int32(1)
+ [2] = Int32(0)
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `computed_read`
- [ 18] NewPrimitiveArray dst:reg7, elements:[1]
- [ 30] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, computed_read, arguments:[reg7]
- [ 58] GetGlobal value_feedback:2, dst:reg7, `computed_read_expression`
- [ 68] NewPrimitiveArray dst:reg8, elements:[1]
- [ 80] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, computed_read_expression, arguments:[reg8, Int32(0)]
- [ a8] End value:reg6
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `computed_read`
+ [ 28] NewPrimitiveArray dst:reg7, elements:[1]
+ [ 40] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 68] GetGlobal value_feedback:2, dst:reg6, `computed_read_expression`
+ [ 78] NewPrimitiveArray dst:reg7, elements:[1]
+ [ 90] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7, Int32(0)]
+ [ b8] End value:reg5
computed_read$f0ef6ac1 computed-member-access.js:5:5
@@ -24,7 +26,7 @@ computed_read$f0ef6ac1 computed-member-access.js:5:5
block0:
[ 0] Enter
- [ 8] GetByValue value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0, property:Int32(0) (a[Int32(0)])
+ [ 8] GetByValue value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0, property:Int32(0)
[ 28] Return value:reg5
@@ -34,5 +36,5 @@ computed_read_expression$c18fd380 computed-member-access.js:9:5
block0:
[ 0] Enter
- [ 8] GetByValue value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0, property:arg1 (a[arg1])
+ [ 8] GetByValue value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0, property:arg1
[ 28] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/computed-member-compound-assign.txt b/Tests/LibJS/Bytecode/expected/computed-member-compound-assign.txt
index 891d29d917b..04de37f4eef 100644
--- a/Tests/LibJS/Bytecode/expected/computed-member-compound-assign.txt
+++ b/Tests/LibJS/Bytecode/expected/computed-member-compound-assign.txt
@@ -1,5 +1,5 @@
-$01294703 computed-member-compound-assign.js:15:1
- Registers: 9
+$fe6555f3 computed-member-compound-assign.js:15:1
+ Registers: 8
Blocks: 1
Constants:
[0] = Undefined
@@ -8,19 +8,20 @@ $01294703 computed-member-compound-assign.js:15:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `compound_computed`
- [ 18] NewObject dst:reg7
- [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, compound_computed, arguments:[reg7, String("x")]
- [ 50] GetGlobal value_feedback:2, dst:reg7, `compound_then_assign`
- [ 60] NewObject dst:reg8
- [ 70] InitObjectLiteralProperty object:reg8, `x`, src:Int32(1), shape_cache_index:0, property_slot:0
- [ 88] CacheObjectShape object:reg8
- [ 98] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, compound_then_assign, arguments:[reg8, String("x")]
- [ c0] End value:reg6
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `compound_computed`
+ [ 28] NewObject dst:reg7
+ [ 38] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7, String("x")]
+ [ 60] GetGlobal value_feedback:2, dst:reg6, `compound_then_assign`
+ [ 70] NewObject dst:reg7
+ [ 80] InitObjectLiteralProperty object:reg7, `x`, src:Int32(1), shape_cache_index:0, property_slot:0
+ [ 98] CacheObjectShape object:reg7
+ [ a8] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7, String("x")]
+ [ d0] End value:reg5
-compound_computed$a50f1bab computed-member-compound-assign.js:7:14
- Registers: 9
+compound_computed$7b93fbbb computed-member-compound-assign.js:7:14
+ Registers: 8
Blocks: 1
Constants:
[0] = Int32(1)
@@ -28,17 +29,16 @@ compound_computed$a50f1bab computed-member-compound-assign.js:7:14
block0:
[ 0] Enter
- [ 8] Mov dst:reg5, src:arg0
- [ 18] ThrowIfNullish src:reg5
- [ 20] ToPrimitiveWithStringHint dst:reg6, value:arg1
- [ 30] GetByValue value_feedback:0, keyed_feedback:0, dst:reg7, base:reg5, property:reg6 (obj[reg6])
- [ 50] AddRhsInt32 arith_feedback:0, dst:reg8, lhs:reg7, rhs:1
- [ 60] PutByValue keyed_feedback:1, base:reg5, property:reg6, src:reg8, kind:Normal
- [ 80] End value:Undefined
+ [ 8] ThrowIfNullish src:arg0
+ [ 10] ToPrimitiveWithStringHint dst:reg5, value:arg1
+ [ 20] GetByValue value_feedback:0, keyed_feedback:0, dst:reg6, base:arg0, property:reg5
+ [ 40] AddRhsInt32 arith_feedback:0, dst:reg7, lhs:reg6, rhs:1
+ [ 50] PutByValue keyed_feedback:1, base:arg0, property:reg5, src:reg7, kind:Normal
+ [ 70] End value:Undefined
-compound_then_assign$223bcf74 computed-member-compound-assign.js:11:13
- Registers: 9
+compound_then_assign$abe99b2c computed-member-compound-assign.js:11:13
+ Registers: 8
Blocks: 1
Constants:
[0] = Int32(0)
@@ -46,12 +46,10 @@ compound_then_assign$223bcf74 computed-member-compound-assign.js:11:13
block0:
[ 0] Enter
- [ 8] Mov dst:reg5, src:arg0
- [ 18] ThrowIfNullish src:reg5
- [ 20] ToPrimitiveWithStringHint dst:reg6, value:arg1
- [ 30] GetByValue value_feedback:0, keyed_feedback:0, dst:reg7, base:reg5, property:reg6 (imag[reg6])
- [ 50] AddRhsInt32 arith_feedback:0, dst:reg8, lhs:reg7, rhs:0
- [ 60] PutByValue keyed_feedback:1, base:reg5, property:reg6, src:reg8, kind:Normal
- [ 80] Mov2 c0_dst:reg8, c0_src:arg0, c1_dst:reg5, c1_src:arg1
- [ 98] PutByValue keyed_feedback:2, base:reg8, property:reg5, src:arg1, kind:Normal (imag[reg5])
- [ b8] End value:Undefined
+ [ 8] ThrowIfNullish src:arg0
+ [ 10] ToPrimitiveWithStringHint dst:reg5, value:arg1
+ [ 20] GetByValue value_feedback:0, keyed_feedback:0, dst:reg6, base:arg0, property:reg5
+ [ 40] AddRhsInt32 arith_feedback:0, dst:reg7, lhs:reg6, rhs:0
+ [ 50] PutByValue keyed_feedback:1, base:arg0, property:reg5, src:reg7, kind:Normal
+ [ 70] PutByValue keyed_feedback:2, base:arg0, property:arg1, src:arg1, kind:Normal
+ [ 90] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/computed-string-object-literal.txt b/Tests/LibJS/Bytecode/expected/computed-string-object-literal.txt
index 06bd15813a9..01c4abab1cc 100644
--- a/Tests/LibJS/Bytecode/expected/computed-string-object-literal.txt
+++ b/Tests/LibJS/Bytecode/expected/computed-string-object-literal.txt
@@ -1,5 +1,5 @@
-$fba164e3 computed-string-object-literal.js:15:1
- Registers: 8
+$f8dd73d3 computed-string-object-literal.js:15:1
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
@@ -7,42 +7,43 @@ $fba164e3 computed-string-object-literal.js:15:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `simple_computed`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, simple_computed
- [ 38] GetGlobal value_feedback:2, dst:reg7, `mixed`
- [ 48] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, mixed
- [ 68] GetGlobal value_feedback:4, dst:reg7, `dynamic`
- [ 78] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg7, this_value:Undefined, dynamic, arguments:[String("x")]
- [ a0] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `simple_computed`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] GetGlobal value_feedback:2, dst:reg6, `mixed`
+ [ 58] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined
+ [ 78] GetGlobal value_feedback:4, dst:reg6, `dynamic`
+ [ 88] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined, arguments:[String("x")]
+ [ b0] End value:reg5
-simple_computed$6cbba156 computed-string-object-literal.js:6:5
+simple_computed$ee1d99de computed-string-object-literal.js:6:5
Registers: 6
Blocks: 1
Constants:
- [0] = Int32(1)
+ [0] = String("x")
+ [1] = Int32(1)
block0:
[ 0] Enter
[ 8] NewObject dst:reg5
- [ 18] InitObjectLiteralProperty object:reg5, `x`, src:Int32(1), shape_cache_index:0, property_slot:0
- [ 30] CacheObjectShape object:reg5
- [ 40] Return value:reg5
+ [ 18] PutById base:reg5, `x`, src:Int32(1), kind:Own
+ [ 38] Return value:reg5
mixed$15906784 computed-string-object-literal.js:9:5
Registers: 6
Blocks: 1
Constants:
- [0] = Int32(1)
- [1] = Int32(2)
+ [0] = String("a")
+ [1] = Int32(1)
+ [2] = Int32(2)
block0:
[ 0] Enter
[ 8] NewObject dst:reg5
- [ 18] InitObjectLiteralProperty object:reg5, `a`, src:Int32(1), shape_cache_index:0, property_slot:0
- [ 30] InitObjectLiteralProperty object:reg5, `b`, src:Int32(2), shape_cache_index:0, property_slot:1
- [ 48] CacheObjectShape object:reg5
+ [ 18] PutById base:reg5, `a`, src:Int32(1), kind:Own
+ [ 38] PutById base:reg5, `b`, src:Int32(2), kind:Own
[ 58] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/computed-string-to-ById.txt b/Tests/LibJS/Bytecode/expected/computed-string-to-ById.txt
index 961c7bfeec1..69c6c7fc014 100644
--- a/Tests/LibJS/Bytecode/expected/computed-string-to-ById.txt
+++ b/Tests/LibJS/Bytecode/expected/computed-string-to-ById.txt
@@ -1,24 +1,25 @@
-$632db05a computed-string-to-ById.js:17:1
- Registers: 9
+$5ae1dd2a computed-string-to-ById.js:17:1
+ Registers: 8
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `get_string_prop`
- [ 18] NewObject dst:reg7
- [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, get_string_prop, arguments:[reg7]
- [ 50] GetGlobal value_feedback:2, dst:reg7, `set_string_prop`
- [ 60] NewObject dst:reg8
- [ 70] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, set_string_prop, arguments:[reg8]
- [ 98] GetGlobal value_feedback:4, dst:reg7, `get_index_prop`
- [ a8] NewArray dst:reg8
- [ b8] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg7, this_value:Undefined, get_index_prop, arguments:[reg8]
- [ e0] GetGlobal value_feedback:6, dst:reg7, `get_length_prop`
- [ f0] NewArray dst:reg8
- [ 100] Call value_feedback:7, call_feedback:3, dst:reg6, callee:reg7, this_value:Undefined, get_length_prop, arguments:[reg8]
- [ 128] End value:reg6
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `get_string_prop`
+ [ 28] NewObject dst:reg7
+ [ 38] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 60] GetGlobal value_feedback:2, dst:reg6, `set_string_prop`
+ [ 70] NewObject dst:reg7
+ [ 80] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ a8] GetGlobal value_feedback:4, dst:reg6, `get_index_prop`
+ [ b8] NewArray dst:reg7
+ [ c8] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ f0] GetGlobal value_feedback:6, dst:reg6, `get_length_prop`
+ [ 100] NewArray dst:reg7
+ [ 110] Call value_feedback:7, call_feedback:3, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 138] End value:reg5
get_string_prop$d3f03c93 computed-string-to-ById.js:5:5
@@ -29,12 +30,12 @@ get_string_prop$d3f03c93 computed-string-to-ById.js:5:5
block0:
[ 0] Enter
- [ 8] GetById value_feedback:0, dst:reg5, base:arg0, `hello` (o.hello)
+ [ 8] GetById value_feedback:0, dst:reg5, base:arg0, `hello`
[ 20] Return value:reg5
-set_string_prop$592a21c7 computed-string-to-ById.js:8:16
- Registers: 6
+set_string_prop$50de4e97 computed-string-to-ById.js:8:16
+ Registers: 5
Blocks: 1
Constants:
[0] = String("hello")
@@ -43,9 +44,8 @@ set_string_prop$592a21c7 computed-string-to-ById.js:8:16
block0:
[ 0] Enter
- [ 8] Mov dst:reg5, src:arg0
- [ 18] PutById base:reg5, `hello`, src:Int32(42), kind:Normal (o.hello)
- [ 38] End value:Undefined
+ [ 8] PutById base:arg0, `hello`, src:Int32(42), kind:Normal
+ [ 28] End value:Undefined
get_index_prop$a54df54e computed-string-to-ById.js:11:5
@@ -56,7 +56,7 @@ get_index_prop$a54df54e computed-string-to-ById.js:11:5
block0:
[ 0] Enter
- [ 8] GetByValue value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0, property:String("0") (o[String("0")])
+ [ 8] GetByValue value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0, property:String("0")
[ 28] Return value:reg5
@@ -68,5 +68,5 @@ get_length_prop$0563fe89 computed-string-to-ById.js:14:5
block0:
[ 0] Enter
- [ 8] GetLength value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0 (o.length)
+ [ 8] GetLength value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0
[ 20] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/computed-update-register-order.txt b/Tests/LibJS/Bytecode/expected/computed-update-register-order.txt
index 8f188136e1e..a7756295269 100644
--- a/Tests/LibJS/Bytecode/expected/computed-update-register-order.txt
+++ b/Tests/LibJS/Bytecode/expected/computed-update-register-order.txt
@@ -1,19 +1,24 @@
-$9790b964 computed-update-register-order.js:8:1
+$b5fc1514 computed-update-register-order.js:8:1
Registers: 8
Blocks: 1
Constants:
[0] = Undefined
+ [1] = Int32(1)
+ [2] = Int32(2)
+ [3] = Int32(3)
+ [4] = Int32(4)
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `test`
- [ 18] NewPrimitiveArray dst:reg7, elements:[1, 2, 3, 4]
- [ 48] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, test, arguments:[reg7]
- [ 70] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `test`
+ [ 28] NewPrimitiveArray dst:reg7, elements:[1, 2, 3, 4]
+ [ 58] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 80] End value:reg5
-test$7664d27f computed-update-register-order.js:5:9
- Registers: 8
+test$7becb49f computed-update-register-order.js:5:9
+ Registers: 7
Blocks: 1
Constants:
[0] = Int32(3)
@@ -21,14 +26,12 @@ test$7664d27f computed-update-register-order.js:5:9
block0:
[ 0] Enter
- [ 8] Mov dst:reg5, src:arg0
- [ 18] GetByValue value_feedback:0, keyed_feedback:0, dst:reg6, base:reg5, property:Int32(3) (c[Int32(3)])
- [ 38] PostfixIncrement arith_feedback:0, dst:reg7, src:reg6
- [ 48] PutByValue keyed_feedback:1, base:reg5, property:Int32(3), src:reg6, kind:Normal
- [ 68] GetGlobal value_feedback:1, dst:reg5, `foo`
- [ 78] Mov dst:reg6, src:arg0
- [ 88] Call value_feedback:2, call_feedback:0, dst:reg7, callee:reg5, this_value:Undefined, foo, arguments:[reg6]
- [ b0] End value:Undefined
+ [ 8] GetByValue value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0, property:Int32(3)
+ [ 28] PostfixIncrement arith_feedback:0, dst:reg6, src:reg5
+ [ 38] PutByValue keyed_feedback:1, base:arg0, property:Int32(3), src:reg5, kind:Normal
+ [ 58] GetGlobal value_feedback:1, dst:reg5, `foo`
+ [ 68] Call value_feedback:2, call_feedback:0, dst:reg5, callee:reg5, this_value:Undefined, arguments:[arg0]
+ [ 90] End value:Undefined
foo$14c42854 computed-update-register-order.js:2:5
diff --git a/Tests/LibJS/Bytecode/expected/condition-dead-code-elim.txt b/Tests/LibJS/Bytecode/expected/condition-dead-code-elim.txt
index bcaf86459b2..bc75494fb1c 100644
--- a/Tests/LibJS/Bytecode/expected/condition-dead-code-elim.txt
+++ b/Tests/LibJS/Bytecode/expected/condition-dead-code-elim.txt
@@ -1,5 +1,5 @@
-$fa637ceb condition-dead-code-elim.js:141:1
- Registers: 8
+$f79f8bdb condition-dead-code-elim.js:141:1
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
@@ -7,68 +7,81 @@ $fa637ceb condition-dead-code-elim.js:141:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `ternary_true`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, ternary_true
- [ 38] GetGlobal value_feedback:2, dst:reg7, `ternary_truthy`
- [ 48] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, ternary_truthy
- [ 68] GetGlobal value_feedback:4, dst:reg7, `ternary_false`
- [ 78] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg7, this_value:Undefined, ternary_false
- [ 98] GetGlobal value_feedback:6, dst:reg7, `ternary_falsey`
- [ a8] Call value_feedback:7, call_feedback:3, dst:reg6, callee:reg7, this_value:Undefined, ternary_falsey
- [ c8] GetGlobal value_feedback:8, dst:reg7, `while_falsey`
- [ d8] Call value_feedback:9, call_feedback:4, dst:reg5, callee:reg7, this_value:Undefined, while_falsey
- [ f8] GetGlobal value_feedback:10, dst:reg7, `do_while_falsey`
- [ 108] Call value_feedback:11, call_feedback:5, dst:reg6, callee:reg7, this_value:Undefined, do_while_falsey
- [ 128] GetGlobal value_feedback:12, dst:reg7, `if_falsely`
- [ 138] Call value_feedback:13, call_feedback:6, dst:reg5, callee:reg7, this_value:Undefined, if_falsely
- [ 158] GetGlobal value_feedback:14, dst:reg7, `if_truthy`
- [ 168] Call value_feedback:15, call_feedback:7, dst:reg6, callee:reg7, this_value:Undefined, if_truthy
- [ 188] GetGlobal value_feedback:16, dst:reg7, `if_exhausted`
- [ 198] Call value_feedback:17, call_feedback:8, dst:reg5, callee:reg7, this_value:Undefined, if_exhausted
- [ 1b8] GetGlobal value_feedback:18, dst:reg7, `for_false`
- [ 1c8] Call value_feedback:19, call_feedback:9, dst:reg6, callee:reg7, this_value:Undefined, for_false
- [ 1e8] GetGlobal value_feedback:20, dst:reg7, `for_true`
- [ 1f8] Call value_feedback:21, call_feedback:10, dst:reg5, callee:reg7, this_value:Undefined, for_true, arguments:[Bool(true)]
- [ 220] End value:reg5
-
-
-ternary_true$5188be0f condition-dead-code-elim.js:9:5
- Registers: 5
- Blocks: 1
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `ternary_true`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] GetGlobal value_feedback:2, dst:reg6, `ternary_truthy`
+ [ 58] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined
+ [ 78] GetGlobal value_feedback:4, dst:reg6, `ternary_false`
+ [ 88] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined
+ [ a8] GetGlobal value_feedback:6, dst:reg6, `ternary_falsey`
+ [ b8] Call value_feedback:7, call_feedback:3, dst:reg5, callee:reg6, this_value:Undefined
+ [ d8] GetGlobal value_feedback:8, dst:reg6, `while_falsey`
+ [ e8] Call value_feedback:9, call_feedback:4, dst:reg5, callee:reg6, this_value:Undefined
+ [ 108] GetGlobal value_feedback:10, dst:reg6, `do_while_falsey`
+ [ 118] Call value_feedback:11, call_feedback:5, dst:reg5, callee:reg6, this_value:Undefined
+ [ 138] GetGlobal value_feedback:12, dst:reg6, `if_falsely`
+ [ 148] Call value_feedback:13, call_feedback:6, dst:reg5, callee:reg6, this_value:Undefined
+ [ 168] GetGlobal value_feedback:14, dst:reg6, `if_truthy`
+ [ 178] Call value_feedback:15, call_feedback:7, dst:reg5, callee:reg6, this_value:Undefined
+ [ 198] GetGlobal value_feedback:16, dst:reg6, `if_exhausted`
+ [ 1a8] Call value_feedback:17, call_feedback:8, dst:reg5, callee:reg6, this_value:Undefined
+ [ 1c8] GetGlobal value_feedback:18, dst:reg6, `for_false`
+ [ 1d8] Call value_feedback:19, call_feedback:9, dst:reg5, callee:reg6, this_value:Undefined
+ [ 1f8] GetGlobal value_feedback:20, dst:reg6, `for_true`
+ [ 208] Call value_feedback:21, call_feedback:10, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Bool(true)]
+ [ 230] End value:reg5
+
+
+ternary_true$d2eab697 condition-dead-code-elim.js:9:5
+ Registers: 7
+ Blocks: 2
Constants:
[0] = Bool(true)
[1] = Int32(1)
+ [2] = Undefined
block0:
[ 0] Enter
- [ 8] Return value:Int32(1)
+ [ 8] Mov dst:reg5, src:Int32(1)
+ [ 18] Jump target:block1
+block1:
+ [ 20] Return value:reg5
-ternary_truthy$106c205a condition-dead-code-elim.js:12:5
- Registers: 5
- Blocks: 1
+
+ternary_truthy$86be54a2 condition-dead-code-elim.js:12:5
+ Registers: 7
+ Blocks: 2
Constants:
[0] = Int32(1)
+ [1] = Undefined
block0:
[ 0] Enter
- [ 8] Return value:Int32(1)
+ [ 8] Mov dst:reg5, src:Int32(1)
+ [ 18] Jump target:block1
+
+block1:
+ [ 20] Return value:reg5
-ternary_false$94167eba condition-dead-code-elim.js:15:5
- Registers: 5
+ternary_false$96da6fca condition-dead-code-elim.js:15:5
+ Registers: 7
Blocks: 1
Constants:
[0] = Bool(false)
- [1] = Int32(1)
+ [1] = Undefined
+ [2] = Int32(1)
block0:
[ 0] Enter
- [ 8] Return value:Int32(1)
+ [ 8] Mov dst:reg5, src:Int32(1)
+ [ 18] Return value:reg5
-ternary_falsey$c2de8186 condition-dead-code-elim.js:18:5
- Registers: 5
+ternary_falsey$c01a9076 condition-dead-code-elim.js:18:5
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
@@ -76,21 +89,22 @@ ternary_falsey$c2de8186 condition-dead-code-elim.js:18:5
block0:
[ 0] Enter
- [ 8] Return value:Int32(1)
+ [ 8] Mov dst:reg5, src:Int32(1)
+ [ 18] Return value:reg5
-while_falsey$17590e95 condition-dead-code-elim.js:33:5
- Registers: 7
+while_falsey$195d6166 condition-dead-code-elim.js:22:17
+ Registers: 6
Blocks: 1
Constants:
[0] = Bool(false)
- [1] = Null
- [2] = Undefined
+ [1] = Undefined
+ [2] = Null
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `alive`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, alive
+ [ 8] GetGlobal value_feedback:6, dst:reg5, `alive`
+ [ 18] Call value_feedback:7, call_feedback:3, dst:reg5, callee:reg5, this_value:Undefined
[ 38] End value:Undefined
@@ -106,44 +120,44 @@ block0:
do_while_falsey$af48c539 condition-dead-code-elim.js:37:9
- Registers: 7
+ Registers: 6
Blocks: 1
Constants:
- [0] = Bool(false)
- [1] = Undefined
+ [0] = Undefined
+ [1] = Bool(false)
[2] = Null
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `alive`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, alive
- [ 38] GetGlobal value_feedback:2, dst:reg6, `alive`
- [ 48] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, alive
- [ 68] GetGlobal value_feedback:4, dst:reg6, `alive`
- [ 78] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined, alive
- [ 98] GetGlobal value_feedback:6, dst:reg6, `alive`
- [ a8] Call value_feedback:7, call_feedback:3, dst:reg5, callee:reg6, this_value:Undefined, alive
+ [ 8] GetGlobal value_feedback:0, dst:reg5, `alive`
+ [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg5, this_value:Undefined
+ [ 38] GetGlobal value_feedback:2, dst:reg5, `alive`
+ [ 48] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg5, this_value:Undefined
+ [ 68] GetGlobal value_feedback:4, dst:reg5, `alive`
+ [ 78] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg5, this_value:Undefined
+ [ 98] GetGlobal value_feedback:6, dst:reg5, `alive`
+ [ a8] Call value_feedback:7, call_feedback:3, dst:reg5, callee:reg5, this_value:Undefined
[ c8] End value:Undefined
-if_falsely$537336d6 condition-dead-code-elim.js:62:5
- Registers: 7
+if_falsely$3704b7c0 condition-dead-code-elim.js:51:14
+ Registers: 6
Blocks: 1
Constants:
[0] = Bool(false)
- [1] = Null
- [2] = Undefined
+ [1] = Undefined
+ [2] = Null
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `alive`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, alive
+ [ 8] GetGlobal value_feedback:6, dst:reg5, `alive`
+ [ 18] Call value_feedback:7, call_feedback:3, dst:reg5, callee:reg5, this_value:Undefined
[ 38] End value:Undefined
-if_truthy$1f8e5cc8 condition-dead-code-elim.js:66:9
- Registers: 7
- Blocks: 1
+if_truthy$a6783770 condition-dead-code-elim.js:66:9
+ Registers: 6
+ Blocks: 4
Constants:
[0] = Bool(true)
[1] = Undefined
@@ -152,20 +166,29 @@ if_truthy$1f8e5cc8 condition-dead-code-elim.js:66:9
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `alive`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, alive
- [ 38] GetGlobal value_feedback:2, dst:reg6, `alive`
- [ 48] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, alive
- [ 68] GetGlobal value_feedback:4, dst:reg6, `alive`
- [ 78] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined, alive
- [ 98] GetGlobal value_feedback:6, dst:reg6, `alive`
- [ a8] Call value_feedback:7, call_feedback:3, dst:reg5, callee:reg6, this_value:Undefined, alive
- [ c8] End value:Undefined
+ [ 8] GetGlobal value_feedback:0, dst:reg5, `alive`
+ [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg5, this_value:Undefined
+ [ 38] Jump target:block1
+
+block1:
+ [ 40] GetGlobal value_feedback:4, dst:reg5, `alive`
+ [ 50] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg5, this_value:Undefined
+ [ 70] Jump target:block2
+block2:
+ [ 78] GetGlobal value_feedback:8, dst:reg5, `alive`
+ [ 88] Call value_feedback:9, call_feedback:4, dst:reg5, callee:reg5, this_value:Undefined
+ [ a8] Jump target:block3
-if_exhausted$9a8b31f1 condition-dead-code-elim.js:90:9
- Registers: 7
- Blocks: 1
+block3:
+ [ b0] GetGlobal value_feedback:12, dst:reg5, `alive`
+ [ c0] Call value_feedback:13, call_feedback:6, dst:reg5, callee:reg5, this_value:Undefined
+ [ e0] End value:Undefined
+
+
+if_exhausted$56ba4c21 condition-dead-code-elim.js:85:14
+ Registers: 6
+ Blocks: 2
Constants:
[0] = Bool(false)
[1] = Undefined
@@ -173,55 +196,62 @@ if_exhausted$9a8b31f1 condition-dead-code-elim.js:90:9
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `alive`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, alive
- [ 38] GetGlobal value_feedback:2, dst:reg6, `alive`
- [ 48] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, alive
- [ 68] GetGlobal value_feedback:4, dst:reg6, `alive`
- [ 78] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined, alive
- [ 98] End value:Undefined
+ [ 8] GetGlobal value_feedback:4, dst:reg5, `alive`
+ [ 18] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg5, this_value:Undefined
+ [ 38] GetGlobal value_feedback:6, dst:reg5, `alive`
+ [ 48] Call value_feedback:7, call_feedback:3, dst:reg5, callee:reg5, this_value:Undefined
+ [ 68] Jump target:block1
+block1:
+ [ 70] GetGlobal value_feedback:12, dst:reg5, `alive`
+ [ 80] Call value_feedback:13, call_feedback:6, dst:reg5, callee:reg5, this_value:Undefined
+ [ a0] End value:Undefined
-for_false$a2052754 condition-dead-code-elim.js:109:5
- Registers: 7
+
+for_false$6708fd83 condition-dead-code-elim.js:109:9
+ Registers: 6
Blocks: 9
Locals: x~0
Constants:
- [0] = Bool(false)
- [1] = Null
- [2] = Undefined
+ [0] = Undefined
+ [1] = Bool(false)
+ [2] = Null
block0:
[ 0] Enter
[ 8] Jump target:block2
block1:
- [ 10] End value:Undefined
+ [ 10] GetGlobal value_feedback:0, dst:reg5, `dead`
+ [ 20] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg5, this_value:Undefined
block2:
- [ 18] Jump target:block4
+ [ 40] Jump target:block4
block3:
- [ 20] End value:Undefined
+ [ 48] GetGlobal value_feedback:2, dst:reg5, `dead`
+ [ 58] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg5, this_value:Undefined
block4:
- [ 28] Jump target:block6
+ [ 78] Jump target:block6
block5:
- [ 30] End value:Undefined
+ [ 80] GetGlobal value_feedback:4, dst:reg5, `dead`
+ [ 90] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg5, this_value:Undefined
block6:
- [ 38] GetGlobal value_feedback:0, dst:reg5, `call_this`
- [ 48] Call value_feedback:1, call_feedback:0, dst:x~0, callee:reg5, this_value:Undefined, call_this
- [ 68] Jump target:block8
+ [ b0] GetGlobal value_feedback:6, dst:reg5, `call_this`
+ [ c0] Call value_feedback:7, call_feedback:3, dst:x~0, callee:reg5, this_value:Undefined
+ [ e0] Jump target:block8
block7:
- [ 70] End value:Undefined
+ [ e8] GetGlobal value_feedback:8, dst:reg5, `dead`
+ [ f8] Call value_feedback:9, call_feedback:4, dst:reg5, callee:reg5, this_value:Undefined
block8:
- [ 78] GetGlobal value_feedback:2, dst:reg6, `alive`
- [ 88] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, alive
- [ a8] End value:Undefined
+ [ 118] GetGlobal value_feedback:10, dst:reg5, `alive`
+ [ 128] Call value_feedback:11, call_feedback:5, dst:reg5, callee:reg5, this_value:Undefined
+ [ 148] End value:Undefined
call_this$f8b916c2 condition-dead-code-elim.js:105:5
@@ -235,50 +265,44 @@ block0:
[ 8] Return value:Int32(1)
-for_true$e6a6f225 condition-dead-code-elim.js:128:5
- Registers: 7
- Blocks: 11
+for_true$08bfa266 condition-dead-code-elim.js:128:9
+ Registers: 6
+ Blocks: 9
Constants:
- [0] = Bool(true)
- [1] = Undefined
+ [0] = Undefined
+ [1] = Bool(true)
[2] = Int32(1)
block0:
[ 0] Enter
- [ 8] Jump target:block2
+ [ 8] Jump target:block3
block1:
- [ 10] GetGlobal value_feedback:0, dst:reg6, `alive`
- [ 20] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, alive
- [ 40] JumpIf condition:arg0, true_target:block4, false_target:block5
+ [ 10] GetGlobal value_feedback:0, dst:reg5, `alive`
+ [ 20] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg5, this_value:Undefined
+ [ 40] JumpFalse condition:arg0, target:block3
block2:
- [ 50] JumpLoop target:block1
+ [ 50] Jump target:block4
block3:
- [ 58] Jump target:block7
+ [ 58] JumpLoop target:block1
block4:
- [ 60] JumpLoop target:block3
+ [ 60] Jump target:block7
block5:
- [ 68] JumpLoop target:block2
+ [ 68] GetGlobal value_feedback:2, dst:reg5, `alive`
+ [ 78] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg5, this_value:Undefined
+ [ 98] JumpFalse condition:arg0, target:block7
block6:
- [ 70] GetGlobal value_feedback:2, dst:reg6, `alive`
- [ 80] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, alive
- [ a0] JumpIf condition:arg0, true_target:block9, false_target:block10
+ [ a8] Jump target:block8
block7:
- [ b0] JumpLoop target:block6
+ [ b0] JumpLoop target:block5
block8:
- [ b8] GetGlobal value_feedback:4, dst:reg6, `alive`
- [ c8] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined, alive
+ [ b8] GetGlobal value_feedback:4, dst:reg5, `alive`
+ [ c8] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg5, this_value:Undefined
[ e8] End value:Undefined
-
-block9:
- [ f0] JumpLoop target:block8
-
-block10:
- [ f8] JumpLoop target:block7
diff --git a/Tests/LibJS/Bytecode/expected/conditional-register-order.txt b/Tests/LibJS/Bytecode/expected/conditional-register-order.txt
index 09b7b1cd532..6f3a078303a 100644
--- a/Tests/LibJS/Bytecode/expected/conditional-register-order.txt
+++ b/Tests/LibJS/Bytecode/expected/conditional-register-order.txt
@@ -1,4 +1,4 @@
-$2b997e90 conditional-register-order.js:4:1
+$28d58d80 conditional-register-order.js:4:1
Registers: 7
Blocks: 1
Constants:
@@ -6,14 +6,15 @@ $2b997e90 conditional-register-order.js:4:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `foo`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, foo
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `foo`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
foo$9e71f40c conditional-register-order.js:2:5
Registers: 6
- Blocks: 3
+ Blocks: 4
Constants:
[0] = Int32(1)
[1] = Int32(2)
@@ -24,8 +25,10 @@ block0:
block1:
[ 18] Mov dst:reg5, src:Int32(1)
- [ 28] Return value:reg5
+ [ 28] Jump target:block3
block2:
[ 30] Mov dst:reg5, src:Int32(2)
+
+block3:
[ 40] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/const-assignment-no-extra-tdz.txt b/Tests/LibJS/Bytecode/expected/const-assignment-no-extra-tdz.txt
index 2826e55c144..68b04dcdffa 100644
--- a/Tests/LibJS/Bytecode/expected/const-assignment-no-extra-tdz.txt
+++ b/Tests/LibJS/Bytecode/expected/const-assignment-no-extra-tdz.txt
@@ -1,32 +1,36 @@
-$0d47ea81 const-assignment-no-extra-tdz.js:5:1
- Registers: 9
- Blocks: 3
+$8ea9e309 const-assignment-no-extra-tdz.js:5:1
+ Registers: 7
+ Blocks: 4
Locals: e~0
Constants:
[0] = Undefined
+ [1] = <Empty>
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:reg5
- [ 10] Jump target:block2
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:Undefined
block1:
- [ 18] Catch value_feedback:0, dst:reg6
- [ 20] Mov3 c0_dst:e~0, c0_src:reg6, c1_dst:reg7, c1_src:Undefined, c2_dst:reg5, c2_src:reg7
- [ 40] End value:reg5
+ [ 28] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 38] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 58] Jump target:block3
block2:
- [ 48] MovSrcUndefined dst:reg6
- [ 50] GetGlobal value_feedback:1, dst:reg8, `f`
- [ 60] Call value_feedback:2, call_feedback:0, dst:reg7, callee:reg8, this_value:Undefined, f
- [ 80] Mov2 c0_dst:reg6, c0_src:reg7, c1_dst:reg5, c1_src:reg6
- [ 98] End value:reg5
+ [ 60] Catch value_feedback:2, dst:reg6
+ [ 68] Mov dst:reg5, src:Undefined
+ [ 78] Mov dst:e~0, src:<Empty>
+ [ 88] Mov dst:e~0, src:reg6
+ [ 98] Jump target:block3
+
+block3:
+ [ a0] End value:reg5
Exception handlers:
- [ 48 .. a0] => handler block1
+ [ 28 .. 60] => handler block2
-f$6007a144 const-assignment-no-extra-tdz.js:2:5
+f$c80d9f4a const-assignment-no-extra-tdz.js:2:11
Registers: 5
Blocks: 1
Locals: x~0
diff --git a/Tests/LibJS/Bytecode/expected/const-fold-exponentiation.txt b/Tests/LibJS/Bytecode/expected/const-fold-exponentiation.txt
index f014398aea8..ee93eed612f 100644
--- a/Tests/LibJS/Bytecode/expected/const-fold-exponentiation.txt
+++ b/Tests/LibJS/Bytecode/expected/const-fold-exponentiation.txt
@@ -1,21 +1,22 @@
-$5e3d9c55 const-fold-exponentiation.js:1:1
- Registers: 5
+$b6d67583 const-fold-exponentiation.js:1:7
+ Registers: 6
Blocks: 1
Constants:
- [0] = Int32(1)
- [1] = Int32(-1)
- [2] = Double(inf)
- [3] = Double(nan)
- [4] = Double(-inf)
- [5] = Int32(2)
- [6] = Int32(10)
- [7] = Int32(1024)
- [8] = Undefined
+ [0] = Undefined
+ [1] = Int32(1)
+ [2] = Int32(-1)
+ [3] = Double(inf)
+ [4] = Double(nan)
+ [5] = Double(-inf)
+ [6] = Int32(2)
+ [7] = Int32(10)
+ [8] = Int32(1024)
block0:
[ 0] Enter
- [ 8] DynamicInitializeLexicalBinding `a`, src:Double(nan)
- [ 18] DynamicInitializeLexicalBinding `b`, src:Double(nan)
- [ 28] DynamicInitializeLexicalBinding `c`, src:Double(nan)
- [ 38] DynamicInitializeLexicalBinding `d`, src:Int32(1024)
- [ 48] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] DynamicInitializeLexicalBinding `a`, src:Double(nan)
+ [ 28] DynamicInitializeLexicalBinding `b`, src:Double(nan)
+ [ 38] DynamicInitializeLexicalBinding `c`, src:Double(nan)
+ [ 48] DynamicInitializeLexicalBinding `d`, src:Int32(1024)
+ [ 58] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/const-fold-template-literals.txt b/Tests/LibJS/Bytecode/expected/const-fold-template-literals.txt
index 7e30782c385..fa59bd35c03 100644
--- a/Tests/LibJS/Bytecode/expected/const-fold-template-literals.txt
+++ b/Tests/LibJS/Bytecode/expected/const-fold-template-literals.txt
@@ -1,46 +1,47 @@
-$638fe0be const-fold-template-literals.js:20:1
+$9b013f68 const-fold-template-literals.js:20:7
Registers: 7
Blocks: 1
Constants:
- [0] = String("abc")
- [1] = String("xyz")
- [2] = String("abcxyz")
- [3] = String("")
- [4] = Undefined
+ [0] = Undefined
+ [1] = String("abc")
+ [2] = String("xyz")
+ [3] = String("abcxyz")
+ [4] = String("")
[5] = Int32(1)
[6] = Int32(2)
[7] = Int32(3)
block0:
[ 0] Enter
- [ 8] DynamicInitializeLexicalBinding `a`, src:String("abcxyz")
- [ 18] DynamicInitializeLexicalBinding `b`, src:String("abcxyz")
- [ 28] DynamicInitializeLexicalBinding `c`, src:String("abcxyz")
- [ 38] DynamicInitializeLexicalBinding `d`, src:String("abcxyz")
- [ 48] DynamicInitializeLexicalBinding `e`, src:String("abcxyz")
- [ 58] DynamicInitializeLexicalBinding `f`, src:String("abcxyz")
- [ 68] Mov dst:reg5, src:String("abc")
- [ 78] ConcatString dst:reg5, src:String("xyz")
- [ 88] DynamicInitializeLexicalBinding `g`, src:reg5
- [ 98] GetGlobal value_feedback:0, dst:reg6, `prefix`
- [ a8] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, prefix, arguments:[String("abc")]
- [ d0] DynamicInitializeLexicalBinding `_prefix`, src:reg5
- [ e0] GetGlobal value_feedback:2, dst:reg6, `suffix`
- [ f0] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, suffix, arguments:[String("abc")]
- [ 118] DynamicInitializeLexicalBinding `_suffix`, src:reg5
- [ 128] GetGlobal value_feedback:4, dst:reg6, `tostring`
- [ 138] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined, tostring, arguments:[String("abc")]
- [ 160] DynamicInitializeLexicalBinding `_tostring`, src:reg5
- [ 170] GetGlobal value_feedback:6, dst:reg6, `multi`
- [ 180] Call value_feedback:7, call_feedback:3, dst:reg5, callee:reg6, this_value:Undefined, multi, arguments:[Int32(1), Int32(2), Int32(3)]
- [ 1b0] DynamicInitializeLexicalBinding `_multi`, src:reg5
- [ 1c0] GetGlobal value_feedback:8, dst:reg6, `literal`
- [ 1d0] Call value_feedback:9, call_feedback:4, dst:reg5, callee:reg6, this_value:Undefined, literal
- [ 1f0] DynamicInitializeLexicalBinding `_literal`, src:reg5
- [ 200] GetGlobal value_feedback:10, dst:reg6, `empty`
- [ 210] Call value_feedback:11, call_feedback:5, dst:reg5, callee:reg6, this_value:Undefined, empty
- [ 230] DynamicInitializeLexicalBinding `_empty`, src:reg5
- [ 240] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] DynamicInitializeLexicalBinding `a`, src:String("abcxyz")
+ [ 28] DynamicInitializeLexicalBinding `b`, src:String("abcxyz")
+ [ 38] DynamicInitializeLexicalBinding `c`, src:String("abcxyz")
+ [ 48] DynamicInitializeLexicalBinding `d`, src:String("abcxyz")
+ [ 58] DynamicInitializeLexicalBinding `e`, src:String("abcxyz")
+ [ 68] DynamicInitializeLexicalBinding `f`, src:String("abcxyz")
+ [ 78] Mov dst:reg6, src:String("abc")
+ [ 88] ConcatString dst:reg6, src:String("xyz")
+ [ 98] DynamicInitializeLexicalBinding `g`, src:reg6
+ [ a8] GetGlobal value_feedback:0, dst:reg6, `prefix`
+ [ b8] Call value_feedback:1, call_feedback:0, dst:reg6, callee:reg6, this_value:Undefined, arguments:[String("abc")]
+ [ e0] DynamicInitializeLexicalBinding `_prefix`, src:reg6
+ [ f0] GetGlobal value_feedback:2, dst:reg6, `suffix`
+ [ 100] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg6, this_value:Undefined, arguments:[String("abc")]
+ [ 128] DynamicInitializeLexicalBinding `_suffix`, src:reg6
+ [ 138] GetGlobal value_feedback:4, dst:reg6, `tostring`
+ [ 148] Call value_feedback:5, call_feedback:2, dst:reg6, callee:reg6, this_value:Undefined, arguments:[String("abc")]
+ [ 170] DynamicInitializeLexicalBinding `_tostring`, src:reg6
+ [ 180] GetGlobal value_feedback:6, dst:reg6, `multi`
+ [ 190] Call value_feedback:7, call_feedback:3, dst:reg6, callee:reg6, this_value:Undefined, arguments:[Int32(1), Int32(2), Int32(3)]
+ [ 1c0] DynamicInitializeLexicalBinding `_multi`, src:reg6
+ [ 1d0] GetGlobal value_feedback:8, dst:reg6, `literal`
+ [ 1e0] Call value_feedback:9, call_feedback:4, dst:reg6, callee:reg6, this_value:Undefined
+ [ 200] DynamicInitializeLexicalBinding `_literal`, src:reg6
+ [ 210] GetGlobal value_feedback:10, dst:reg6, `empty`
+ [ 220] Call value_feedback:11, call_feedback:5, dst:reg6, callee:reg6, this_value:Undefined
+ [ 240] DynamicInitializeLexicalBinding `_empty`, src:reg6
+ [ 250] End value:reg5
prefix$ee05ef82 const-fold-template-literals.js:2:5
@@ -103,7 +104,7 @@ block0:
empty$c72ec9ec const-fold-template-literals.js:17:5
- Registers: 5
+ Registers: 6
Blocks: 1
Constants:
[0] = String("")
diff --git a/Tests/LibJS/Bytecode/expected/constant-fold-large-string-to-number.txt b/Tests/LibJS/Bytecode/expected/constant-fold-large-string-to-number.txt
index b4b37530312..2c71a5f5b1e 100644
--- a/Tests/LibJS/Bytecode/expected/constant-fold-large-string-to-number.txt
+++ b/Tests/LibJS/Bytecode/expected/constant-fold-large-string-to-number.txt
@@ -1,18 +1,19 @@
-$5e3d9c55 constant-fold-large-string-to-number.js:1:1
- Registers: 5
+$07237b81 constant-fold-large-string-to-number.js:1:5
+ Registers: 6
Blocks: 1
Constants:
- [0] = String("0x10000000000000000")
- [1] = Double(18446744073709552000)
- [2] = String("0xFFFFFFFFFFFFFFFF")
- [3] = String("0b10000000000000000000000000000000000000000000000000000000000000000")
- [4] = String("0o2000000000000000000000")
- [5] = Undefined
+ [0] = Undefined
+ [1] = String("0x10000000000000000")
+ [2] = Double(18446744073709552000)
+ [3] = String("0xFFFFFFFFFFFFFFFF")
+ [4] = String("0b10000000000000000000000000000000000000000000000000000000000000000")
+ [5] = String("0o2000000000000000000000")
block0:
[ 0] Enter
- [ 8] SetGlobal `a`, src:Double(18446744073709552000)
- [ 18] SetGlobal `b`, src:Double(18446744073709552000)
- [ 28] SetGlobal `c`, src:Double(18446744073709552000)
- [ 38] SetGlobal `d`, src:Double(18446744073709552000)
- [ 48] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] SetGlobal `a`, src:Double(18446744073709552000)
+ [ 28] SetGlobal `b`, src:Double(18446744073709552000)
+ [ 38] SetGlobal `c`, src:Double(18446744073709552000)
+ [ 48] SetGlobal `d`, src:Double(18446744073709552000)
+ [ 58] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/constant-fold-string-to-number.txt b/Tests/LibJS/Bytecode/expected/constant-fold-string-to-number.txt
index 96e66121e5c..427ee7e71a8 100644
--- a/Tests/LibJS/Bytecode/expected/constant-fold-string-to-number.txt
+++ b/Tests/LibJS/Bytecode/expected/constant-fold-string-to-number.txt
@@ -1,21 +1,22 @@
-$5e3d9c55 constant-fold-string-to-number.js:1:1
- Registers: 5
+$07237b81 constant-fold-string-to-number.js:1:5
+ Registers: 6
Blocks: 1
Constants:
- [0] = String("12345")
- [1] = Int32(12345)
- [2] = Int32(10)
- [3] = Int32(123450)
- [4] = String("42")
- [5] = Int32(-42)
- [6] = String("5")
- [7] = Int32(-6)
- [8] = Undefined
+ [0] = Undefined
+ [1] = String("12345")
+ [2] = Int32(12345)
+ [3] = Int32(10)
+ [4] = Int32(123450)
+ [5] = String("42")
+ [6] = Int32(-42)
+ [7] = String("5")
+ [8] = Int32(-6)
block0:
[ 0] Enter
- [ 8] SetGlobal `a`, src:Int32(12345)
- [ 18] SetGlobal `b`, src:Int32(123450)
- [ 28] SetGlobal `c`, src:Int32(-42)
- [ 38] SetGlobal `d`, src:Int32(-6)
- [ 48] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] SetGlobal `a`, src:Int32(12345)
+ [ 28] SetGlobal `b`, src:Int32(123450)
+ [ 38] SetGlobal `c`, src:Int32(-42)
+ [ 48] SetGlobal `d`, src:Int32(-6)
+ [ 58] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/debugger-statement.txt b/Tests/LibJS/Bytecode/expected/debugger-statement.txt
index 49a3dd302ad..7b6af5eb21d 100644
--- a/Tests/LibJS/Bytecode/expected/debugger-statement.txt
+++ b/Tests/LibJS/Bytecode/expected/debugger-statement.txt
@@ -1,4 +1,4 @@
-$e8d1e772 debugger-statement.js:6:1
+$e60df662 debugger-statement.js:6:1
Registers: 7
Blocks: 1
Constants:
@@ -6,9 +6,10 @@ $e8d1e772 debugger-statement.js:6:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `run`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, run
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `run`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
run$c8d7583b debugger-statement.js:2:5
diff --git a/Tests/LibJS/Bytecode/expected/default-param-self-reference.txt b/Tests/LibJS/Bytecode/expected/default-param-self-reference.txt
index 5c4f5fce3c8..3343a5c22b9 100644
--- a/Tests/LibJS/Bytecode/expected/default-param-self-reference.txt
+++ b/Tests/LibJS/Bytecode/expected/default-param-self-reference.txt
@@ -1,4 +1,4 @@
-$b865a0be default-param-self-reference.js:2:1
+$b5a1afae default-param-self-reference.js:2:1
Registers: 7
Blocks: 1
Constants:
@@ -7,12 +7,13 @@ $b865a0be default-param-self-reference.js:2:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[Int32(1)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(1)]
+ [ 50] End value:reg5
-f$55f1a862 default-param-self-reference.js:1:16
+f$b0fa3bce default-param-self-reference.js:1:12
Registers: 5
Blocks: 3
Constants:
@@ -26,7 +27,6 @@ block0:
block1:
[ 18] Mov dst:arg0, src:<Empty>
[ 28] ThrowIfTDZ src:arg0
- [ 30] Mov dst:arg0, src:arg0
block2:
- [ 40] End value:Undefined
+ [ 30] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/delete-expression-register.txt b/Tests/LibJS/Bytecode/expected/delete-expression-register.txt
index a0c67d8978e..187a56221f9 100644
--- a/Tests/LibJS/Bytecode/expected/delete-expression-register.txt
+++ b/Tests/LibJS/Bytecode/expected/delete-expression-register.txt
@@ -1,4 +1,4 @@
-$6a33dffa delete-expression-register.js:6:1
+$676feeea delete-expression-register.js:6:1
Registers: 7
Blocks: 1
Constants:
@@ -7,15 +7,16 @@ $6a33dffa delete-expression-register.js:6:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[Int32(1)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(1)]
+ [ 50] End value:reg5
-f$9f0a10bf delete-expression-register.js:3:7
+f$9c808ee0 delete-expression-register.js:2:9
Registers: 7
Blocks: 3
- Locals: x~0, arguments~1
+ Locals: arguments~0, x~1
Constants:
[0] = Undefined
[1] = Bool(false)
@@ -23,14 +24,15 @@ f$9f0a10bf delete-expression-register.js:3:7
block0:
[ 0] Enter
- [ 8] CreateArguments dst:arguments~1, is_immutable:false, creates_parameter_bindings:false
- [ 18] Mov3 c0_dst:x~0, c0_src:Undefined, c1_dst:x~0, c1_src:Bool(false), c2_dst:reg5, c2_src:x~0
- [ 38] JumpTrue condition:x~0, target:block2
+ [ 8] CreateArguments dst:arguments~0, is_immutable:false, creates_parameter_bindings:false
+ [ 18] Mov dst:x~1, src:Undefined
+ [ 28] Mov dst:x~1, src:Bool(false)
+ [ 38] Mov dst:reg5, src:x~1
+ [ 48] JumpTrue condition:reg5, target:block2
block1:
- [ 48] DeleteByValue dst:reg6, base:arguments~1, property:Int32(0)
- [ 58] Mov dst:reg5, src:reg6
+ [ 58] DeleteByValue dst:reg5, base:arguments~0, property:Int32(0)
block2:
- [ 68] Mov dst:x~0, src:reg5
- [ 78] Return value:x~0
+ [ 68] Mov dst:x~1, src:reg5
+ [ 78] Return value:x~1
diff --git a/Tests/LibJS/Bytecode/expected/delete-super-eval-order.txt b/Tests/LibJS/Bytecode/expected/delete-super-eval-order.txt
index d6ce8d8db90..3542bc1d024 100644
--- a/Tests/LibJS/Bytecode/expected/delete-super-eval-order.txt
+++ b/Tests/LibJS/Bytecode/expected/delete-super-eval-order.txt
@@ -1,39 +1,40 @@
-$e91e3953 delete-super-eval-order.js:4:1
- Registers: 10
- Blocks: 3
+$ebe22a63 delete-super-eval-order.js:4:1
+ Registers: 8
+ Blocks: 4
Constants:
- [0] = String("m")
- [1] = Undefined
+ [0] = Undefined
+ [1] = String("m")
[2] = String("x")
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `A`, is_immutable:true, is_global:false, is_strict:true
- [ 38] SetLexicalEnvironment environment:reg4
- [ 40] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:String("m")]
- [ 70] DynamicInitializeLexicalBinding `A`, src:reg6
- [ 80] MovSrcUndefined dst:reg6
- [ 88] Jump target:block2
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `A`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] SetLexicalEnvironment environment:reg4
+ [ 50] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0, element_keys:[element_keys:String("m")]
+ [ 80] DynamicInitializeLexicalBinding `A`, src:reg6
+ [ 90] Mov dst:reg5, src:Undefined
block1:
- [ 90] Catch value_feedback:0, dst:reg5
- [ 98] SetLexicalEnvironment environment:reg4
- [ a0] Mov2 c0_dst:reg7, c0_src:Undefined, c1_dst:reg6, c1_src:reg7
- [ b8] End value:reg6
+ [ a0] GetGlobal value_feedback:0, dst:reg6, `A`
+ [ b0] CallConstruct value_feedback:1, call_feedback:0, dst:reg6, callee:reg6
+ [ d0] GetById value_feedback:2, dst:reg7, base:reg6, `m`
+ [ e8] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[String("x")]
+ [ 110] Jump target:block3
block2:
- [ c0] MovSrcUndefined dst:reg5
- [ c8] GetGlobal value_feedback:1, dst:reg9, `A`
- [ d8] CallConstruct value_feedback:2, call_feedback:0, dst:reg8, callee:reg9, A
- [ f8] GetById value_feedback:3, dst:reg9, base:reg8, `m`
- [ 110] Call value_feedback:4, call_feedback:1, dst:reg7, callee:reg9, this_value:reg8, <object>.m, arguments:[String("x")]
- [ 138] Mov2 c0_dst:reg5, c0_src:reg7, c1_dst:reg6, c1_src:reg5
- [ 150] End value:reg6
+ [ 118] Catch value_feedback:4, dst:reg6
+ [ 120] SetLexicalEnvironment environment:reg4
+ [ 128] Mov dst:reg5, src:Undefined
+ [ 138] Jump target:block3
+
+block3:
+ [ 140] End value:reg5
Exception handlers:
- [ c0 .. 158] => handler block1
+ [ a0 .. 118] => handler block2
A$70678274
@@ -47,18 +48,13 @@ block0:
[ 8] End value:Undefined
-m$90de41ff delete-super-eval-order.js:6:9
- Registers: 7
- Blocks: 2
- Constants:
- [0] = Undefined
+m$0f7c4977 delete-super-eval-order.js:6:9
+ Registers: 6
+ Blocks: 1
block0:
[ 0] Enter
[ 8] ResolveThisBinding
[ 10] ResolveSuperBase dst:reg5
- [ 18] NewReferenceError dst:reg6, Can't delete a property on 'super'
- [ 28] Throw src:reg6
-
-block1:
- [ 30] End value:Undefined
+ [ 18] NewReferenceError dst:reg5, Can't delete a property on 'super'
+ [ 28] Throw src:reg5
diff --git a/Tests/LibJS/Bytecode/expected/delete-super-property.txt b/Tests/LibJS/Bytecode/expected/delete-super-property.txt
index efd03511208..a86e0306f81 100644
--- a/Tests/LibJS/Bytecode/expected/delete-super-property.txt
+++ b/Tests/LibJS/Bytecode/expected/delete-super-property.txt
@@ -1,59 +1,63 @@
$752dc5b7 delete-super-property.js:1:1
- Registers: 11
- Blocks: 6
+ Registers: 8
+ Blocks: 7
Locals: e~0, e~1
Constants:
- [0] = String("foo")
- [1] = String("baz")
- [2] = Undefined
+ [0] = Undefined
+ [1] = String("foo")
+ [2] = String("baz")
+ [3] = <Empty>
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `A`, is_immutable:true, is_global:false, is_strict:true
- [ 38] SetLexicalEnvironment environment:reg4
- [ 40] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:String("foo"), element_keys:String("baz")]
- [ 70] DynamicInitializeLexicalBinding `A`, src:reg6
- [ 80] MovSrcUndefined dst:reg6
- [ 88] Jump target:block3
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `A`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] SetLexicalEnvironment environment:reg4
+ [ 50] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0, element_keys:[element_keys:String("foo"), element_keys:String("baz")]
+ [ 80] DynamicInitializeLexicalBinding `A`, src:reg6
+ [ 90] Mov dst:reg5, src:Undefined
block1:
- [ 90] Catch value_feedback:0, dst:reg5
- [ 98] SetLexicalEnvironment environment:reg4
- [ a0] Mov3 c0_dst:e~0, c0_src:reg5, c1_dst:reg7, c1_src:Undefined, c2_dst:reg6, c2_src:reg7
+ [ a0] GetGlobal value_feedback:0, dst:reg6, `A`
+ [ b0] CallConstruct value_feedback:1, call_feedback:0, dst:reg6, callee:reg6
+ [ d0] GetById value_feedback:2, dst:reg7, base:reg6, `foo`
+ [ e8] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6
+ [ 108] Jump target:block3
block2:
- [ c0] MovSrcUndefined dst:reg5
- [ c8] Jump target:block5
+ [ 110] Catch value_feedback:4, dst:reg6
+ [ 118] SetLexicalEnvironment environment:reg4
+ [ 120] Mov dst:reg5, src:Undefined
+ [ 130] Mov dst:e~0, src:<Empty>
+ [ 140] Mov dst:e~0, src:reg6
+ [ 150] Jump target:block3
block3:
- [ d0] MovSrcUndefined dst:reg5
- [ d8] GetGlobal value_feedback:1, dst:reg9, `A`
- [ e8] CallConstruct value_feedback:2, call_feedback:0, dst:reg8, callee:reg9, A
- [ 108] GetById value_feedback:3, dst:reg9, base:reg8, `foo`
- [ 120] Call value_feedback:4, call_feedback:1, dst:reg7, callee:reg9, this_value:reg8, <object>.foo
- [ 140] Mov2 c0_dst:reg5, c0_src:reg7, c1_dst:reg6, c1_src:reg5
- [ 158] JumpLoop target:block2
+ [ 158] Mov dst:reg5, src:Undefined
block4:
- [ 160] Catch value_feedback:5, dst:reg7
- [ 168] SetLexicalEnvironment environment:reg4
- [ 170] Mov3 c0_dst:e~1, c0_src:reg7, c1_dst:reg9, c1_src:Undefined, c2_dst:reg5, c2_src:reg9
- [ 190] End value:reg5
+ [ 168] GetGlobal value_feedback:5, dst:reg6, `A`
+ [ 178] CallConstruct value_feedback:6, call_feedback:2, dst:reg6, callee:reg6
+ [ 198] GetById value_feedback:7, dst:reg7, base:reg6, `baz`
+ [ 1b0] Call value_feedback:8, call_feedback:3, dst:reg5, callee:reg7, this_value:reg6
+ [ 1d0] Jump target:block6
block5:
- [ 198] MovSrcUndefined dst:reg7
- [ 1a0] GetGlobal value_feedback:6, dst:reg10, `A`
- [ 1b0] CallConstruct value_feedback:7, call_feedback:2, dst:reg8, callee:reg10, A
- [ 1d0] GetById value_feedback:8, dst:reg10, base:reg8, `baz`
- [ 1e8] Call value_feedback:9, call_feedback:3, dst:reg9, callee:reg10, this_value:reg8, <object>.baz
- [ 208] Mov2 c0_dst:reg7, c0_src:reg9, c1_dst:reg5, c1_src:reg7
+ [ 1d8] Catch value_feedback:9, dst:reg6
+ [ 1e0] SetLexicalEnvironment environment:reg4
+ [ 1e8] Mov dst:reg5, src:Undefined
+ [ 1f8] Mov dst:e~1, src:<Empty>
+ [ 208] Mov dst:e~1, src:reg6
+ [ 218] Jump target:block6
+
+block6:
[ 220] End value:reg5
Exception handlers:
- [ d0 .. 160] => handler block1
- [ 198 .. 228] => handler block4
+ [ a0 .. 110] => handler block2
+ [ 168 .. 1d8] => handler block5
A$70678274
@@ -67,36 +71,27 @@ block0:
[ 8] End value:Undefined
-foo$f5a5dc81 delete-super-property.js:3:9
- Registers: 7
- Blocks: 2
- Constants:
- [0] = Undefined
+foo$7707d509 delete-super-property.js:3:9
+ Registers: 6
+ Blocks: 1
block0:
[ 0] Enter
[ 8] ResolveThisBinding
[ 10] ResolveSuperBase dst:reg5
- [ 18] NewReferenceError dst:reg6, Can't delete a property on 'super'
- [ 28] Throw src:reg6
+ [ 18] NewReferenceError dst:reg5, Can't delete a property on 'super'
+ [ 28] Throw src:reg5
-block1:
- [ 30] End value:Undefined
-
-baz$09694243 delete-super-property.js:6:9
- Registers: 7
- Blocks: 2
+baz$8acb3acb delete-super-property.js:6:9
+ Registers: 6
+ Blocks: 1
Constants:
[0] = String("bar")
- [1] = Undefined
block0:
[ 0] Enter
[ 8] ResolveThisBinding
[ 10] ResolveSuperBase dst:reg5
- [ 18] NewReferenceError dst:reg6, Can't delete a property on 'super'
- [ 28] Throw src:reg6
-
-block1:
- [ 30] End value:Undefined
+ [ 18] NewReferenceError dst:reg5, Can't delete a property on 'super'
+ [ 28] Throw src:reg5
diff --git a/Tests/LibJS/Bytecode/expected/destructure-array-rest.txt b/Tests/LibJS/Bytecode/expected/destructure-array-rest.txt
index f58eb13b581..0ccdff7aecd 100644
--- a/Tests/LibJS/Bytecode/expected/destructure-array-rest.txt
+++ b/Tests/LibJS/Bytecode/expected/destructure-array-rest.txt
@@ -1,4 +1,4 @@
-$fd650eed destructure-array-rest.js:9:1
+$faa11ddd destructure-array-rest.js:9:1
Registers: 7
Blocks: 1
Constants:
@@ -6,92 +6,75 @@ $fd650eed destructure-array-rest.js:9:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-f$4683b1b6 destructure-array-rest.js:6:5
- Registers: 14
- Blocks: 19
+f$208077fb destructure-array-rest.js:6:5
+ Registers: 12
+ Blocks: 14
Locals: a~0, b~1
Constants:
- [0] = Bool(false)
- [1] = Undefined
- [2] = Int32(1)
- [3] = Int32(2)
+ [0] = <Empty>
+ [1] = Int32(1)
+ [2] = Int32(2)
+ [3] = Int32(3)
+ [4] = Bool(false)
+ [5] = Undefined
block0:
[ 0] Enter
- [ 8] NewPrimitiveArray dst:reg5, elements:[1, 2, 3]
- [ 30] Mov dst:reg6, src:Bool(false)
- [ 40] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5, fast_array_mode_allowed:true
- [ 60] Jump target:block3
+ [ 8] Mov dst:a~0, src:<Empty>
+ [ 18] Mov dst:b~1, src:<Empty>
+ [ 28] NewPrimitiveArray dst:reg5, elements:[1, 2, 3]
+ [ 50] Mov dst:reg6, src:Bool(false)
+ [ 60] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5, fast_array_mode_allowed:true
+ [ 80] IteratorNextUnpack dst_value:reg10, dst_done:reg6, iterator_object:reg7, iterator_next:reg8, iterator_done:reg9
block1:
- [ 68] Catch value_feedback:0, dst:reg11
- [ 70] Mov dst:reg10, src:Int32(1)
- [ 80] JumpIf condition:reg9, true_target:block14, false_target:block13
+ [ 98] JumpFalse condition:reg6, target:block3
block2:
- [ 90] Return value:b~1
+ [ a8] Mov dst:reg10, src:Undefined
block3:
- [ 98] Jump target:block5
+ [ b8] Mov dst:a~0, src:reg10
+ [ c8] JumpTrue condition:reg6, target:block6
block4:
- [ a0] MovSrcUndefined dst:reg12
- [ a8] Jump target:block6
+ [ d8] IteratorToArray dst:reg10, iterator_object:reg7, iterator_next_method:reg8, iterator_done_property:reg9
block5:
- [ b0] IteratorNextUnpack dst_value:reg12, dst_done:reg6, iterator_object:reg7, iterator_next:reg8, iterator_done:reg9
- [ c8] JumpTrueLoop condition:reg6, target:block4
+ [ f0] Jump target:block7
block6:
- [ d8] Mov dst:a~0, src:reg12
- [ e8] JumpFalse condition:reg6, target:block8
+ [ f8] NewArray dst:reg10
block7:
- [ f8] NewArray dst:reg13
- [ 108] Jump target:block9
+ [ 108] Mov dst:b~1, src:reg10
block8:
- [ 110] IteratorToArray dst:reg13, iterator_object:reg7, iterator_next_method:reg8, iterator_done_property:reg9
+ [ 118] JumpTrue condition:reg9, target:block13
block9:
- [ 128] Mov dst:b~1, src:reg13
+ [ 128] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:Undefined
+ [ 148] Jump target:block13
block10:
- [ 138] JumpFalse condition:reg9, target:block12
+ [ 150] Catch value_feedback:0, dst:reg11
+ [ 158] JumpTrue condition:reg9, target:block12
block11:
- [ 148] Return value:b~1
+ [ 168] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:reg11
block12:
- [ 150] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:Undefined
- [ 170] JumpLoop target:block11
+ [ 188] Throw src:reg11
block13:
- [ 178] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg10, rhs:1, true_target:block15, false_target:block16
-
-block14:
- [ 190] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg10, rhs:2, true_target:block17, false_target:block18
-
-block15:
- [ 1a8] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:reg11
- [ 1c8] Throw src:reg11
-
-block16:
- [ 1d0] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:Undefined
- [ 1f0] JumpLoop target:block14
-
-block17:
- [ 1f8] Return value:reg11
-
-block18:
- [ 200] Throw src:reg11
+ [ 190] Return value:b~1
Exception handlers:
- [ 98 .. b0] => handler block1
- [ d8 .. 110] => handler block1
- [ 128 .. 138] => handler block1
+ [ 98 .. d8] => handler block10
+ [ f0 .. 118] => handler block10
diff --git a/Tests/LibJS/Bytecode/expected/destructuring-assignment-in-logical-and.txt b/Tests/LibJS/Bytecode/expected/destructuring-assignment-in-logical-and.txt
index 758b27db651..03a4d6776a4 100644
--- a/Tests/LibJS/Bytecode/expected/destructuring-assignment-in-logical-and.txt
+++ b/Tests/LibJS/Bytecode/expected/destructuring-assignment-in-logical-and.txt
@@ -1,4 +1,4 @@
-$9431c529 destructuring-assignment-in-logical-and.js:5:1
+$916dd419 destructuring-assignment-in-logical-and.js:5:1
Registers: 7
Blocks: 1
Constants:
@@ -8,102 +8,78 @@ $9431c529 destructuring-assignment-in-logical-and.js:5:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[Null, Int32(0)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Null, Int32(0)]
+ [ 50] End value:reg5
-f$6d0ab5b2 destructuring-assignment-in-logical-and.js:2:5
- Registers: 14
- Blocks: 21
+f$d31b6efb destructuring-assignment-in-logical-and.js:2:9
+ Registers: 13
+ Blocks: 16
Locals: a~0, b~1
Constants:
[0] = Undefined
[1] = Bool(false)
- [2] = Int32(1)
- [3] = Int32(2)
block0:
[ 0] Enter
- [ 8] Mov3 c0_dst:a~0, c0_src:Undefined, c1_dst:b~1, c1_src:Undefined, c2_dst:reg5, c2_src:arg0
- [ 28] JumpFalse condition:arg0, target:block2
+ [ 8] Mov dst:a~0, src:Undefined
+ [ 18] Mov dst:b~1, src:Undefined
+ [ 28] Mov dst:reg5, src:arg0
+ [ 38] JumpFalse condition:reg5, target:block15
block1:
- [ 38] Mov2 c0_dst:reg7, c0_src:arg0, c1_dst:reg8, c1_src:arg1
- [ 50] Call value_feedback:0, call_feedback:0, dst:reg6, callee:reg7, this_value:Undefined, t, arguments:[reg8]
- [ 78] Mov dst:reg7, src:Bool(false)
- [ 88] GetIterator dst_iterator_object:reg8, dst_iterator_next:reg9, dst_iterator_done:reg10, iterable:reg6, fast_array_mode_allowed:true
- [ a8] Jump target:block5
+ [ 48] Call value_feedback:0, call_feedback:0, dst:reg7, callee:arg0, this_value:Undefined, arguments:[arg1]
+ [ 70] Mov dst:reg8, src:Bool(false)
+ [ 80] GetIterator dst_iterator_object:reg9, dst_iterator_next:reg10, dst_iterator_done:reg11, iterable:reg7, fast_array_mode_allowed:true
+ [ a0] IteratorNextUnpack dst_value:reg12, dst_done:reg8, iterator_object:reg9, iterator_next:reg10, iterator_done:reg11
block2:
- [ b0] End value:Undefined
+ [ b8] JumpFalse condition:reg8, target:block4
block3:
- [ b8] Catch value_feedback:1, dst:reg12
- [ c0] Mov dst:reg11, src:Int32(1)
- [ d0] JumpIf condition:reg10, true_target:block16, false_target:block15
+ [ c8] Mov dst:reg12, src:Undefined
block4:
- [ e0] Mov dst:reg5, src:reg6
- [ f0] JumpLoop target:block2
+ [ d8] Mov dst:a~0, src:reg12
+ [ e8] JumpTrue condition:reg8, target:block7
block5:
- [ f8] Jump target:block7
+ [ f8] IteratorNextUnpack dst_value:reg12, dst_done:reg8, iterator_object:reg9, iterator_next:reg10, iterator_done:reg11
block6:
- [ 100] MovSrcUndefined dst:reg13
- [ 108] Jump target:block8
+ [ 110] JumpFalse condition:reg8, target:block8
block7:
- [ 110] IteratorNextUnpack dst_value:reg13, dst_done:reg7, iterator_object:reg8, iterator_next:reg9, iterator_done:reg10
- [ 128] JumpTrueLoop condition:reg7, target:block6
+ [ 120] Mov dst:reg12, src:Undefined
block8:
- [ 138] Mov dst:a~0, src:reg13
- [ 148] JumpFalse condition:reg7, target:block10
+ [ 130] Mov dst:b~1, src:reg12
block9:
- [ 158] MovSrcUndefined dst:reg13
- [ 160] Jump target:block11
+ [ 140] JumpTrue condition:reg11, target:block14
block10:
- [ 168] IteratorNextUnpack dst_value:reg13, dst_done:reg7, iterator_object:reg8, iterator_next:reg9, iterator_done:reg10
- [ 180] JumpTrueLoop condition:reg7, target:block9
+ [ 150] IteratorClose iterator_object:reg9, iterator_next:reg10, iterator_done:reg11, completion_value:Undefined
+ [ 170] Jump target:block14
block11:
- [ 190] Mov dst:b~1, src:reg13
+ [ 178] Catch value_feedback:1, dst:reg12
+ [ 180] JumpTrue condition:reg11, target:block13
block12:
- [ 1a0] JumpFalse condition:reg10, target:block14
+ [ 190] IteratorClose iterator_object:reg9, iterator_next:reg10, iterator_done:reg11, completion_value:reg12
block13:
- [ 1b0] JumpLoop target:block4
+ [ 1b0] Throw src:reg12
block14:
- [ 1b8] IteratorClose iterator_object:reg8, iterator_next:reg9, iterator_done:reg10, completion_value:Undefined
- [ 1d8] JumpLoop target:block13
+ [ 1b8] Mov dst:reg5, src:reg7
block15:
- [ 1e0] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg11, rhs:1, true_target:block17, false_target:block18
-
-block16:
- [ 1f8] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg11, rhs:2, true_target:block19, false_target:block20
-
-block17:
- [ 210] IteratorClose iterator_object:reg8, iterator_next:reg9, iterator_done:reg10, completion_value:reg12
- [ 230] Throw src:reg12
-
-block18:
- [ 238] IteratorClose iterator_object:reg8, iterator_next:reg9, iterator_done:reg10, completion_value:Undefined
- [ 258] JumpLoop target:block16
-
-block19:
- [ 260] Return value:reg12
-
-block20:
- [ 268] Throw src:reg12
+ [ 1c8] End value:Undefined
Exception handlers:
- [ f8 .. 110] => handler block3
- [ 138 .. 168] => handler block3
- [ 190 .. 1a0] => handler block3
+ [ b8 .. f8] => handler block11
+ [ 110 .. 140] => handler block11
diff --git a/Tests/LibJS/Bytecode/expected/destructuring-assignment.txt b/Tests/LibJS/Bytecode/expected/destructuring-assignment.txt
index 6bc9a995457..5cc1d77cc90 100644
--- a/Tests/LibJS/Bytecode/expected/destructuring-assignment.txt
+++ b/Tests/LibJS/Bytecode/expected/destructuring-assignment.txt
@@ -1,109 +1,84 @@
-$f02c5cc8 destructuring-assignment.js:28:1
- Registers: 8
+$f2f04dd8 destructuring-assignment.js:28:1
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `array_destructuring_with_class_default`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, array_destructuring_with_class_default
- [ 38] GetGlobal value_feedback:2, dst:reg7, `object_destructuring_with_function_default`
- [ 48] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, object_destructuring_with_function_default
- [ 68] GetGlobal value_feedback:4, dst:reg7, `setter_parameter_resolution`
- [ 78] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg7, this_value:Undefined, setter_parameter_resolution
- [ 98] End value:reg5
-
-
-array_destructuring_with_class_default$58df6358 destructuring-assignment.js:6:10
- Registers: 15
- Blocks: 18
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `array_destructuring_with_class_default`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] GetGlobal value_feedback:2, dst:reg6, `object_destructuring_with_function_default`
+ [ 58] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined
+ [ 78] GetGlobal value_feedback:4, dst:reg6, `setter_parameter_resolution`
+ [ 88] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined
+ [ a8] End value:reg5
+
+
+array_destructuring_with_class_default$125a2281 destructuring-assignment.js:5:9
+ Registers: 14
+ Blocks: 12
Locals: x~0
Constants:
[0] = Undefined
[1] = Bool(false)
- [2] = Int32(1)
- [3] = Int32(2)
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] MovSrcUndefined dst:x~0
- [ 18] NewArray dst:reg5, elements:[Undefined]
- [ 30] Mov dst:reg6, src:Bool(false)
- [ 40] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5, fast_array_mode_allowed:true
- [ 60] Jump target:block3
+ [ 8] Mov dst:x~0, src:Undefined
+ [ 18] GetLexicalEnvironment dst:reg4
+ [ 20] NewArray dst:reg6, elements:[Undefined]
+ [ 38] Mov dst:reg7, src:Bool(false)
+ [ 48] GetIterator dst_iterator_object:reg8, dst_iterator_next:reg9, dst_iterator_done:reg10, iterable:reg6, fast_array_mode_allowed:true
+ [ 68] IteratorNextUnpack dst_value:reg11, dst_done:reg7, iterator_object:reg8, iterator_next:reg9, iterator_done:reg10
block1:
- [ 68] Catch value_feedback:0, dst:reg11
- [ 70] SetLexicalEnvironment environment:reg4
- [ 78] Mov dst:reg10, src:Int32(1)
- [ 88] JumpIf condition:reg9, true_target:block13, false_target:block12
+ [ 80] JumpFalse condition:reg7, target:block3
block2:
- [ 98] Return value:x~0
+ [ 90] Mov dst:reg11, src:Undefined
block3:
- [ a0] Jump target:block5
+ [ a0] JumpUndefined condition:reg11, true_target:block4, false_target:block5
block4:
- [ a8] MovSrcUndefined dst:reg12
- [ b0] Jump target:block6
+ [ b0] CreateLexicalEnvironment dst:reg13, parent:reg4, capacity:1, is_catch_environment:false
+ [ c8] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
+ [ d8] SetLexicalEnvironment environment:reg4
+ [ e0] NewClass dst:reg12, class_environment:reg13, class_blueprint_index:0
+ [ 108] Mov dst:reg11, src:reg12
block5:
- [ b8] IteratorNextUnpack dst_value:reg12, dst_done:reg6, iterator_object:reg7, iterator_next:reg8, iterator_done:reg9
- [ d0] JumpTrueLoop condition:reg6, target:block4
+ [ 118] Mov dst:x~0, src:reg11
block6:
- [ e0] JumpUndefined condition:reg12, true_target:block7, false_target:block8
+ [ 128] JumpTrue condition:reg10, target:block11
block7:
- [ f0] CreateLexicalEnvironment dst:reg13, parent:reg4, capacity:1, is_catch_environment:false
- [ 108] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
- [ 118] SetLexicalEnvironment environment:reg4
- [ 120] NewClass dst:reg14, class_environment:reg13, class_blueprint_index:0
- [ 148] Mov dst:reg12, src:reg14
+ [ 138] IteratorClose iterator_object:reg8, iterator_next:reg9, iterator_done:reg10, completion_value:Undefined
+ [ 158] Jump target:block11
block8:
- [ 158] Mov dst:x~0, src:reg12
+ [ 160] Catch value_feedback:0, dst:reg11
+ [ 168] SetLexicalEnvironment environment:reg4
+ [ 170] JumpTrue condition:reg10, target:block10
block9:
- [ 168] JumpFalse condition:reg9, target:block11
+ [ 180] IteratorClose iterator_object:reg8, iterator_next:reg9, iterator_done:reg10, completion_value:reg11
block10:
- [ 178] Return value:x~0
+ [ 1a0] Throw src:reg11
block11:
- [ 180] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:Undefined
- [ 1a0] JumpLoop target:block10
-
-block12:
- [ 1a8] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg10, rhs:1, true_target:block14, false_target:block15
-
-block13:
- [ 1c0] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg10, rhs:2, true_target:block16, false_target:block17
-
-block14:
- [ 1d8] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:reg11
- [ 1f8] Throw src:reg11
-
-block15:
- [ 200] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:Undefined
- [ 220] JumpLoop target:block13
-
-block16:
- [ 228] Return value:reg11
-
-block17:
- [ 230] Throw src:reg11
+ [ 1a8] Return value:x~0
Exception handlers:
- [ a0 .. b8] => handler block1
- [ e0 .. 168] => handler block1
+ [ 80 .. 128] => handler block8
-object_destructuring_with_function_default$cadc791a destructuring-assignment.js:12:12
- Registers: 8
+object_destructuring_with_function_default$66979be0 destructuring-assignment.js:11:9
+ Registers: 9
Blocks: 3
Locals: x~0
Constants:
@@ -111,98 +86,78 @@ object_destructuring_with_function_default$cadc791a destructuring-assignment.js:
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:x~0
- [ 10] NewObject dst:reg5
- [ 20] ThrowIfNullish src:reg5
- [ 28] GetById value_feedback:0, dst:reg6, base:reg5, `x`
- [ 40] JumpUndefined condition:reg6, true_target:block1, false_target:block2
+ [ 8] Mov dst:x~0, src:Undefined
+ [ 18] NewObject dst:reg5
+ [ 28] Mov dst:reg6, src:reg5
+ [ 38] ThrowIfNullish src:reg6
+ [ 40] GetById value_feedback:0, dst:reg7, base:reg6, `x`
+ [ 58] JumpUndefined condition:reg7, true_target:block1, false_target:block2
block1:
- [ 50] NewFunction dst:reg7, shared_function_data_index:0 (x)
- [ 68] Mov dst:reg6, src:reg7
+ [ 68] NewFunction dst:reg7, shared_function_data_index:0 (x)
block2:
- [ 78] Mov dst:x~0, src:reg6
- [ 88] Return value:x~0
+ [ 80] Mov dst:x~0, src:reg7
+ [ 90] Return value:x~0
-setter_parameter_resolution$f1fdebeb destructuring-assignment.js:19:9
- Registers: 14
- Blocks: 16
+setter_parameter_resolution$dac170a8 destructuring-assignment.js:17:9
+ Registers: 13
+ Blocks: 12
Constants:
[0] = Undefined
- [1] = Bool(false)
- [2] = Int32(1)
- [3] = Int32(2)
+ [1] = Int32(23)
+ [2] = Bool(false)
block0:
[ 0] Enter
[ 8] CreateVariable `setValue`, is_immutable:false, is_global:false, is_strict:false
[ 18] InitializeVariableBinding `setValue`, src:Undefined
- [ 30] NewPrimitiveArray dst:reg5, elements:[23]
- [ 48] Mov dst:reg6, src:Bool(false)
- [ 58] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5, fast_array_mode_allowed:true
- [ 78] Jump target:block3
+ [ 30] NewPrimitiveArray dst:reg6, elements:[23]
+ [ 48] Mov dst:reg7, src:Bool(false)
+ [ 58] GetIterator dst_iterator_object:reg8, dst_iterator_next:reg9, dst_iterator_done:reg10, iterable:reg6, fast_array_mode_allowed:true
block1:
- [ 80] Catch value_feedback:0, dst:reg11
- [ 88] Mov dst:reg10, src:Int32(1)
- [ 98] JumpIf condition:reg9, true_target:block11, false_target:block10
+ [ 78] NewObject dst:reg11
+ [ 88] NewFunction dst:reg12, shared_function_data_index:0 (set y), home_object:reg11
+ [ a0] PutById base:reg11, `y`, src:reg12, kind:Setter
block2:
- [ a8] GetInitializedBinding value_feedback:1, dst:reg5, `setValue`
- [ c0] Return value:reg5
+ [ c0] IteratorNextUnpack dst_value:reg12, dst_done:reg7, iterator_object:reg8, iterator_next:reg9, iterator_done:reg10
block3:
- [ c8] NewObject dst:reg12
- [ d8] NewFunction dst:reg13, shared_function_data_index:0 (set y), home_object:reg12
- [ f0] PutById base:reg12, `y`, src:reg13, kind:Setter
- [ 110] Jump target:block5
+ [ d8] JumpFalse condition:reg7, target:block5
block4:
- [ 118] MovSrcUndefined dst:reg13
- [ 120] Jump target:block6
+ [ e8] Mov dst:reg12, src:Undefined
block5:
- [ 128] IteratorNextUnpack dst_value:reg13, dst_done:reg6, iterator_object:reg7, iterator_next:reg8, iterator_done:reg9
- [ 140] JumpTrueLoop condition:reg6, target:block4
+ [ f8] PutById base:reg11, `y`, src:reg12, kind:Normal
block6:
- [ 150] PutById base:reg12, `y`, src:reg13, kind:Normal
+ [ 118] JumpTrue condition:reg10, target:block11
block7:
- [ 170] JumpFalse condition:reg9, target:block9
+ [ 128] IteratorClose iterator_object:reg8, iterator_next:reg9, iterator_done:reg10, completion_value:Undefined
+ [ 148] Jump target:block11
block8:
- [ 180] JumpLoop target:block2
+ [ 150] Catch value_feedback:0, dst:reg11
+ [ 158] JumpTrue condition:reg10, target:block10
block9:
- [ 188] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:Undefined
- [ 1a8] JumpLoop target:block8
+ [ 168] IteratorClose iterator_object:reg8, iterator_next:reg9, iterator_done:reg10, completion_value:reg11
block10:
- [ 1b0] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg10, rhs:1, true_target:block12, false_target:block13
+ [ 188] Throw src:reg11
block11:
- [ 1c8] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg10, rhs:2, true_target:block14, false_target:block15
-
-block12:
- [ 1e0] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:reg11
- [ 200] Throw src:reg11
-
-block13:
- [ 208] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:Undefined
- [ 228] JumpLoop target:block11
-
-block14:
- [ 230] Return value:reg11
-
-block15:
- [ 238] Throw src:reg11
+ [ 190] GetInitializedBinding value_feedback:1, dst:reg5, `setValue`
+ [ 1a8] Return value:reg5
Exception handlers:
- [ c8 .. 128] => handler block1
- [ 150 .. 170] => handler block1
+ [ 78 .. c0] => handler block8
+ [ d8 .. 118] => handler block8
set y$f1335721 destructuring-assignment.js:21:26
diff --git a/Tests/LibJS/Bytecode/expected/destructuring-let-compound-assign.txt b/Tests/LibJS/Bytecode/expected/destructuring-let-compound-assign.txt
index 2753aa4fe37..5eedea62e58 100644
--- a/Tests/LibJS/Bytecode/expected/destructuring-let-compound-assign.txt
+++ b/Tests/LibJS/Bytecode/expected/destructuring-let-compound-assign.txt
@@ -1,4 +1,4 @@
-$99b9a749 destructuring-let-compound-assign.js:5:1
+$96f5b639 destructuring-let-compound-assign.js:5:1
Registers: 9
Blocks: 1
Constants:
@@ -6,29 +6,30 @@ $99b9a749 destructuring-let-compound-assign.js:5:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] NewObject dst:reg7
- [ 28] NewObject dst:reg8
- [ 38] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[reg7, reg8]
- [ 60] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] NewObject dst:reg7
+ [ 38] NewObject dst:reg8
+ [ 48] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7, reg8]
+ [ 70] End value:reg5
-f$f789224c destructuring-let-compound-assign.js:2:5
- Registers: 8
+f$7baf0be4 destructuring-let-compound-assign.js:2:5
+ Registers: 7
Blocks: 1
Locals: a~0
Constants:
- [0] = Int32(16)
- [1] = Undefined
+ [0] = <Empty>
+ [1] = Int32(16)
+ [2] = Undefined
block0:
[ 0] Enter
- [ 8] ThrowIfNullish src:arg0
- [ 10] Mov dst:reg5, src:arg0
- [ 20] GetById value_feedback:0, dst:reg6, base:reg5, `patchFlag`
- [ 38] Mov2 c0_dst:a~0, c0_src:reg6, c1_dst:reg5, c1_src:a~0
- [ 50] GetById value_feedback:1, dst:reg6, base:arg1, `patchFlag` (e.patchFlag)
- [ 68] BitwiseAnd arith_feedback:0, dst:reg7, lhs:Int32(16), rhs:reg6
- [ 78] BitwiseOr arith_feedback:1, dst:reg6, lhs:reg5, rhs:reg7
- [ 88] Mov dst:a~0, src:reg6
- [ 98] End value:Undefined
+ [ 8] Mov dst:a~0, src:<Empty>
+ [ 18] ThrowIfNullish src:arg0
+ [ 20] Mov dst:reg5, src:arg0
+ [ 30] GetById value_feedback:0, dst:a~0, base:reg5, `patchFlag`
+ [ 48] GetById value_feedback:1, dst:reg5, base:arg1, `patchFlag`
+ [ 60] BitwiseAnd arith_feedback:0, dst:reg5, lhs:Int32(16), rhs:reg5
+ [ 70] BitwiseOr arith_feedback:1, dst:a~0, lhs:a~0, rhs:reg5
+ [ 80] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/destructuring-no-base-identifier.txt b/Tests/LibJS/Bytecode/expected/destructuring-no-base-identifier.txt
index 4741be9c234..5dcaaf48bc8 100644
--- a/Tests/LibJS/Bytecode/expected/destructuring-no-base-identifier.txt
+++ b/Tests/LibJS/Bytecode/expected/destructuring-no-base-identifier.txt
@@ -1,74 +1,56 @@
-$bf243d42 destructuring-no-base-identifier.js:1:1
+$46dacfae destructuring-no-base-identifier.js:1:5
Registers: 14
- Blocks: 16
+ Blocks: 12
Constants:
- [0] = Bool(false)
- [1] = Undefined
- [2] = Int32(1)
- [3] = Int32(2)
+ [0] = Undefined
+ [1] = Int32(42)
+ [2] = Bool(false)
block0:
[ 0] Enter
- [ 8] NewObject dst:reg5
- [ 18] SetGlobal `x`, src:reg5
- [ 28] NewPrimitiveArray dst:reg5, elements:[42]
- [ 40] Mov dst:reg6, src:Bool(false)
- [ 50] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5, fast_array_mode_allowed:true
- [ 70] Jump target:block3
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] NewObject dst:reg6
+ [ 28] SetGlobal `x`, src:reg6
+ [ 38] NewPrimitiveArray dst:reg7, elements:[42]
+ [ 50] Mov dst:reg8, src:Bool(false)
+ [ 60] GetIterator dst_iterator_object:reg9, dst_iterator_next:reg10, dst_iterator_done:reg11, iterable:reg7, fast_array_mode_allowed:true
block1:
- [ 78] Catch value_feedback:1, dst:reg11
- [ 80] Mov dst:reg10, src:Int32(1)
- [ 90] JumpIf condition:reg9, true_target:block11, false_target:block10
+ [ 80] GetGlobal value_feedback:0, dst:reg12, `x`
block2:
- [ a0] End value:reg5
+ [ 90] IteratorNextUnpack dst_value:reg13, dst_done:reg8, iterator_object:reg9, iterator_next:reg10, iterator_done:reg11
block3:
- [ a8] GetGlobal value_feedback:0, dst:reg12, `x`
- [ b8] Jump target:block5
+ [ a8] JumpFalse condition:reg8, target:block5
block4:
- [ c0] MovSrcUndefined dst:reg13
- [ c8] Jump target:block6
+ [ b8] Mov dst:reg13, src:Undefined
block5:
- [ d0] IteratorNextUnpack dst_value:reg13, dst_done:reg6, iterator_object:reg7, iterator_next:reg8, iterator_done:reg9
- [ e8] JumpTrueLoop condition:reg6, target:block4
+ [ c8] PutById base:reg12, `y`, src:reg13, kind:Normal
block6:
- [ f8] PutById base:reg12, `y`, src:reg13, kind:Normal
+ [ e8] JumpTrue condition:reg11, target:block11
block7:
- [ 118] JumpFalse condition:reg9, target:block9
+ [ f8] IteratorClose iterator_object:reg9, iterator_next:reg10, iterator_done:reg11, completion_value:Undefined
+ [ 118] Jump target:block11
block8:
- [ 128] End value:reg5
+ [ 120] Catch value_feedback:1, dst:reg12
+ [ 128] JumpTrue condition:reg11, target:block10
block9:
- [ 130] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:Undefined
- [ 150] JumpLoop target:block8
+ [ 138] IteratorClose iterator_object:reg9, iterator_next:reg10, iterator_done:reg11, completion_value:reg12
block10:
- [ 158] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg10, rhs:1, true_target:block12, false_target:block13
+ [ 158] Throw src:reg12
block11:
- [ 170] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg10, rhs:2, true_target:block14, false_target:block15
-
-block12:
- [ 188] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:reg11
- [ 1a8] Throw src:reg11
-
-block13:
- [ 1b0] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:Undefined
- [ 1d0] JumpLoop target:block11
-
-block14:
- [ 1d8] Return value:reg11
-
-block15:
- [ 1e0] Throw src:reg11
+ [ 160] Mov dst:reg5, src:reg7
+ [ 170] End value:reg5
Exception handlers:
- [ a8 .. d0] => handler block1
- [ f8 .. 118] => handler block1
+ [ 80 .. 90] => handler block8
+ [ a8 .. e8] => handler block8
diff --git a/Tests/LibJS/Bytecode/expected/destructuring-param-no-param-expressions.txt b/Tests/LibJS/Bytecode/expected/destructuring-param-no-param-expressions.txt
index d1ad050b63f..568a337142c 100644
--- a/Tests/LibJS/Bytecode/expected/destructuring-param-no-param-expressions.txt
+++ b/Tests/LibJS/Bytecode/expected/destructuring-param-no-param-expressions.txt
@@ -1,4 +1,4 @@
-$2e11f366 destructuring-param-no-param-expressions.js:10:1
+$365dc696 destructuring-param-no-param-expressions.js:10:1
Registers: 8
Blocks: 1
Constants:
@@ -8,16 +8,17 @@ $2e11f366 destructuring-param-no-param-expressions.js:10:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] NewObject dst:reg7
- [ 28] InitObjectLiteralProperty object:reg7, `captured`, src:Int32(1), shape_cache_index:0, property_slot:0
- [ 40] InitObjectLiteralProperty object:reg7, `local`, src:Int32(2), shape_cache_index:0, property_slot:1
- [ 58] CacheObjectShape object:reg7
- [ 68] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[reg7]
- [ 90] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] NewObject dst:reg7
+ [ 38] InitObjectLiteralProperty object:reg7, `captured`, src:Int32(1), shape_cache_index:0, property_slot:0
+ [ 50] InitObjectLiteralProperty object:reg7, `local`, src:Int32(2), shape_cache_index:0, property_slot:1
+ [ 68] CacheObjectShape object:reg7
+ [ 78] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ a0] End value:reg5
-f$c0843f91 destructuring-param-no-param-expressions.js:7:5
+f$24ed28b9 destructuring-param-no-param-expressions.js:6:12
Registers: 7
Blocks: 1
Locals: local~0
@@ -29,7 +30,6 @@ block0:
[ 20] Mov dst:reg5, src:arg0
[ 30] GetById value_feedback:0, dst:reg6, base:reg5, `captured`
[ 48] InitializeLexicalBinding `captured`, src:reg6
- [ 60] GetById value_feedback:1, dst:reg6, base:reg5, `local`
- [ 78] Mov dst:local~0, src:reg6
- [ 88] NewFunction dst:reg5, shared_function_data_index:0
- [ a0] Return value:reg5
+ [ 60] GetById value_feedback:1, dst:local~0, base:reg5, `local`
+ [ 78] NewFunction dst:reg5, shared_function_data_index:0
+ [ 90] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/do-while-register-allocation.txt b/Tests/LibJS/Bytecode/expected/do-while-register-allocation.txt
index 814981c56bc..083d488eca7 100644
--- a/Tests/LibJS/Bytecode/expected/do-while-register-allocation.txt
+++ b/Tests/LibJS/Bytecode/expected/do-while-register-allocation.txt
@@ -1,4 +1,4 @@
-$6c6bb70b do-while-register-allocation.js:15:1
+$69a7c5fb do-while-register-allocation.js:15:1
Registers: 7
Blocks: 1
Constants:
@@ -6,13 +6,14 @@ $6c6bb70b do-while-register-allocation.js:15:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `test`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, test
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `test`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-test$62b23a07 do-while-register-allocation.js:9:5
- Registers: 9
+test$dda5d10a do-while-register-allocation.js:8:9
+ Registers: 7
Blocks: 3
Locals: i~0
Constants:
@@ -22,20 +23,20 @@ test$62b23a07 do-while-register-allocation.js:9:5
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:i~0, c0_src:Undefined, c1_dst:i~0, c1_src:Int32(0)
- [ 20] GetGlobal value_feedback:0, dst:reg6, `foo`
- [ 30] NewArray dst:reg7
- [ 40] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, foo, arguments:[reg7]
+ [ 8] Mov dst:i~0, src:Undefined
+ [ 18] Mov dst:i~0, src:Int32(0)
+ [ 28] GetGlobal value_feedback:0, dst:reg5, `foo`
+ [ 38] NewArray dst:reg6
+ [ 48] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg5, this_value:Undefined, arguments:[reg6]
block1:
- [ 68] GetGlobal value_feedback:2, dst:reg7, `bar`
- [ 78] Mov dst:reg8, src:i~0
- [ 88] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, bar, arguments:[reg8]
- [ b0] PostfixIncrement arith_feedback:1, dst:reg6, src:i~0
- [ c0] JumpLessThanLoopRhsInt32 arith_feedback:0, lhs:i~0, rhs:7, true_target:block1, false_target:block2
+ [ 70] GetGlobal value_feedback:2, dst:reg5, `bar`
+ [ 80] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg5, this_value:Undefined, arguments:[i~0]
+ [ a8] Increment arith_feedback:0, dst:i~0
+ [ b0] JumpLessThanLoopRhsInt32 arith_feedback:1, lhs:i~0, rhs:7, true_target:block1, false_target:block2
block2:
- [ d8] End value:Undefined
+ [ c8] End value:Undefined
foo$14c42854 do-while-register-allocation.js:2:5
diff --git a/Tests/LibJS/Bytecode/expected/double-constant-deduplication.txt b/Tests/LibJS/Bytecode/expected/double-constant-deduplication.txt
index f6a94e4b00d..282da579802 100644
--- a/Tests/LibJS/Bytecode/expected/double-constant-deduplication.txt
+++ b/Tests/LibJS/Bytecode/expected/double-constant-deduplication.txt
@@ -1,4 +1,4 @@
-$162ec0dc double-constant-deduplication.js:8:1
+$136acfcc double-constant-deduplication.js:8:1
Registers: 7
Blocks: 1
Constants:
@@ -6,13 +6,14 @@ $162ec0dc double-constant-deduplication.js:8:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `foo`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, foo
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `foo`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-foo$1fd3ec94 double-constant-deduplication.js:2:5
- Registers: 7
+foo$81fdd1a8 double-constant-deduplication.js:2:9
+ Registers: 6
Blocks: 1
Locals: a~0, b~1, c~2
Constants:
@@ -20,7 +21,9 @@ foo$1fd3ec94 double-constant-deduplication.js:2:5
block0:
[ 0] Enter
- [ 8] Mov3 c0_dst:a~0, c0_src:Double(0.5), c1_dst:b~1, c1_src:Double(0.5), c2_dst:c~2, c2_src:Double(0.5)
- [ 28] Add arith_feedback:0, dst:reg5, lhs:a~0, rhs:b~1
- [ 38] Add arith_feedback:1, dst:reg6, lhs:reg5, rhs:c~2
- [ 48] Return value:reg6
+ [ 8] Mov dst:a~0, src:Double(0.5)
+ [ 18] Mov dst:b~1, src:Double(0.5)
+ [ 28] Mov dst:c~2, src:Double(0.5)
+ [ 38] Add arith_feedback:0, dst:reg5, lhs:a~0, rhs:b~1
+ [ 48] Add arith_feedback:1, dst:reg5, lhs:reg5, rhs:c~2
+ [ 58] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/enclosing-function-bindings-with-eval-or-with.txt b/Tests/LibJS/Bytecode/expected/enclosing-function-bindings-with-eval-or-with.txt
index f4630ee2949..1b38cef962c 100644
--- a/Tests/LibJS/Bytecode/expected/enclosing-function-bindings-with-eval-or-with.txt
+++ b/Tests/LibJS/Bytecode/expected/enclosing-function-bindings-with-eval-or-with.txt
@@ -1,4 +1,4 @@
-$6c6bb70b enclosing-function-bindings-with-eval-or-with.js:15:1
+$69a7c5fb enclosing-function-bindings-with-eval-or-with.js:15:1
Registers: 7
Blocks: 1
Constants:
@@ -6,45 +6,44 @@ $6c6bb70b enclosing-function-bindings-with-eval-or-with.js:15:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `outer`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, outer
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `outer`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-outer$58202ed8 enclosing-function-bindings-with-eval-or-with.js:2:5
- Registers: 12
+outer$9d7827c4 enclosing-function-bindings-with-eval-or-with.js:2:9
+ Registers: 11
Blocks: 1
Constants:
- [0] = Undefined
- [1] = Int32(1)
+ [0] = Int32(1)
+ [1] = Undefined
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateVariable `evaluates`, is_immutable:false, is_global:false, is_strict:false
- [ 20] InitializeVariableBinding `evaluates`, src:Undefined
- [ 38] CreateVariable `withObject`, is_immutable:false, is_global:false, is_strict:false
- [ 48] InitializeVariableBinding `withObject`, src:Undefined
- [ 60] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 78] CreateVariable `a`, is_immutable:false, is_global:false, is_strict:false
- [ 88] NewFunction dst:reg6, shared_function_data_index:0
- [ a0] SetVariableBinding `evaluates`, src:reg6
- [ b8] NewFunction dst:reg6, shared_function_data_index:1
- [ d0] SetVariableBinding `withObject`, src:reg6
- [ e8] InitializeLexicalBinding `a`, src:Int32(1)
- [ 100] GetCalleeAndThisFromEnvironment value_feedback:0, callee:reg8, this_value:reg9, `evaluates`
- [ 118] Call value_feedback:1, call_feedback:0, dst:reg7, callee:reg8, this_value:reg9, evaluates
- [ 138] Call value_feedback:2, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined
- [ 158] GetCalleeAndThisFromEnvironment value_feedback:3, callee:reg9, this_value:reg10, `withObject`
- [ 170] NewObject dst:reg11
- [ 180] Call value_feedback:4, call_feedback:2, dst:reg8, callee:reg9, this_value:reg10, withObject, arguments:[reg11]
- [ 1a8] Call value_feedback:5, call_feedback:3, dst:reg7, callee:reg8, this_value:Undefined
- [ 1c8] NewArray dst:reg8, elements:[reg6, reg7]
- [ 1e0] Return value:reg8
+ [ 8] CreateVariable `a`, is_immutable:false, is_global:false, is_strict:false
+ [ 18] CreateVariable `evaluates`, is_immutable:false, is_global:false, is_strict:false
+ [ 28] InitializeVariableBinding `evaluates`, src:Undefined
+ [ 40] NewFunction dst:reg5, shared_function_data_index:0
+ [ 58] SetVariableBinding `evaluates`, src:reg5
+ [ 70] CreateVariable `withObject`, is_immutable:false, is_global:false, is_strict:false
+ [ 80] InitializeVariableBinding `withObject`, src:Undefined
+ [ 98] NewFunction dst:reg6, shared_function_data_index:1
+ [ b0] SetVariableBinding `withObject`, src:reg6
+ [ c8] InitializeLexicalBinding `a`, src:Int32(1)
+ [ e0] GetCalleeAndThisFromEnvironment value_feedback:0, callee:reg7, this_value:reg8, `evaluates`
+ [ f8] Call value_feedback:1, call_feedback:0, dst:reg7, callee:reg7, this_value:reg8
+ [ 118] Call value_feedback:2, call_feedback:1, dst:reg7, callee:reg7, this_value:Undefined
+ [ 138] GetCalleeAndThisFromEnvironment value_feedback:3, callee:reg8, this_value:reg9, `withObject`
+ [ 150] NewObject dst:reg10
+ [ 160] Call value_feedback:4, call_feedback:2, dst:reg8, callee:reg8, this_value:reg9, arguments:[reg10]
+ [ 188] Call value_feedback:5, call_feedback:3, dst:reg8, callee:reg8, this_value:Undefined
+ [ 1a8] NewArray dst:reg9, elements:[reg7, reg8]
+ [ 1c0] Return value:reg9
evaluates$c9a2fbb4 enclosing-function-bindings-with-eval-or-with.js:4:13
- Registers: 8
+ Registers: 7
Blocks: 1
Constants:
[0] = String("")
@@ -52,21 +51,22 @@ evaluates$c9a2fbb4 enclosing-function-bindings-with-eval-or-with.js:4:13
block0:
[ 0] Enter
[ 8] CreateArguments is_immutable:false, creates_parameter_bindings:false
- [ 18] DynamicGetCalleeAndThisFromEnvironment value_feedback:0, callee:reg6, this_value:reg7, `eval`
- [ 30] CallDirectEval value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:reg7, eval, arguments:[String("")]
+ [ 18] DynamicGetCalleeAndThisFromEnvironment value_feedback:0, callee:reg5, this_value:reg6, `eval`
+ [ 30] CallDirectEval value_feedback:1, call_feedback:0, dst:reg5, callee:reg5, this_value:reg6, arguments:[String("")]
[ 58] NewFunction dst:reg5, shared_function_data_index:0
[ 70] Return value:reg5
-eval$3b472b8b
- Registers: 5
+eval$3e0b1c9b
+ Registers: 6
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] End value:reg5
$9c1c05f0 enclosing-function-bindings-with-eval-or-with.js:5:16
@@ -82,8 +82,6 @@ block0:
withObject$c7af78eb enclosing-function-bindings-with-eval-or-with.js:8:9
Registers: 7
Blocks: 1
- Constants:
- [0] = Undefined
block0:
[ 0] Enter
diff --git a/Tests/LibJS/Bytecode/expected/enclosing-function-bindings.txt b/Tests/LibJS/Bytecode/expected/enclosing-function-bindings.txt
index 1d2a912163a..e60b4d6b043 100644
--- a/Tests/LibJS/Bytecode/expected/enclosing-function-bindings.txt
+++ b/Tests/LibJS/Bytecode/expected/enclosing-function-bindings.txt
@@ -1,24 +1,26 @@
-$718e5550 enclosing-function-bindings.js:28:1
- Registers: 9
+$f5bf1d5d enclosing-function-bindings.js:1:1
+ Registers: 7
Blocks: 1
Constants:
- [0] = String("use strict")
- [1] = Undefined
+ [0] = Undefined
+ [1] = String("use strict")
[2] = Int32(1)
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg8, `outer`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg7, callee:reg8, this_value:Undefined, outer, arguments:[Int32(1)]
- [ 40] Call value_feedback:2, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined
- [ 60] Call value_feedback:3, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined
- [ 80] GetGlobal value_feedback:4, dst:reg7, `blockFunctions`
- [ 90] Call value_feedback:5, call_feedback:3, dst:reg6, callee:reg7, this_value:Undefined, blockFunctions
- [ b0] End value:reg6
-
-
-outer$4a68a085 enclosing-function-bindings.js:4:5
- Registers: 6
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:String("use strict")
+ [ 28] GetGlobal value_feedback:0, dst:reg6, `outer`
+ [ 38] Call value_feedback:1, call_feedback:0, dst:reg6, callee:reg6, this_value:Undefined, arguments:[Int32(1)]
+ [ 60] Call value_feedback:2, call_feedback:1, dst:reg6, callee:reg6, this_value:Undefined
+ [ 80] Call value_feedback:3, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined
+ [ a0] GetGlobal value_feedback:4, dst:reg6, `blockFunctions`
+ [ b0] Call value_feedback:5, call_feedback:3, dst:reg5, callee:reg6, this_value:Undefined
+ [ d0] End value:reg5
+
+
+outer$2efab589 enclosing-function-bindings.js:4:9
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
@@ -27,15 +29,15 @@ block0:
[ 0] Enter
[ 8] CreateVariable `a`, is_immutable:false, is_global:false, is_strict:false
[ 18] InitializeLexicalBinding `a`, src:arg0
- [ 30] CreateVariable `callee`, is_immutable:false, is_global:false, is_strict:false
- [ 40] InitializeVariableBinding `callee`, src:Undefined
- [ 58] CreateVariable `b`, is_immutable:false, is_global:false, is_strict:false
+ [ 30] CreateVariable `b`, is_immutable:false, is_global:false, is_strict:false
+ [ 40] CreateVariable `callee`, is_immutable:false, is_global:false, is_strict:false
+ [ 50] InitializeVariableBinding `callee`, src:Undefined
[ 68] NewFunction dst:reg5, shared_function_data_index:0
[ 80] SetVariableBinding `callee`, src:reg5
[ 98] GetBinding value_feedback:0, dst:reg5, `a`
[ b0] InitializeLexicalBinding `b`, src:reg5
- [ c8] NewFunction dst:reg5, shared_function_data_index:1
- [ e0] Return value:reg5
+ [ c8] NewFunction dst:reg6, shared_function_data_index:1
+ [ e0] Return value:reg6
$99e98519 enclosing-function-bindings.js:8:12
@@ -49,7 +51,7 @@ block0:
inner$0df4d11e enclosing-function-bindings.js:10:15
- Registers: 9
+ Registers: 8
Blocks: 1
block0:
@@ -57,10 +59,10 @@ block0:
[ 8] GetBinding value_feedback:0, dst:reg5, `b`
[ 20] SetLexicalBinding `a`, src:reg5
[ 38] TypeofBinding dst:reg5, `a`
- [ 50] GetCalleeAndThisFromEnvironment value_feedback:1, callee:reg7, this_value:reg8, `callee`
- [ 68] Call value_feedback:2, call_feedback:0, dst:reg6, callee:reg7, this_value:reg8, callee
- [ 88] Add arith_feedback:0, dst:reg7, lhs:reg5, rhs:reg6
- [ 98] Return value:reg7
+ [ 50] GetCalleeAndThisFromEnvironment value_feedback:1, callee:reg6, this_value:reg7, `callee`
+ [ 68] Call value_feedback:2, call_feedback:0, dst:reg6, callee:reg6, this_value:reg7
+ [ 88] Add arith_feedback:0, dst:reg5, lhs:reg5, rhs:reg6
+ [ 98] Return value:reg5
callee$c2393260 enclosing-function-bindings.js:6:9
@@ -73,7 +75,7 @@ block0:
[ 20] Return value:reg5
-blockFunctions$c1ad0618 enclosing-function-bindings.js:16:5
+blockFunctions$385d0424 enclosing-function-bindings.js:16:9
Registers: 7
Blocks: 1
Locals: first~0
@@ -83,27 +85,26 @@ blockFunctions$c1ad0618 enclosing-function-bindings.js:16:5
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateVariable `c`, is_immutable:false, is_global:false, is_strict:false
+ [ 8] CreateVariable `c`, is_immutable:false, is_global:false, is_strict:false
+ [ 18] GetLexicalEnvironment dst:reg4
[ 20] InitializeLexicalBinding `c`, src:Int32(1)
[ 38] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 50] CreateMutableBinding environment:reg5, `second`, can_be_deleted:false
- [ 60] NewFunction dst:reg6, shared_function_data_index:0
- [ 78] Mov dst:first~0, src:reg6
- [ 88] NewFunction dst:reg6, shared_function_data_index:1
- [ a0] InitializeLexicalBinding `second`, src:reg6
- [ b8] Call value_feedback:0, call_feedback:0, dst:reg6, callee:first~0, this_value:Undefined, first
- [ d8] SetLexicalEnvironment environment:reg4
- [ e0] Return value:reg6
+ [ 50] CreateVariable `second`, is_immutable:false, is_global:false, is_strict:false
+ [ 60] NewFunction dst:first~0, shared_function_data_index:0
+ [ 78] NewFunction dst:reg6, shared_function_data_index:1
+ [ 90] InitializeLexicalBinding `second`, src:reg6
+ [ a8] Call value_feedback:0, call_feedback:0, dst:reg6, callee:first~0, this_value:Undefined
+ [ c8] SetLexicalEnvironment environment:reg4
+ [ d0] Return value:reg6
first$ff0e9329 enclosing-function-bindings.js:19:13
- Registers: 8
+ Registers: 7
Blocks: 1
block0:
[ 0] Enter
[ 8] GetBinding value_feedback:0, dst:reg5, `c`
[ 20] TypeofBinding dst:reg6, `second`
- [ 38] Add arith_feedback:0, dst:reg7, lhs:reg5, rhs:reg6
- [ 48] Return value:reg7
+ [ 38] Add arith_feedback:0, dst:reg5, lhs:reg5, rhs:reg6
+ [ 48] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/eval-prevents-locals.txt b/Tests/LibJS/Bytecode/expected/eval-prevents-locals.txt
index 45a3119e777..3f0d7521e38 100644
--- a/Tests/LibJS/Bytecode/expected/eval-prevents-locals.txt
+++ b/Tests/LibJS/Bytecode/expected/eval-prevents-locals.txt
@@ -1,20 +1,21 @@
-$1ed4f972 eval-prevents-locals.js:22:1
- Registers: 8
+$2ca8aec2 eval-prevents-locals.js:22:1
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `with_eval`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, with_eval
- [ 38] GetGlobal value_feedback:2, dst:reg7, `outer_eval`
- [ 48] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, outer_eval
- [ 68] End value:reg6
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `with_eval`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] GetGlobal value_feedback:2, dst:reg6, `outer_eval`
+ [ 58] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined
+ [ 78] End value:reg5
-with_eval$43ef143d eval-prevents-locals.js:6:5
- Registers: 9
+with_eval$cd3f1631 eval-prevents-locals.js:6:9
+ Registers: 8
Blocks: 1
Constants:
[0] = Int32(1)
@@ -22,61 +23,65 @@ with_eval$43ef143d eval-prevents-locals.js:6:5
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateArguments is_immutable:false, creates_parameter_bindings:false
+ [ 8] CreateArguments is_immutable:false, creates_parameter_bindings:false
+ [ 18] GetLexicalEnvironment dst:reg4
[ 20] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
[ 38] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
[ 48] InitializeLexicalBinding `x`, src:Int32(1)
- [ 60] DynamicGetCalleeAndThisFromEnvironment value_feedback:0, callee:reg7, this_value:reg8, `eval`
- [ 78] CallDirectEval value_feedback:1, call_feedback:0, dst:reg6, callee:reg7, this_value:reg8, eval, arguments:[String("")]
+ [ 60] DynamicGetCalleeAndThisFromEnvironment value_feedback:0, callee:reg6, this_value:reg7, `eval`
+ [ 78] CallDirectEval value_feedback:1, call_feedback:0, dst:reg6, callee:reg6, this_value:reg7, arguments:[String("")]
[ a0] GetBinding value_feedback:2, dst:reg6, `x`
[ b8] Return value:reg6
-eval$3b472b8b
- Registers: 5
+eval$3e0b1c9b
+ Registers: 6
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] End value:reg5
-outer_eval$e35f2ce2 eval-prevents-locals.js:14:9
- Registers: 8
+outer_eval$069e758d eval-prevents-locals.js:14:9
+ Registers: 9
Blocks: 1
Constants:
- [0] = Undefined
- [1] = String("")
+ [0] = String("")
+ [1] = Undefined
block0:
[ 0] Enter
[ 8] CreateArguments is_immutable:false, creates_parameter_bindings:false
- [ 18] CreateVariable `inner`, is_immutable:false, is_global:false, is_strict:false
- [ 28] InitializeVariableBinding `inner`, src:Undefined
- [ 40] NewFunction dst:reg5, shared_function_data_index:0
- [ 58] SetVariableBinding `inner`, src:reg5
- [ 70] DynamicGetCalleeAndThisFromEnvironment value_feedback:0, callee:reg6, this_value:reg7, `eval`
- [ 88] CallDirectEval value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:reg7, eval, arguments:[String("")]
- [ b0] GetCalleeAndThisFromEnvironment value_feedback:2, callee:reg6, this_value:reg7, `inner`
- [ c8] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:reg7, inner
- [ e8] Return value:reg5
-
-
-eval$3b472b8b
- Registers: 5
+ [ 18] GetLexicalEnvironment dst:reg4
+ [ 20] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `inner`, is_immutable:false, is_global:false, is_strict:false
+ [ 48] InitializeVariableBinding `inner`, src:Undefined
+ [ 60] NewFunction dst:reg6, shared_function_data_index:0
+ [ 78] SetVariableBinding `inner`, src:reg6
+ [ 90] DynamicGetCalleeAndThisFromEnvironment value_feedback:0, callee:reg6, this_value:reg7, `eval`
+ [ a8] CallDirectEval value_feedback:1, call_feedback:0, dst:reg6, callee:reg6, this_value:reg7, arguments:[String("")]
+ [ d0] GetCalleeAndThisFromEnvironment value_feedback:2, callee:reg7, this_value:reg8, `inner`
+ [ e8] Call value_feedback:3, call_feedback:1, dst:reg7, callee:reg7, this_value:reg8
+ [ 108] Return value:reg7
+
+
+eval$3e0b1c9b
+ Registers: 6
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] End value:reg5
-inner$99f991c2 eval-prevents-locals.js:16:9
+inner$0f7f0e46 eval-prevents-locals.js:16:13
Registers: 5
Blocks: 1
Locals: y~0
diff --git a/Tests/LibJS/Bytecode/expected/eval-same-function.txt b/Tests/LibJS/Bytecode/expected/eval-same-function.txt
index 67335ea3ee0..a2c0cf7477b 100644
--- a/Tests/LibJS/Bytecode/expected/eval-same-function.txt
+++ b/Tests/LibJS/Bytecode/expected/eval-same-function.txt
@@ -1,4 +1,4 @@
-$d36729be eval-same-function.js:10:1
+$d0a338ae eval-same-function.js:10:1
Registers: 7
Blocks: 1
Constants:
@@ -6,38 +6,39 @@ $d36729be eval-same-function.js:10:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `foo`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, foo
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `foo`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
foo$40f9e494 eval-same-function.js:6:9
- Registers: 8
+ Registers: 7
Blocks: 1
Constants:
[0] = String("var x = 1")
- [1] = Undefined
- [2] = Int32(42)
+ [1] = Int32(42)
block0:
[ 0] Enter
[ 8] CreateArguments is_immutable:false, creates_parameter_bindings:false
- [ 18] DynamicGetCalleeAndThisFromEnvironment value_feedback:0, callee:reg6, this_value:reg7, `eval`
- [ 30] CallDirectEval value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:reg7, eval, arguments:[String("var x = 1")]
- [ 58] DynamicGetBinding value_feedback:2, dst:reg6, `Number`
- [ 68] CallConstruct value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, Number, arguments:[Int32(42)]
+ [ 18] DynamicGetCalleeAndThisFromEnvironment value_feedback:0, callee:reg5, this_value:reg6, `eval`
+ [ 30] CallDirectEval value_feedback:1, call_feedback:0, dst:reg5, callee:reg5, this_value:reg6, arguments:[String("var x = 1")]
+ [ 58] DynamicGetBinding value_feedback:2, dst:reg5, `Number`
+ [ 68] CallConstruct value_feedback:3, call_feedback:1, dst:reg5, callee:reg5, arguments:[Int32(42)]
[ 90] Return value:reg5
-eval$5fd20edb line 1, column 1
- Registers: 6
+eval$c783d60f line 1, column 5
+ Registers: 7
Blocks: 1
Constants:
- [0] = Int32(1)
- [1] = Undefined
+ [0] = Undefined
+ [1] = Int32(1)
block0:
[ 0] Enter
- [ 8] ResolveBinding dst:reg5, `x`
- [ 18] SetResolvedBinding environment:reg5, `x`, src:Int32(1)
- [ 28] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] ResolveBinding dst:reg6, `x`
+ [ 28] SetResolvedBinding environment:reg6, `x`, src:Int32(1)
+ [ 38] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/eval-scope-optimization.txt b/Tests/LibJS/Bytecode/expected/eval-scope-optimization.txt
index 2245140b0c3..248d01ebfa7 100644
--- a/Tests/LibJS/Bytecode/expected/eval-scope-optimization.txt
+++ b/Tests/LibJS/Bytecode/expected/eval-scope-optimization.txt
@@ -1,4 +1,4 @@
-$c7fd0018 eval-scope-optimization.js:12:1
+$c5390f08 eval-scope-optimization.js:12:1
Registers: 7
Blocks: 1
Constants:
@@ -6,12 +6,13 @@ $c7fd0018 eval-scope-optimization.js:12:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `outer`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, outer
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `outer`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-outer$b6675570 eval-scope-optimization.js:9:5
+outer$aa324eaf eval-scope-optimization.js:6:5
Registers: 7
Blocks: 1
Constants:
@@ -25,5 +26,5 @@ block0:
[ 30] NewFunction dst:reg5, shared_function_data_index:0
[ 48] SetVariableBinding `inner`, src:reg5
[ 60] GetGlobal value_feedback:0, dst:reg6, `Number`
- [ 70] CallConstruct value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, Number, arguments:[Int32(42)]
- [ 98] Return value:reg5
+ [ 70] CallConstruct value_feedback:1, call_feedback:0, dst:reg6, callee:reg6, arguments:[Int32(42)]
+ [ 98] Return value:reg6
diff --git a/Tests/LibJS/Bytecode/expected/expression-identifier-number-format.txt b/Tests/LibJS/Bytecode/expected/expression-identifier-number-format.txt
index 922a0696b52..012de03353d 100644
--- a/Tests/LibJS/Bytecode/expected/expression-identifier-number-format.txt
+++ b/Tests/LibJS/Bytecode/expected/expression-identifier-number-format.txt
@@ -1,18 +1,22 @@
-$772115e5 expression-identifier-number-format.js:1:1
+$1a7f12f1 expression-identifier-number-format.js:1:5
Registers: 8
Blocks: 1
Constants:
- [0] = Double(1.1e-32)
- [1] = Int32(42)
+ [0] = Undefined
+ [1] = Double(1.1e-32)
+ [2] = Int32(42)
block0:
[ 0] Enter
- [ 8] NewObject dst:reg5
- [ 18] SetGlobal `x`, src:reg5
- [ 28] GetGlobal value_feedback:0, dst:reg5, `x`
- [ 38] NewObject dst:reg6
- [ 48] PutByValue keyed_feedback:0, base:reg5, property:Double(1.1e-32), src:reg6, kind:Normal (x[Double(1.1e-32)])
- [ 68] GetGlobal value_feedback:1, dst:reg5, `x`
- [ 78] GetByValue value_feedback:2, keyed_feedback:1, dst:reg7, base:reg5, property:Double(1.1e-32) (x[Double(1.1e-32)])
- [ 98] PutById base:reg7, `foo`, src:Int32(42), kind:Normal (x[1.1e-32].foo)
- [ b8] End value:Int32(42)
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] NewObject dst:reg6
+ [ 28] SetGlobal `x`, src:reg6
+ [ 38] GetGlobal value_feedback:0, dst:reg6, `x`
+ [ 48] NewObject dst:reg7
+ [ 58] PutByValue keyed_feedback:0, base:reg6, property:Double(1.1e-32), src:reg7, kind:Normal
+ [ 78] Mov dst:reg5, src:reg7
+ [ 88] GetGlobal value_feedback:1, dst:reg6, `x`
+ [ 98] GetByValue value_feedback:2, keyed_feedback:1, dst:reg6, base:reg6, property:Double(1.1e-32)
+ [ b8] PutById base:reg6, `foo`, src:Int32(42), kind:Normal
+ [ d8] Mov dst:reg5, src:Int32(42)
+ [ e8] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/for-in-block-order.txt b/Tests/LibJS/Bytecode/expected/for-in-block-order.txt
index d283301d6ab..adac435003f 100644
--- a/Tests/LibJS/Bytecode/expected/for-in-block-order.txt
+++ b/Tests/LibJS/Bytecode/expected/for-in-block-order.txt
@@ -1,4 +1,4 @@
-$916dd419 for-in-block-order.js:5:1
+$99b9a749 for-in-block-order.js:5:1
Registers: 8
Blocks: 1
Constants:
@@ -6,15 +6,16 @@ $916dd419 for-in-block-order.js:5:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `foo`
- [ 18] NewObject dst:reg7
- [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, foo, arguments:[reg7]
- [ 50] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `foo`
+ [ 28] NewObject dst:reg7
+ [ 38] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 60] End value:reg5
-foo$b44aa151 for-in-block-order.js:2:16
- Registers: 10
- Blocks: 6
+foo$7825ea87 for-in-block-order.js:2:14
+ Registers: 11
+ Blocks: 5
Locals: k~0
Constants:
[0] = Undefined
@@ -22,24 +23,21 @@ foo$b44aa151 for-in-block-order.js:2:16
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:k~0
- [ 10] JumpNullish condition:arg0, true_target:block3, false_target:block4
+ [ 8] Mov dst:k~0, src:Undefined
+ [ 18] Mov dst:reg5, src:arg0
+ [ 28] JumpNullish condition:reg5, true_target:block4, false_target:block1
block1:
- [ 20] End value:Undefined
+ [ 38] GetObjectPropertyIterator dst_keys:reg7, dst_receiver:reg6, object:reg5
+ [ 50] Mov dst:reg8, src:Int32(0)
block2:
- [ 28] ObjectPropertyIteratorNext dst_value:reg8, dst_done:reg9, receiver:reg5, keys:reg6, cursor:reg7
- [ 40] JumpIfLoop condition:reg9, true_target:block1, false_target:block5
+ [ 60] ObjectPropertyIteratorNext dst_value:reg9, dst_done:reg10, receiver:reg6, keys:reg7, cursor:reg8
+ [ 78] JumpTrue condition:reg10, target:block4
block3:
- [ 50] JumpLoop target:block1
+ [ 88] Mov dst:k~0, src:reg9
+ [ 98] JumpLoop target:block2
block4:
- [ 58] GetObjectPropertyIterator dst_keys:reg6, dst_receiver:reg5, object:arg0
- [ 70] Mov dst:reg7, src:Int32(0)
- [ 80] JumpLoop target:block2
-
-block5:
- [ 88] Mov dst:k~0, src:reg8
- [ 98] JumpLoop target:block2
+ [ a0] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/for-in-lexical-scope.txt b/Tests/LibJS/Bytecode/expected/for-in-lexical-scope.txt
index 5fb5b08aa8d..6afd31ec867 100644
--- a/Tests/LibJS/Bytecode/expected/for-in-lexical-scope.txt
+++ b/Tests/LibJS/Bytecode/expected/for-in-lexical-scope.txt
@@ -1,47 +1,41 @@
-$bad04f23 for-in-lexical-scope.js:1:12
- Registers: 15
- Blocks: 6
+$4f26a2de for-in-lexical-scope.js:1:5
+ Registers: 13
+ Blocks: 5
+ Locals: probeDecl~0
Constants:
- [0] = Int32(0)
- [1] = Undefined
+ [0] = Undefined
+ [1] = Int32(0)
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
- [ 38] NewObject dst:reg6
- [ 48] InitObjectLiteralProperty object:reg6, `i`, src:Int32(0), shape_cache_index:0, property_slot:0
- [ 60] CacheObjectShape object:reg6
- [ 70] SetLexicalEnvironment environment:reg4
- [ 78] MovSrcUndefined dst:reg9
- [ 80] JumpNullish condition:reg6, true_target:block3, false_target:block4
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
+ [ 48] NewObject dst:reg8
+ [ 58] InitObjectLiteralProperty object:reg8, `i`, src:Int32(0), shape_cache_index:0, property_slot:0
+ [ 70] CacheObjectShape object:reg8
+ [ 80] Mov dst:reg6, src:reg8
+ [ 90] SetLexicalEnvironment environment:reg4
+ [ 98] Mov dst:reg5, src:Undefined
+ [ a8] JumpNullish condition:reg6, true_target:block4, false_target:block1
block1:
- [ 90] End value:reg9
+ [ b8] GetObjectPropertyIterator dst_keys:reg8, dst_receiver:reg7, object:reg6
+ [ d0] Mov dst:reg9, src:Int32(0)
block2:
- [ 98] ObjectPropertyIteratorNext dst_value:reg10, dst_done:reg11, receiver:reg5, keys:reg7, cursor:reg8
- [ b0] JumpIfLoop condition:reg11, true_target:block1, false_target:block5
+ [ e0] ObjectPropertyIteratorNext dst_value:reg10, dst_done:reg11, receiver:reg7, keys:reg8, cursor:reg9
+ [ f8] JumpTrue condition:reg11, target:block4
block3:
- [ c0] End value:reg9
+ [ 108] CreateLexicalEnvironment dst:reg12, parent:reg4, capacity:1, is_catch_environment:false
+ [ 120] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
+ [ 130] InitializeLexicalBinding `x`, src:reg10
+ [ 148] NewFunction dst:probeDecl~0, shared_function_data_index:0
+ [ 160] DynamicSetVariableBinding `probeDecl`, src:probeDecl~0
+ [ 170] SetLexicalEnvironment environment:reg4
+ [ 178] JumpLoop target:block2
block4:
- [ c8] GetObjectPropertyIterator dst_keys:reg7, dst_receiver:reg5, object:reg6
- [ e0] Mov dst:reg8, src:Int32(0)
- [ f0] JumpLoop target:block2
-
-block5:
- [ f8] CreateLexicalEnvironment dst:reg12, parent:reg4, capacity:1, is_catch_environment:false
- [ 110] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
- [ 120] InitializeLexicalBinding `x`, src:reg10
- [ 138] CreateLexicalEnvironment dst:reg13, parent:reg12, capacity:1, is_catch_environment:false
- [ 150] CreateMutableBinding environment:reg13, `probeDecl`, can_be_deleted:false
- [ 160] NewFunction dst:reg14, shared_function_data_index:0
- [ 178] InitializeLexicalBinding `probeDecl`, src:reg14
- [ 190] GetBinding value_feedback:0, dst:reg14, `probeDecl`
- [ 1a8] DynamicSetVariableBinding `probeDecl`, src:reg14
- [ 1b8] SetLexicalEnvironment environment:reg12
- [ 1c0] SetLexicalEnvironment environment:reg4
- [ 1c8] JumpLoop target:block2
+ [ 180] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/for-in-nullish-completion.txt b/Tests/LibJS/Bytecode/expected/for-in-nullish-completion.txt
index cd18c29dc9f..ad85754f293 100644
--- a/Tests/LibJS/Bytecode/expected/for-in-nullish-completion.txt
+++ b/Tests/LibJS/Bytecode/expected/for-in-nullish-completion.txt
@@ -1,32 +1,31 @@
-$107700ec for-in-nullish-completion.js:5:12
- Registers: 11
- Blocks: 6
+$96dbee98 for-in-nullish-completion.js:4:1
+ Registers: 12
+ Blocks: 5
Constants:
- [0] = Int32(1)
- [1] = Null
- [2] = Undefined
+ [0] = Undefined
+ [1] = Int32(1)
+ [2] = Null
[3] = Int32(0)
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:reg8
- [ 10] JumpNullish condition:Null, true_target:block3, false_target:block4
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:Int32(1)
+ [ 28] Mov dst:reg6, src:Null
+ [ 38] Mov dst:reg5, src:Undefined
+ [ 48] JumpNullish condition:reg6, true_target:block4, false_target:block1
block1:
- [ 20] End value:reg8
+ [ 58] GetObjectPropertyIterator dst_keys:reg8, dst_receiver:reg7, object:reg6
+ [ 70] Mov dst:reg9, src:Int32(0)
block2:
- [ 28] ObjectPropertyIteratorNext dst_value:reg9, dst_done:reg10, receiver:reg5, keys:reg6, cursor:reg7
- [ 40] JumpIfLoop condition:reg10, true_target:block1, false_target:block5
+ [ 80] ObjectPropertyIteratorNext dst_value:reg10, dst_done:reg11, receiver:reg7, keys:reg8, cursor:reg9
+ [ 98] JumpTrue condition:reg11, target:block4
block3:
- [ 50] End value:reg8
+ [ a8] SetGlobal `a`, src:reg10
+ [ b8] JumpLoop target:block2
block4:
- [ 58] GetObjectPropertyIterator dst_keys:reg6, dst_receiver:reg5, object:Null
- [ 70] Mov dst:reg7, src:Int32(0)
- [ 80] JumpLoop target:block2
-
-block5:
- [ 88] SetGlobal `a`, src:reg9
- [ 98] JumpLoop target:block2
+ [ c0] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/for-in-object-property-iterator-next.txt b/Tests/LibJS/Bytecode/expected/for-in-object-property-iterator-next.txt
index 78234480088..f8fa958b03b 100644
--- a/Tests/LibJS/Bytecode/expected/for-in-object-property-iterator-next.txt
+++ b/Tests/LibJS/Bytecode/expected/for-in-object-property-iterator-next.txt
@@ -1,55 +1,54 @@
-$b8c00624 for-in-object-property-iterator-next.js:8:1
+$aaec50d4 for-in-object-property-iterator-next.js:8:1
Registers: 8
Blocks: 1
Constants:
[0] = Undefined
- [1] = Int32(2)
- [2] = String("two")
+ [1] = String("two")
+ [2] = Int32(2)
[3] = String("foo")
- [4] = Int32(7)
- [5] = String("seven")
+ [4] = String("seven")
+ [5] = Int32(7)
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `collect`
- [ 18] NewObject dst:reg7
- [ 28] PutByValue keyed_feedback:0, base:reg7, property:Int32(2), src:String("two"), kind:Own
- [ 48] PutById base:reg7, `foo`, src:String("foo"), kind:Own
- [ 68] PutByValue keyed_feedback:1, base:reg7, property:Int32(7), src:String("seven"), kind:Own
- [ 88] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, collect, arguments:[reg7]
- [ b0] End value:reg5
-
-
-collect$d9304438 for-in-object-property-iterator-next.js:2:18
- Registers: 14
- Blocks: 6
- Locals: key~0, keys~1
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `collect`
+ [ 28] NewObject dst:reg7
+ [ 38] PutByValue keyed_feedback:0, base:reg7, property:Int32(2), src:String("two"), kind:Own
+ [ 58] PutById base:reg7, `foo`, src:String("foo"), kind:Own
+ [ 78] PutByValue keyed_feedback:1, base:reg7, property:Int32(7), src:String("seven"), kind:Own
+ [ 98] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ c0] End value:reg5
+
+
+collect$a74ca55b for-in-object-property-iterator-next.js:2:18
+ Registers: 12
+ Blocks: 5
+ Locals: keys~0, key~1
Constants:
- [0] = Int32(0)
+ [0] = <Empty>
+ [1] = Int32(0)
block0:
[ 0] Enter
- [ 8] NewArray dst:keys~1
- [ 18] JumpNullish condition:arg0, true_target:block3, false_target:block4
+ [ 8] NewArray dst:keys~0
+ [ 18] Mov dst:key~1, src:<Empty>
+ [ 28] Mov dst:reg5, src:arg0
+ [ 38] JumpNullish condition:reg5, true_target:block4, false_target:block1
block1:
- [ 28] Return value:keys~1
+ [ 48] GetObjectPropertyIterator dst_keys:reg7, dst_receiver:reg6, object:reg5
+ [ 60] Mov dst:reg8, src:Int32(0)
block2:
- [ 30] ObjectPropertyIteratorNext dst_value:reg8, dst_done:reg9, receiver:reg5, keys:reg6, cursor:reg7
- [ 48] JumpIfLoop condition:reg9, true_target:block1, false_target:block5
+ [ 70] ObjectPropertyIteratorNext dst_value:reg9, dst_done:reg10, receiver:reg6, keys:reg7, cursor:reg8
+ [ 88] JumpTrue condition:reg10, target:block4
block3:
- [ 58] Return value:keys~1
+ [ 98] Mov dst:key~1, src:reg9
+ [ a8] GetById value_feedback:0, dst:reg11, base:keys~0, `push`
+ [ c0] Call value_feedback:1, call_feedback:0, dst:reg11, callee:reg11, this_value:keys~0, arguments:[key~1]
+ [ e8] JumpLoop target:block2
block4:
- [ 60] GetObjectPropertyIterator dst_keys:reg6, dst_receiver:reg5, object:arg0
- [ 78] Mov dst:reg7, src:Int32(0)
- [ 88] JumpLoop target:block2
-
-block5:
- [ 90] Mov dst:key~0, src:reg8
- [ a0] GetById value_feedback:0, dst:reg11, base:keys~1, `push` (keys.push)
- [ b8] Mov2 c0_dst:reg12, c0_src:keys~1, c1_dst:reg13, c1_src:key~0
- [ d0] Call value_feedback:1, call_feedback:0, dst:reg10, callee:reg11, this_value:reg12, keys.push, arguments:[reg13]
- [ f8] JumpLoop target:block2
+ [ f0] Return value:keys~0
diff --git a/Tests/LibJS/Bytecode/expected/for-in-of-lhs-patterns.txt b/Tests/LibJS/Bytecode/expected/for-in-of-lhs-patterns.txt
index 7b4f264dff6..f465cf97aaa 100644
--- a/Tests/LibJS/Bytecode/expected/for-in-of-lhs-patterns.txt
+++ b/Tests/LibJS/Bytecode/expected/for-in-of-lhs-patterns.txt
@@ -1,9 +1,10 @@
-$4e59e625
- Registers: 5
+$511dd735
+ Registers: 6
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/for-in-register-lifetime.txt b/Tests/LibJS/Bytecode/expected/for-in-register-lifetime.txt
index 2fb2c335b21..18740b82da1 100644
--- a/Tests/LibJS/Bytecode/expected/for-in-register-lifetime.txt
+++ b/Tests/LibJS/Bytecode/expected/for-in-register-lifetime.txt
@@ -1,51 +1,48 @@
-$b6d86a12 for-in-register-lifetime.js:1:1
- Registers: 17
- Blocks: 6
+$de5c50b6 for-in-register-lifetime.js:1:5
+ Registers: 16
+ Blocks: 5
Constants:
- [0] = String("")
- [1] = Int32(1)
- [2] = Int32(2)
- [3] = Int32(3)
- [4] = Undefined
+ [0] = Undefined
+ [1] = String("")
+ [2] = Int32(1)
+ [3] = Int32(2)
+ [4] = Int32(3)
[5] = Int32(0)
block0:
[ 0] Enter
- [ 8] SetGlobal `result`, src:String("")
- [ 18] NewObject dst:reg5
- [ 28] InitObjectLiteralProperty object:reg5, `a`, src:Int32(1), shape_cache_index:0, property_slot:0
- [ 40] InitObjectLiteralProperty object:reg5, `b`, src:Int32(2), shape_cache_index:0, property_slot:1
- [ 58] InitObjectLiteralProperty object:reg5, `c`, src:Int32(3), shape_cache_index:0, property_slot:2
- [ 70] CacheObjectShape object:reg5
- [ 80] SetGlobal `obj`, src:reg5
- [ 90] GetGlobal value_feedback:0, dst:reg5, `obj`
- [ a0] MovSrcUndefined dst:reg9
- [ a8] JumpNullish condition:reg5, true_target:block3, false_target:block4
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] SetGlobal `result`, src:String("")
+ [ 28] NewObject dst:reg6
+ [ 38] InitObjectLiteralProperty object:reg6, `a`, src:Int32(1), shape_cache_index:0, property_slot:0
+ [ 50] InitObjectLiteralProperty object:reg6, `b`, src:Int32(2), shape_cache_index:0, property_slot:1
+ [ 68] InitObjectLiteralProperty object:reg6, `c`, src:Int32(3), shape_cache_index:0, property_slot:2
+ [ 80] CacheObjectShape object:reg6
+ [ 90] SetGlobal `obj`, src:reg6
+ [ a0] GetGlobal value_feedback:0, dst:reg6, `obj`
+ [ b0] Mov dst:reg5, src:Undefined
+ [ c0] JumpNullish condition:reg6, true_target:block4, false_target:block1
block1:
- [ b8] End value:reg9
+ [ d0] GetObjectPropertyIterator dst_keys:reg8, dst_receiver:reg7, object:reg6
+ [ e8] Mov dst:reg9, src:Int32(0)
block2:
- [ c0] ObjectPropertyIteratorNext dst_value:reg10, dst_done:reg11, receiver:reg6, keys:reg7, cursor:reg8
- [ d8] JumpIfLoop condition:reg11, true_target:block1, false_target:block5
+ [ f8] ObjectPropertyIteratorNext dst_value:reg10, dst_done:reg11, receiver:reg7, keys:reg8, cursor:reg9
+ [ 110] JumpTrue condition:reg11, target:block4
block3:
- [ e8] End value:reg9
-
-block4:
- [ f0] GetObjectPropertyIterator dst_keys:reg7, dst_receiver:reg6, object:reg5
- [ 108] Mov dst:reg8, src:Int32(0)
- [ 118] JumpLoop target:block2
-
-block5:
[ 120] SetGlobal `k`, src:reg10
[ 130] GetGlobal value_feedback:1, dst:reg12, `result`
[ 140] GetGlobal value_feedback:2, dst:reg13, `k`
[ 150] GetGlobal value_feedback:3, dst:reg14, `obj`
[ 160] GetGlobal value_feedback:4, dst:reg15, `k`
- [ 170] GetByValue value_feedback:5, keyed_feedback:0, dst:reg16, base:reg14, property:reg15 (obj[reg15])
- [ 190] Add arith_feedback:0, dst:reg14, lhs:reg13, rhs:reg16
- [ 1a0] Add arith_feedback:1, dst:reg13, lhs:reg12, rhs:reg14
- [ 1b0] SetGlobal `result`, src:reg13
- [ 1c0] Mov dst:reg9, src:reg13
+ [ 170] GetByValue value_feedback:5, keyed_feedback:0, dst:reg14, base:reg14, property:reg15
+ [ 190] Add arith_feedback:0, dst:reg13, lhs:reg13, rhs:reg14
+ [ 1a0] Add arith_feedback:1, dst:reg14, lhs:reg12, rhs:reg13
+ [ 1b0] SetGlobal `result`, src:reg14
+ [ 1c0] Mov dst:reg5, src:reg14
[ 1d0] JumpLoop target:block2
+
+block4:
+ [ 1d8] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/for-in-var-function-lhs-name.txt b/Tests/LibJS/Bytecode/expected/for-in-var-function-lhs-name.txt
index 1d8707ba07b..a0348497bdd 100644
--- a/Tests/LibJS/Bytecode/expected/for-in-var-function-lhs-name.txt
+++ b/Tests/LibJS/Bytecode/expected/for-in-var-function-lhs-name.txt
@@ -1,4 +1,4 @@
-$d0083583 for-in-var-function-lhs-name.js:7:1
+$cd444473 for-in-var-function-lhs-name.js:7:1
Registers: 7
Blocks: 1
Constants:
@@ -6,14 +6,15 @@ $d0083583 for-in-var-function-lhs-name.js:7:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `fn`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, fn
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `fn`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-fn$c0513fc2 for-in-var-function-lhs-name.js:4:19
+fn$6998b157 for-in-var-function-lhs-name.js:4:14
Registers: 11
- Blocks: 6
+ Blocks: 5
Locals: f~0
Constants:
[0] = Undefined
@@ -21,27 +22,23 @@ fn$c0513fc2 for-in-var-function-lhs-name.js:4:19
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:f~0
- [ 10] NewFunction dst:reg5, shared_function_data_index:0 (f)
- [ 28] Mov dst:f~0, src:reg5
- [ 38] NewObject dst:reg5
- [ 48] JumpNullish condition:reg5, true_target:block3, false_target:block4
+ [ 8] Mov dst:f~0, src:Undefined
+ [ 18] NewFunction dst:f~0, shared_function_data_index:0 (f)
+ [ 30] NewObject dst:reg6
+ [ 40] Mov dst:reg5, src:reg6
+ [ 50] JumpNullish condition:reg5, true_target:block4, false_target:block1
block1:
- [ 58] End value:Undefined
+ [ 60] GetObjectPropertyIterator dst_keys:reg7, dst_receiver:reg6, object:reg5
+ [ 78] Mov dst:reg8, src:Int32(0)
block2:
- [ 60] ObjectPropertyIteratorNext dst_value:reg9, dst_done:reg10, receiver:reg6, keys:reg7, cursor:reg8
- [ 78] JumpIfLoop condition:reg10, true_target:block1, false_target:block5
+ [ 88] ObjectPropertyIteratorNext dst_value:reg9, dst_done:reg10, receiver:reg6, keys:reg7, cursor:reg8
+ [ a0] JumpTrue condition:reg10, target:block4
block3:
- [ 88] JumpLoop target:block1
+ [ b0] Mov dst:f~0, src:reg9
+ [ c0] JumpLoop target:block2
block4:
- [ 90] GetObjectPropertyIterator dst_keys:reg7, dst_receiver:reg6, object:reg5
- [ a8] Mov dst:reg8, src:Int32(0)
- [ b8] JumpLoop target:block2
-
-block5:
- [ c0] Mov dst:f~0, src:reg9
- [ d0] JumpLoop target:block2
+ [ c8] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/for-loop-break-after-if-continue.txt b/Tests/LibJS/Bytecode/expected/for-loop-break-after-if-continue.txt
index 99596ce3d7b..f4cf5efe508 100644
--- a/Tests/LibJS/Bytecode/expected/for-loop-break-after-if-continue.txt
+++ b/Tests/LibJS/Bytecode/expected/for-loop-break-after-if-continue.txt
@@ -1,4 +1,4 @@
-$393b7f47 for-loop-break-after-if-continue.js:11:1
+$36778e37 for-loop-break-after-if-continue.js:11:1
Registers: 7
Blocks: 1
Constants:
@@ -7,14 +7,15 @@ $393b7f47 for-loop-break-after-if-continue.js:11:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `bok`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, bok, arguments:[Bool(false)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `bok`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Bool(false)]
+ [ 50] End value:reg5
-bok$c038c4fc for-loop-break-after-if-continue.js:6:9
+bok$39f47ee0 for-loop-break-after-if-continue.js:5:14
Registers: 5
- Blocks: 5
+ Blocks: 6
Constants:
[0] = Undefined
@@ -22,13 +23,16 @@ block0:
[ 0] Enter
block1:
- [ 8] JumpIf condition:arg0, true_target:block3, false_target:block4
+ [ 8] JumpFalse condition:arg0, target:block3
block2:
- [ 18] End value:Undefined
+ [ 18] Jump target:block4
block3:
- [ 20] JumpLoop target:block1
+ [ 20] Jump target:block5
block4:
- [ 28] JumpLoop target:block2
+ [ 28] JumpLoop target:block1
+
+block5:
+ [ 30] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/for-loop-scoping.txt b/Tests/LibJS/Bytecode/expected/for-loop-scoping.txt
index 4fd2740ad4b..965c27ba264 100644
--- a/Tests/LibJS/Bytecode/expected/for-loop-scoping.txt
+++ b/Tests/LibJS/Bytecode/expected/for-loop-scoping.txt
@@ -1,21 +1,22 @@
-$349a1c8c for-loop-scoping.js:8:1
- Registers: 10
+$3ce5efbc for-loop-scoping.js:8:1
+ Registers: 9
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `forLetClosure`
- [ 40] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, forLetClosure
- [ 60] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 88] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `forLetClosure`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined
+ [ 70] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 98] End value:reg5
-forLetClosure$9a6a346d for-loop-scoping.js:2:15
- Registers: 10
+forLetClosure$94e2524d for-loop-scoping.js:2:15
+ Registers: 8
Blocks: 4
Locals: fns~0
Constants:
@@ -37,36 +38,34 @@ block0:
[ c0] Jump target:block2
block1:
- [ c8] GetById value_feedback:3, dst:reg7, base:fns~0, `push` (fns.push)
- [ e0] Mov dst:reg8, src:fns~0
- [ f0] NewFunction dst:reg9, shared_function_data_index:0
- [ 108] Call value_feedback:4, call_feedback:0, dst:reg6, callee:reg7, this_value:reg8, fns.push, arguments:[reg9]
- [ 130] GetBinding value_feedback:5, dst:reg6, `i`
- [ 148] SetLexicalEnvironment environment:reg4
- [ 150] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 168] CreateVariable `i`, is_immutable:false, is_global:false, is_strict:false
- [ 178] InitializeLexicalBinding `i`, src:reg6
- [ 190] GetBinding value_feedback:2, dst:reg7, `i`
- [ 1a8] PostfixIncrement arith_feedback:1, dst:reg6, src:reg7
- [ 1b8] SetLexicalBinding `i`, src:reg7
+ [ c8] GetById value_feedback:1, dst:reg6, base:fns~0, `push`
+ [ e0] NewFunction dst:reg7, shared_function_data_index:0
+ [ f8] Call value_feedback:2, call_feedback:0, dst:reg6, callee:reg6, this_value:fns~0, arguments:[reg7]
+ [ 120] GetBinding value_feedback:3, dst:reg6, `i`
+ [ 138] SetLexicalEnvironment environment:reg4
+ [ 140] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
+ [ 158] CreateVariable `i`, is_immutable:false, is_global:false, is_strict:false
+ [ 168] InitializeLexicalBinding `i`, src:reg6
+ [ 180] GetBinding value_feedback:4, dst:reg6, `i`
+ [ 198] PostfixIncrement arith_feedback:0, dst:reg7, src:reg6
+ [ 1a8] SetLexicalBinding `i`, src:reg6
block2:
- [ 1d0] GetBinding value_feedback:1, dst:reg6, `i`
- [ 1e8] JumpLessThanLoopRhsInt32 arith_feedback:0, lhs:reg6, rhs:3, true_target:block1, false_target:block3
+ [ 1c0] GetBinding value_feedback:5, dst:reg6, `i`
+ [ 1d8] JumpLessThanLoopRhsInt32 arith_feedback:1, lhs:reg6, rhs:3, true_target:block1, false_target:block3
block3:
- [ 200] SetLexicalEnvironment environment:reg4
- [ 208] GetById value_feedback:6, dst:reg6, base:fns~0, `map` (fns.map)
- [ 220] Mov dst:reg7, src:fns~0
- [ 230] NewFunction dst:reg8, shared_function_data_index:1
- [ 248] Call value_feedback:7, call_feedback:1, dst:reg5, callee:reg6, this_value:reg7, fns.map, arguments:[reg8]
- [ 270] Return value:reg5
-
-
-map$10ccd4e6 BuiltinFile:275:28
- Registers: 7
- Blocks: 9
- Locals: kValue~0, mappedValue~1, k~2, object~3, length~4, array~5
+ [ 1f0] SetLexicalEnvironment environment:reg4
+ [ 1f8] GetById value_feedback:6, dst:reg5, base:fns~0, `map`
+ [ 210] NewFunction dst:reg6, shared_function_data_index:1
+ [ 228] Call value_feedback:7, call_feedback:1, dst:reg5, callee:reg5, this_value:fns~0, arguments:[reg6]
+ [ 250] Return value:reg5
+
+
+map$04814a69 BuiltinFile:275:11
+ Registers: 6
+ Blocks: 8
+ Locals: object~0, length~1, array~2, k~3, kValue~4, mappedValue~5
Constants:
[0] = Value([object RawNativeFunction])
[1] = Undefined
@@ -74,41 +73,43 @@ map$10ccd4e6 BuiltinFile:275:28
block0:
[ 0] Enter
- [ 8] ToObject dst:object~3, value:this
- [ 18] GetLength value_feedback:0, keyed_feedback:0, dst:reg5, base:object~3 (object.length)
- [ 30] ToLength dst:length~4, value:reg5
- [ 40] IsCallable dst:reg6, value:arg0
- [ 50] Not dst:reg5, src:reg6
- [ 60] JumpFalse condition:reg5, target:block2
+ [ 8] ToObject dst:reg5, value:this
+ [ 18] Mov dst:object~0, src:reg5
+ [ 28] GetLength value_feedback:0, keyed_feedback:0, dst:reg5, base:object~0
+ [ 40] ToLength dst:reg5, value:reg5
+ [ 50] Mov dst:length~1, src:reg5
+ [ 60] IsCallable dst:reg5, value:arg0
+ [ 70] Not dst:reg5, src:reg5
+ [ 80] JumpFalse condition:reg5, target:block2
block1:
- [ 70] ThrowNotAFunction src:arg0
+ [ 90] ThrowNotAFunction src:arg0
block2:
- [ 78] Call value_feedback:1, call_feedback:0, dst:array~5, callee:Value([object RawNativeFunction]), this_value:Undefined, ArraySpeciesCreate, arguments:[object~3, length~4]
- [ a0] Mov dst:k~2, src:Int32(0)
- [ b0] Jump target:block5
+ [ 98] Call value_feedback:1, call_feedback:0, dst:reg5, callee:Value([object RawNativeFunction]), this_value:Undefined, arguments:[object~0, length~1]
+ [ c0] Mov dst:array~2, src:reg5
+ [ d0] Mov dst:k~3, src:Int32(0)
+ [ e0] Jump target:block6
block3:
- [ b8] In dst:reg5, lhs:k~2, rhs:object~3
- [ c8] JumpIf condition:reg5, true_target:block7, false_target:block8
+ [ e8] In dst:reg5, lhs:k~3, rhs:object~0
+ [ f8] JumpFalse condition:reg5, target:block5
block4:
- [ d8] Increment arith_feedback:1, dst:k~2
+ [ 108] GetByValue value_feedback:2, keyed_feedback:1, dst:reg5, base:object~0, property:k~3
+ [ 128] Mov dst:kValue~4, src:reg5
+ [ 138] Call value_feedback:3, call_feedback:1, dst:reg5, callee:arg0, this_value:arg1, arguments:[kValue~4, k~3, object~0]
+ [ 168] Mov dst:mappedValue~5, src:reg5
+ [ 178] CreateDataPropertyOrThrow object:array~2, property:k~3, value:mappedValue~5
block5:
- [ e0] JumpLessThanLoop arith_feedback:0, lhs:k~2, rhs:length~4, true_target:block3, false_target:block6
+ [ 188] Increment arith_feedback:0, dst:k~3
block6:
- [ f8] Return value:array~5
+ [ 190] JumpLessThanLoop arith_feedback:1, lhs:k~3, rhs:length~1, true_target:block3, false_target:block7
block7:
- [ 100] GetByValue value_feedback:2, keyed_feedback:1, dst:kValue~0, base:object~3, property:k~2 (object[k~2])
- [ 120] Call value_feedback:3, call_feedback:1, dst:mappedValue~1, callee:arg0, this_value:arg1, callback, arguments:[kValue~0, k~2, object~3]
- [ 150] CreateDataPropertyOrThrow object:array~5, property:k~2, value:mappedValue~1
-
-block8:
- [ 160] JumpLoop target:block4
+ [ 1a8] Return value:array~2
$dd56fdd7 for-loop-scoping.js:6:20
@@ -119,7 +120,7 @@ $dd56fdd7 for-loop-scoping.js:6:20
block0:
[ 0] Enter
- [ 8] Call value_feedback:0, call_feedback:0, dst:reg5, callee:arg0, this_value:Undefined, f
+ [ 8] Call value_feedback:0, call_feedback:0, dst:reg5, callee:arg0, this_value:Undefined
[ 28] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/for-of-cond-rhs-block-order.txt b/Tests/LibJS/Bytecode/expected/for-of-cond-rhs-block-order.txt
index 35c439ba7eb..c6e7e32f527 100644
--- a/Tests/LibJS/Bytecode/expected/for-of-cond-rhs-block-order.txt
+++ b/Tests/LibJS/Bytecode/expected/for-of-cond-rhs-block-order.txt
@@ -1,4 +1,4 @@
-$6a33dffa for-of-cond-rhs-block-order.js:6:1
+$676feeea for-of-cond-rhs-block-order.js:6:1
Registers: 7
Blocks: 1
Constants:
@@ -7,144 +7,106 @@ $6a33dffa for-of-cond-rhs-block-order.js:6:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[Null, Null]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Null, Null]
+ [ 50] End value:reg5
-f$08f135b5 for-of-cond-rhs-block-order.js:2:21
- Registers: 19
- Blocks: 31
+f$a6e23ba8 for-of-cond-rhs-block-order.js:2:15
+ Registers: 16
+ Blocks: 22
Locals: r~0, n~1
Constants:
- [0] = Bool(false)
- [1] = Undefined
- [2] = Int32(1)
- [3] = Int32(2)
+ [0] = <Empty>
+ [1] = Bool(false)
+ [2] = Undefined
block0:
[ 0] Enter
- [ 8] JumpIf condition:arg0, true_target:block3, false_target:block4
+ [ 8] Mov dst:r~0, src:<Empty>
+ [ 18] Mov dst:n~1, src:<Empty>
+ [ 28] JumpFalse condition:arg0, target:block2
block1:
- [ 18] End value:Undefined
+ [ 38] GetById value_feedback:0, dst:reg6, base:arg0, `x`
+ [ 50] Jump target:block3
block2:
- [ 20] IteratorNextUnpack dst_value:reg10, dst_done:reg11, iterator_object:reg5, iterator_next:reg8, iterator_done:reg7
- [ 38] JumpIfLoop condition:reg11, true_target:block1, false_target:block8
+ [ 58] Mov dst:reg6, src:arg1
block3:
- [ 48] GetById value_feedback:0, dst:reg6, base:arg0, `x` (o.x)
- [ 60] Mov dst:reg5, src:reg6
- [ 70] Jump target:block5
+ [ 68] GetGlobal value_feedback:1, dst:reg7, `Object`
+ [ 78] GetById value_feedback:2, dst:reg8, base:reg7, `entries`
+ [ 90] NewObject dst:reg9
+ [ a0] Call value_feedback:3, call_feedback:0, dst:reg5, callee:reg8, this_value:reg7, arguments:[reg9]
+ [ c8] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true
block4:
- [ 78] Mov dst:reg5, src:arg1
+ [ e8] IteratorNextUnpack dst_value:reg9, dst_done:reg10, iterator_object:reg6, iterator_next:reg7, iterator_done:reg8
+ [ 100] JumpTrue condition:reg10, target:block21
block5:
- [ 88] GetGlobal value_feedback:1, dst:reg7, `Object`
- [ 98] GetById value_feedback:2, dst:reg8, base:reg7, `entries` (Object.entries)
- [ b0] NewObject dst:reg9
- [ c0] Call value_feedback:3, call_feedback:0, dst:reg6, callee:reg8, this_value:reg7, Object.entries, arguments:[reg9]
- [ e8] GetIterator dst_iterator_object:reg5, dst_iterator_next:reg8, dst_iterator_done:reg7, iterable:reg6, fast_array_mode_allowed:true
- [ 108] JumpLoop target:block2
+ [ 110] Mov dst:reg11, src:Bool(false)
+ [ 120] GetIterator dst_iterator_object:reg12, dst_iterator_next:reg13, dst_iterator_done:reg14, iterable:reg9, fast_array_mode_allowed:true
block6:
- [ 110] Catch value_feedback:5, dst:reg9
- [ 118] Mov dst:reg6, src:Int32(1)
+ [ 140] IteratorNextUnpack dst_value:reg15, dst_done:reg11, iterator_object:reg12, iterator_next:reg13, iterator_done:reg14
block7:
- [ 128] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:reg6, rhs:1, true_target:block27, false_target:block28
+ [ 158] JumpFalse condition:reg11, target:block9
block8:
- [ 140] Mov dst:reg12, src:Bool(false)
- [ 150] GetIterator dst_iterator_object:reg13, dst_iterator_next:reg14, dst_iterator_done:reg15, iterable:reg10, fast_array_mode_allowed:true
- [ 170] Jump target:block11
+ [ 168] Mov dst:reg15, src:Undefined
block9:
- [ 178] Catch value_feedback:4, dst:reg17
- [ 180] Mov dst:reg16, src:Int32(1)
- [ 190] JumpIf condition:reg15, true_target:block22, false_target:block21
+ [ 178] Mov dst:r~0, src:reg15
+ [ 188] JumpTrue condition:reg11, target:block12
block10:
- [ 1a0] JumpLoop target:block2
+ [ 198] IteratorNextUnpack dst_value:reg15, dst_done:reg11, iterator_object:reg12, iterator_next:reg13, iterator_done:reg14
block11:
- [ 1a8] Jump target:block13
+ [ 1b0] JumpFalse condition:reg11, target:block13
block12:
- [ 1b0] MovSrcUndefined dst:reg18
- [ 1b8] Jump target:block14
+ [ 1c0] Mov dst:reg15, src:Undefined
block13:
- [ 1c0] IteratorNextUnpack dst_value:reg18, dst_done:reg12, iterator_object:reg13, iterator_next:reg14, iterator_done:reg15
- [ 1d8] JumpTrueLoop condition:reg12, target:block12
+ [ 1d0] Mov dst:n~1, src:reg15
block14:
- [ 1e8] Mov dst:r~0, src:reg18
- [ 1f8] JumpFalse condition:reg12, target:block16
+ [ 1e0] JumpTrue condition:reg14, target:block19
block15:
- [ 208] MovSrcUndefined dst:reg18
- [ 210] Jump target:block17
+ [ 1f0] IteratorClose iterator_object:reg12, iterator_next:reg13, iterator_done:reg14, completion_value:Undefined
+ [ 210] Jump target:block19
block16:
- [ 218] IteratorNextUnpack dst_value:reg18, dst_done:reg12, iterator_object:reg13, iterator_next:reg14, iterator_done:reg15
- [ 230] JumpTrueLoop condition:reg12, target:block15
+ [ 218] Catch value_feedback:4, dst:reg15
+ [ 220] JumpTrue condition:reg14, target:block18
block17:
- [ 240] Mov dst:n~1, src:reg18
+ [ 230] IteratorClose iterator_object:reg12, iterator_next:reg13, iterator_done:reg14, completion_value:reg15
block18:
- [ 250] JumpFalse condition:reg15, target:block20
+ [ 250] Throw src:reg15
block19:
- [ 260] JumpLoop target:block10
+ [ 258] JumpLoop target:block4
block20:
- [ 268] IteratorClose iterator_object:reg13, iterator_next:reg14, iterator_done:reg15, completion_value:Undefined
- [ 288] JumpLoop target:block19
+ [ 260] Catch value_feedback:5, dst:reg11
+ [ 268] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:reg11
+ [ 288] Throw src:reg11
block21:
- [ 290] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg16, rhs:1, true_target:block23, false_target:block24
-
-block22:
- [ 2a8] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg16, rhs:2, true_target:block25, false_target:block26
-
-block23:
- [ 2c0] IteratorClose iterator_object:reg13, iterator_next:reg14, iterator_done:reg15, completion_value:reg17
- [ 2e0] Throw src:reg17
-
-block24:
- [ 2e8] IteratorClose iterator_object:reg13, iterator_next:reg14, iterator_done:reg15, completion_value:Undefined
- [ 308] JumpLoop target:block22
-
-block25:
- [ 310] Mov2 c0_dst:reg6, c0_src:reg16, c1_dst:reg9, c1_src:reg17
- [ 328] JumpLoop target:block7
-
-block26:
- [ 330] Throw src:reg17
-
-block27:
- [ 338] IteratorClose iterator_object:reg5, iterator_next:reg8, iterator_done:reg7, completion_value:reg9
- [ 358] Throw src:reg9
-
-block28:
- [ 360] IteratorClose iterator_object:reg5, iterator_next:reg8, iterator_done:reg7, completion_value:Undefined
- [ 380] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg6, rhs:2, true_target:block29, false_target:block30
-
-block29:
- [ 398] Return value:reg9
-
-block30:
- [ 3a0] Throw src:reg9
+ [ 290] End value:Undefined
Exception handlers:
- [ 140 .. 1a8] => handler block6
- [ 1a8 .. 1c0] => handler block9
- [ 1c0 .. 1e8] => handler block6
- [ 1e8 .. 218] => handler block9
- [ 218 .. 240] => handler block6
- [ 240 .. 250] => handler block9
- [ 250 .. 338] => handler block6
+ [ 110 .. 140] => handler block20
+ [ 140 .. 158] => handler block20
+ [ 158 .. 198] => handler block16
+ [ 198 .. 1b0] => handler block20
+ [ 1b0 .. 1e0] => handler block16
+ [ 1e0 .. 260] => handler block20
diff --git a/Tests/LibJS/Bytecode/expected/for-of-continue-with-block-scope.txt b/Tests/LibJS/Bytecode/expected/for-of-continue-with-block-scope.txt
index 41d5182cc8b..f2a37ef84c3 100644
--- a/Tests/LibJS/Bytecode/expected/for-of-continue-with-block-scope.txt
+++ b/Tests/LibJS/Bytecode/expected/for-of-continue-with-block-scope.txt
@@ -1,4 +1,4 @@
-$2b0d6491 for-of-continue-with-block-scope.js:13:1
+$335937c1 for-of-continue-with-block-scope.js:13:1
Registers: 8
Blocks: 1
Constants:
@@ -6,81 +6,63 @@ $2b0d6491 for-of-continue-with-block-scope.js:13:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] NewArray dst:reg7
- [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[reg7]
- [ 50] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] NewArray dst:reg7
+ [ 38] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 60] End value:reg5
-f$ac6a1dc8 for-of-continue-with-block-scope.js:2:15
- Registers: 18
- Blocks: 11
- Locals: o~0, t~1
- Constants:
- [0] = Int32(1)
- [1] = Undefined
- [2] = Int32(2)
+f$2dcc1650 for-of-continue-with-block-scope.js:2:15
+ Registers: 14
+ Blocks: 7
+ Locals: t~0, o~1
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] NewArray dst:t~1
- [ 20] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 38] CreateVariable `r`, is_immutable:false, is_global:false, is_strict:false
- [ 48] SetLexicalEnvironment environment:reg4
- [ 50] GetIterator dst_iterator_object:reg5, dst_iterator_next:reg6, dst_iterator_done:reg7, iterable:arg0, fast_array_mode_allowed:true
- [ 70] Jump target:block2
+ [ 10] NewArray dst:t~0
+ [ 20] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `r`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] Mov dst:reg5, src:arg0
+ [ 58] SetLexicalEnvironment environment:reg4
+ [ 60] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true
block1:
- [ 78] Return value:t~1
+ [ 80] IteratorNextUnpack dst_value:reg9, dst_done:reg10, iterator_object:reg6, iterator_next:reg7, iterator_done:reg8
+ [ 98] JumpTrue condition:reg10, target:block6
block2:
- [ 80] IteratorNextUnpack dst_value:reg10, dst_done:reg11, iterator_object:reg5, iterator_next:reg6, iterator_done:reg7
- [ 98] JumpIfLoop condition:reg11, true_target:block1, false_target:block4
+ [ a8] CreateLexicalEnvironment dst:reg11, parent:reg4, capacity:1, is_catch_environment:false
+ [ c0] CreateVariable `r`, is_immutable:true, is_global:false, is_strict:true
+ [ d0] InitializeLexicalBinding `r`, src:reg9
+ [ e8] GetBinding value_feedback:0, dst:reg12, `r`
+ [ 100] Not dst:reg12, src:reg12
+ [ 110] JumpFalse condition:reg12, target:block4
block3:
- [ a8] Catch value_feedback:6, dst:reg9
- [ b0] SetLexicalEnvironment environment:reg4
- [ b8] Mov dst:reg8, src:Int32(1)
- [ c8] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg8, rhs:1, true_target:block7, false_target:block8
+ [ 120] GetById value_feedback:1, dst:reg12, base:t~0, `push`
+ [ 138] GetBinding value_feedback:2, dst:reg13, `r`
+ [ 150] Call value_feedback:3, call_feedback:0, dst:reg12, callee:reg12, this_value:t~0, arguments:[reg13]
+ [ 178] SetLexicalEnvironment environment:reg4
+ [ 180] Jump target:block1
block4:
- [ e0] CreateLexicalEnvironment dst:reg12, parent:reg4, capacity:1, is_catch_environment:false
- [ f8] CreateVariable `r`, is_immutable:true, is_global:false, is_strict:true
- [ 108] InitializeLexicalBinding `r`, src:reg10
- [ 120] GetBinding value_feedback:0, dst:reg14, `r`
- [ 138] Not dst:reg13, src:reg14
- [ 148] JumpFalse condition:reg13, target:block6
+ [ 188] GetById value_feedback:4, dst:reg12, base:t~0, `find`
+ [ 1a0] NewFunction dst:reg13, shared_function_data_index:0
+ [ 1b8] Call value_feedback:5, call_feedback:1, dst:reg12, callee:reg12, this_value:t~0, arguments:[reg13]
+ [ 1e0] Mov dst:o~1, src:reg12
+ [ 1f0] SetLexicalEnvironment environment:reg4
+ [ 1f8] JumpLoop target:block1
block5:
- [ 158] GetById value_feedback:1, dst:reg15, base:t~1, `push` (t.push)
- [ 170] Mov dst:reg16, src:t~1
- [ 180] GetBinding value_feedback:2, dst:reg17, `r`
- [ 198] Call value_feedback:3, call_feedback:0, dst:reg14, callee:reg15, this_value:reg16, t.push, arguments:[reg17]
- [ 1c0] SetLexicalEnvironment environment:reg4
- [ 1c8] JumpLoop target:block2
+ [ 200] Catch value_feedback:6, dst:reg11
+ [ 208] SetLexicalEnvironment environment:reg4
+ [ 210] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:reg11
+ [ 230] Throw src:reg11
block6:
- [ 1d0] GetById value_feedback:4, dst:reg13, base:t~1, `find` (t.find)
- [ 1e8] Mov dst:reg14, src:t~1
- [ 1f8] NewFunction dst:reg15, shared_function_data_index:0
- [ 210] Call value_feedback:5, call_feedback:1, dst:o~0, callee:reg13, this_value:reg14, t.find, arguments:[reg15]
- [ 238] SetLexicalEnvironment environment:reg4
- [ 240] JumpLoop target:block2
-
-block7:
- [ 248] IteratorClose iterator_object:reg5, iterator_next:reg6, iterator_done:reg7, completion_value:reg9
- [ 268] Throw src:reg9
-
-block8:
- [ 270] IteratorClose iterator_object:reg5, iterator_next:reg6, iterator_done:reg7, completion_value:Undefined
- [ 290] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg8, rhs:2, true_target:block9, false_target:block10
-
-block9:
- [ 2a8] Return value:reg9
-
-block10:
- [ 2b0] Throw src:reg9
+ [ 238] Return value:t~0
Exception handlers:
- [ e0 .. 248] => handler block3
+ [ a8 .. 200] => handler block5
diff --git a/Tests/LibJS/Bytecode/expected/for-of-iteration-env-capacity.txt b/Tests/LibJS/Bytecode/expected/for-of-iteration-env-capacity.txt
index 179a152e0ca..5055036e3da 100644
--- a/Tests/LibJS/Bytecode/expected/for-of-iteration-env-capacity.txt
+++ b/Tests/LibJS/Bytecode/expected/for-of-iteration-env-capacity.txt
@@ -1,48 +1,38 @@
-$0a509d5d for-of-iteration-env-capacity.js:1:14
- Registers: 14
- Blocks: 9
+$41ba29cb for-of-iteration-env-capacity.js:1:12
+ Registers: 13
+ Blocks: 5
Locals: x~0
Constants:
[0] = Undefined
- [1] = Int32(1)
- [2] = Int32(2)
+ [1] = <Empty>
+ [2] = Int32(1)
+ [3] = Int32(2)
+ [4] = Int32(3)
block0:
[ 0] Enter
- [ 8] NewPrimitiveArray dst:reg5, elements:[1, 2, 3]
- [ 30] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true
- [ 50] MovSrcUndefined dst:reg5
- [ 58] Jump target:block2
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:x~0, src:<Empty>
+ [ 28] NewPrimitiveArray dst:reg6, elements:[1, 2, 3]
+ [ 50] Mov dst:reg5, src:Undefined
+ [ 60] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg6, fast_array_mode_allowed:true
block1:
- [ 60] End value:reg5
+ [ 80] IteratorNextUnpack dst_value:reg10, dst_done:reg11, iterator_object:reg7, iterator_next:reg8, iterator_done:reg9
+ [ 98] JumpTrue condition:reg11, target:block4
block2:
- [ 68] IteratorNextUnpack dst_value:reg11, dst_done:reg12, iterator_object:reg6, iterator_next:reg7, iterator_done:reg8
- [ 80] JumpIfLoop condition:reg12, true_target:block1, false_target:block4
+ [ a8] Mov dst:x~0, src:reg10
+ [ b8] Mov dst:reg5, src:x~0
+ [ c8] JumpLoop target:block1
block3:
- [ 90] Catch value_feedback:0, dst:reg10
- [ 98] Mov dst:reg9, src:Int32(1)
- [ a8] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg9, rhs:1, true_target:block5, false_target:block6
+ [ d0] Catch value_feedback:0, dst:reg12
+ [ d8] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:reg12
+ [ f8] Throw src:reg12
block4:
- [ c0] Mov3 c0_dst:x~0, c0_src:reg11, c1_dst:reg13, c1_src:x~0, c2_dst:reg5, c2_src:reg13
- [ e0] JumpLoop target:block2
-
-block5:
- [ e8] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:reg10
- [ 108] Throw src:reg10
-
-block6:
- [ 110] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:Undefined
- [ 130] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg9, rhs:2, true_target:block7, false_target:block8
-
-block7:
- [ 148] Return value:reg10
-
-block8:
- [ 150] Throw src:reg10
+ [ 100] End value:reg5
Exception handlers:
- [ c0 .. e8] => handler block3
+ [ a8 .. d0] => handler block3
diff --git a/Tests/LibJS/Bytecode/expected/for-of-iterator-close.txt b/Tests/LibJS/Bytecode/expected/for-of-iterator-close.txt
index 8aca2d6c27d..e83ae164eee 100644
--- a/Tests/LibJS/Bytecode/expected/for-of-iterator-close.txt
+++ b/Tests/LibJS/Bytecode/expected/for-of-iterator-close.txt
@@ -1,253 +1,211 @@
-$fc2d7ee2 for-of-iterator-close.js:6:1
- Registers: 9
+$04795212 for-of-iterator-close.js:6:1
+ Registers: 8
Blocks: 1
Constants:
[0] = Undefined
+ [1] = Int32(1)
+ [2] = Int32(2)
+ [3] = Int32(3)
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `forOfBreak`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, forOfBreak
- [ 38] GetGlobal value_feedback:2, dst:reg7, `forOfReturn`
- [ 48] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, forOfReturn
- [ 68] GetGlobal value_feedback:4, dst:reg7, `forAwaitOfBreak`
- [ 78] NewPrimitiveArray dst:reg8, elements:[1, 2, 3]
- [ a0] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg7, this_value:Undefined, forAwaitOfBreak, arguments:[reg8]
- [ c8] End value:reg5
-
-
-forOfBreak$8c4ac10b for-of-iterator-close.js:2:18
- Registers: 13
- Blocks: 13
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `forOfBreak`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] GetGlobal value_feedback:2, dst:reg6, `forOfReturn`
+ [ 58] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined
+ [ 78] GetGlobal value_feedback:4, dst:reg6, `forAwaitOfBreak`
+ [ 88] NewPrimitiveArray dst:reg7, elements:[1, 2, 3]
+ [ b0] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ d8] End value:reg5
+
+
+forOfBreak$33b1e7dd for-of-iterator-close.js:2:16
+ Registers: 12
+ Blocks: 7
Locals: x~0
Constants:
- [0] = Int32(2)
- [1] = Int32(3)
- [2] = Int32(1)
- [3] = Undefined
+ [0] = <Empty>
+ [1] = Int32(1)
+ [2] = Int32(2)
+ [3] = Int32(3)
+ [4] = Undefined
block0:
[ 0] Enter
- [ 8] NewPrimitiveArray dst:reg5, elements:[1, 2, 3]
- [ 30] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true
- [ 50] Jump target:block2
+ [ 8] Mov dst:x~0, src:<Empty>
+ [ 18] NewPrimitiveArray dst:reg5, elements:[1, 2, 3]
+ [ 40] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true
block1:
- [ 58] End value:Undefined
+ [ 60] IteratorNextUnpack dst_value:reg9, dst_done:reg10, iterator_object:reg6, iterator_next:reg7, iterator_done:reg8
+ [ 78] JumpTrue condition:reg10, target:block6
block2:
- [ 60] IteratorNextUnpack dst_value:reg10, dst_done:reg11, iterator_object:reg6, iterator_next:reg7, iterator_done:reg8
- [ 78] JumpIfLoop condition:reg11, true_target:block1, false_target:block5
+ [ 88] Mov dst:x~0, src:reg9
+ [ 98] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:x~0, rhs:2, true_target:block3, false_target:block4
block3:
- [ 88] Catch value_feedback:0, dst:reg9
- [ 90] Mov dst:reg5, src:Int32(1)
+ [ b0] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:Undefined
+ [ d0] Jump target:block6
block4:
- [ a0] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg5, rhs:1, true_target:block8, false_target:block9
+ [ d8] JumpLoop target:block1
block5:
- [ b8] Mov dst:x~0, src:reg10
- [ c8] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:x~0, rhs:2, true_target:block6, false_target:block7
+ [ e0] Catch value_feedback:0, dst:reg11
+ [ e8] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:reg11
+ [ 108] Throw src:reg11
block6:
- [ e0] Mov dst:reg5, src:Int32(3)
- [ f0] JumpLoop target:block4
-
-block7:
- [ f8] JumpLoop target:block2
-
-block8:
- [ 100] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:reg9
- [ 120] Throw src:reg9
-
-block9:
- [ 128] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:Undefined
- [ 148] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:2, lhs:reg5, rhs:3, true_target:block1, false_target:block10
-
-block10:
- [ 160] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg5, rhs:2, true_target:block11, false_target:block12
-
-block11:
- [ 178] Return value:reg9
-
-block12:
- [ 180] Throw src:reg9
+ [ 110] End value:Undefined
Exception handlers:
- [ b8 .. 100] => handler block3
+ [ 88 .. b0] => handler block5
+ [ d8 .. e0] => handler block5
-forOfReturn$3e676e69 for-of-iterator-close.js:9:18
+forOfReturn$df036ef4 for-of-iterator-close.js:9:16
Registers: 12
- Blocks: 10
+ Blocks: 5
Locals: x~0
Constants:
- [0] = Int32(2)
+ [0] = <Empty>
[1] = Int32(1)
- [2] = Undefined
+ [2] = Int32(2)
+ [3] = Int32(3)
+ [4] = Undefined
block0:
[ 0] Enter
- [ 8] NewPrimitiveArray dst:reg5, elements:[1, 2, 3]
- [ 30] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true
- [ 50] Jump target:block2
+ [ 8] Mov dst:x~0, src:<Empty>
+ [ 18] NewPrimitiveArray dst:reg5, elements:[1, 2, 3]
+ [ 40] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true
+ [ 60] IteratorNextUnpack dst_value:reg9, dst_done:reg10, iterator_object:reg6, iterator_next:reg7, iterator_done:reg8
+ [ 78] JumpTrue condition:reg10, target:block4
block1:
- [ 58] End value:Undefined
+ [ 88] Mov dst:x~0, src:reg9
block2:
- [ 60] IteratorNextUnpack dst_value:reg10, dst_done:reg11, iterator_object:reg6, iterator_next:reg7, iterator_done:reg8
- [ 78] JumpIfLoop condition:reg11, true_target:block1, false_target:block5
+ [ 98] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:Undefined
+ [ b8] Return value:x~0
block3:
- [ 88] Catch value_feedback:0, dst:reg9
- [ 90] Mov dst:reg5, src:Int32(1)
+ [ c0] Catch value_feedback:0, dst:reg11
+ [ c8] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:reg11
+ [ e8] Throw src:reg11
block4:
- [ a0] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg5, rhs:1, true_target:block6, false_target:block7
-
-block5:
- [ b8] Mov3 c0_dst:x~0, c0_src:reg10, c1_dst:reg9, c1_src:x~0, c2_dst:reg5, c2_src:Int32(2)
- [ d8] JumpLoop target:block4
-
-block6:
- [ e0] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:reg9
- [ 100] Throw src:reg9
-
-block7:
- [ 108] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:Undefined
- [ 128] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg5, rhs:2, true_target:block8, false_target:block9
-
-block8:
- [ 140] Return value:reg9
-
-block9:
- [ 148] Throw src:reg9
+ [ f0] End value:Undefined
Exception handlers:
- [ b8 .. e0] => handler block3
+ [ 88 .. 98] => handler block3
-forAwaitOfBreak$976a8bbf for-of-iterator-close.js:16:24
+forAwaitOfBreak$fa5b4aea for-of-iterator-close.js:16:22
Registers: 18
- Blocks: 29
+ Blocks: 23
Locals: x~0
Constants:
- [0] = Int32(1)
- [1] = Int32(2)
- [2] = Int32(3)
+ [0] = <Empty>
+ [1] = Int32(1)
+ [2] = Int32(2)
[3] = Undefined
block0:
[ 0] Enter
- [ 8] GetIterator dst_iterator_object:reg5, dst_iterator_next:reg6, dst_iterator_done:reg7, iterable:arg0, fast_array_mode_allowed:false
- [ 28] Jump target:block2
+ [ 8] Mov dst:x~0, src:<Empty>
+ [ 18] Mov dst:reg5, src:arg0
+ [ 28] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:false
block1:
- [ 30] Yield value:Undefined
+ [ 48] IteratorNext dst:reg11, iterator_object:reg6, iterator_next:reg7, iterator_done:reg8
+ [ 60] Mov dst:reg12, src:reg0
+ [ 70] Await continuation_label:block2, argument:reg11
block2:
- [ 40] IteratorNext dst:reg12, iterator_object:reg5, iterator_next:reg6, iterator_done:reg7
- [ 58] Mov dst:reg13, src:reg0
- [ 68] Await continuation_label:block5, argument:reg12
+ [ 80] Mov dst:reg12, src:reg0
+ [ 90] GetCompletionFields type_dst:reg13, value_dst:reg14, completion:reg12
+ [ a0] StrictlyEqualsRhsInt32 arith_feedback:0, dst:reg15, lhs:reg13, rhs:1
+ [ b0] JumpIf condition:reg15, true_target:block4, false_target:block3
block3:
- [ 78] Catch value_feedback:2, dst:reg9
- [ 80] Mov dst:reg8, src:Int32(1)
+ [ c0] Throw src:reg14
block4:
- [ 90] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:reg8, rhs:1, true_target:block12, false_target:block13
+ [ c8] ThrowIfNotObject src:reg14
+ [ d0] GetById value_feedback:0, dst:reg10, base:reg14, `done`
+ [ e8] JumpTrue condition:reg10, target:block22
block5:
- [ a8] Mov dst:reg13, src:reg0
- [ b8] GetCompletionFields type_dst:reg14, value_dst:reg15, completion:reg13
- [ c8] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg14, rhs:1, true_target:block6, false_target:block7
+ [ f8] GetById value_feedback:1, dst:reg9, base:reg14, `value`
block6:
- [ e0] Mov dst:reg12, src:reg15
- [ f0] ThrowIfNotObject src:reg12
- [ f8] GetById value_feedback:0, dst:reg11, base:reg12, `done`
- [ 110] JumpIfLoop condition:reg11, true_target:block1, false_target:block8
+ [ 110] Mov dst:x~0, src:reg9
+ [ 120] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:x~0, rhs:2, true_target:block7, false_target:block13
block7:
- [ 120] Throw src:reg15
+ [ 138] GetMethod dst:reg11, object:reg6, `return`
+ [ 150] JumpUndefined condition:reg11, true_target:block12, false_target:block8
block8:
- [ 128] GetById value_feedback:1, dst:reg10, base:reg12, `value`
+ [ 160] Call value_feedback:2, call_feedback:0, dst:reg12, callee:reg11, this_value:reg6
+ [ 180] Mov dst:reg13, src:reg0
+ [ 190] Await continuation_label:block9, argument:reg12
block9:
- [ 140] Mov dst:x~0, src:reg10
- [ 150] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:x~0, rhs:2, true_target:block10, false_target:block11
+ [ 1a0] Mov dst:reg13, src:reg0
+ [ 1b0] GetCompletionFields type_dst:reg14, value_dst:reg15, completion:reg13
+ [ 1c0] StrictlyEqualsRhsInt32 arith_feedback:2, dst:reg16, lhs:reg14, rhs:1
+ [ 1d0] JumpIf condition:reg16, true_target:block11, false_target:block10
block10:
- [ 168] Mov dst:reg8, src:Int32(3)
- [ 178] JumpLoop target:block4
+ [ 1e0] Throw src:reg15
block11:
- [ 180] JumpLoop target:block2
+ [ 1e8] ThrowIfNotObject src:reg15
block12:
- [ 188] Jump target:block24
+ [ 1f0] Jump target:block22
block13:
- [ 190] GetMethod dst:reg12, object:reg5, `return`
- [ 1a8] JumpUndefined condition:reg12, true_target:block14, false_target:block15
+ [ 1f8] JumpLoop target:block1
block14:
- [ 1b8] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:4, lhs:reg8, rhs:3, true_target:block1, false_target:block19
+ [ 200] Catch value_feedback:3, dst:reg11
block15:
- [ 1d0] Call value_feedback:3, call_feedback:0, dst:reg13, callee:reg12, this_value:reg5
- [ 1f0] Await continuation_label:block16, argument:reg13
+ [ 208] GetMethod dst:reg12, object:reg6, `return`
+ [ 220] JumpUndefined condition:reg12, true_target:block21, false_target:block16
block16:
- [ 200] Mov dst:reg14, src:reg0
- [ 210] GetCompletionFields type_dst:reg15, value_dst:reg16, completion:reg14
- [ 220] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg15, rhs:1, true_target:block17, false_target:block18
+ [ 230] Call value_feedback:4, call_feedback:1, dst:reg13, callee:reg12, this_value:reg6
+ [ 250] Mov dst:reg14, src:reg0
+ [ 260] Await continuation_label:block17, argument:reg13
block17:
- [ 238] ThrowIfNotObject src:reg16
- [ 240] JumpLoop target:block14
+ [ 270] Mov dst:reg14, src:reg0
+ [ 280] GetCompletionFields type_dst:reg15, value_dst:reg16, completion:reg14
+ [ 290] StrictlyEqualsRhsInt32 arith_feedback:3, dst:reg17, lhs:reg15, rhs:1
+ [ 2a0] JumpIf condition:reg17, true_target:block19, false_target:block18
block18:
- [ 248] Throw src:reg16
+ [ 2b0] Throw src:reg16
block19:
- [ 250] JumpStrictlyEqualsRhsInt32 arith_feedback:5, lhs:reg8, rhs:2, true_target:block20, false_target:block21
+ [ 2b8] Jump target:block21
block20:
- [ 268] Return value:reg9
+ [ 2c0] Catch value_feedback:5, dst:reg12
block21:
- [ 270] Throw src:reg9
+ [ 2c8] Throw src:reg11
block22:
- [ 278] Throw src:reg9
-
-block23:
- [ 280] Catch value_feedback:5, dst:reg12
- [ 288] JumpLoop target:block22
-
-block24:
- [ 290] GetMethod dst:reg12, object:reg5, `return`
- [ 2a8] JumpUndefined condition:reg12, true_target:block22, false_target:block25
-
-block25:
- [ 2b8] Call value_feedback:4, call_feedback:1, dst:reg13, callee:reg12, this_value:reg5
- [ 2d8] Await continuation_label:block26, argument:reg13
-
-block26:
- [ 2e8] Mov dst:reg14, src:reg0
- [ 2f8] GetCompletionFields type_dst:reg15, value_dst:reg16, completion:reg14
- [ 308] JumpStrictlyEqualsRhsInt32 arith_feedback:6, lhs:reg15, rhs:1, true_target:block27, false_target:block28
-
-block27:
- [ 320] JumpLoop target:block22
-
-block28:
- [ 328] Throw src:reg16
+ [ 2d0] Yield value:Undefined
Exception handlers:
- [ 140 .. 188] => handler block3
- [ 290 .. 330] => handler block23
+ [ 110 .. 138] => handler block14
+ [ 1f8 .. 200] => handler block14
+ [ 208 .. 2c0] => handler block20
diff --git a/Tests/LibJS/Bytecode/expected/for-of-rhs-precedence.txt b/Tests/LibJS/Bytecode/expected/for-of-rhs-precedence.txt
index 7b4f264dff6..f465cf97aaa 100644
--- a/Tests/LibJS/Bytecode/expected/for-of-rhs-precedence.txt
+++ b/Tests/LibJS/Bytecode/expected/for-of-rhs-precedence.txt
@@ -1,9 +1,10 @@
-$4e59e625
- Registers: 5
+$511dd735
+ Registers: 6
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/for-try-finally-continue.txt b/Tests/LibJS/Bytecode/expected/for-try-finally-continue.txt
index 5895bab6145..ad2dbb3ee37 100644
--- a/Tests/LibJS/Bytecode/expected/for-try-finally-continue.txt
+++ b/Tests/LibJS/Bytecode/expected/for-try-finally-continue.txt
@@ -1,81 +1,78 @@
-$3576718a for-try-finally-continue.js:1:1
- Registers: 11
- Blocks: 16
+$5fbe493e for-try-finally-continue.js:1:5
+ Registers: 9
+ Blocks: 14
Locals: e~0
Constants:
- [0] = Int32(0)
- [1] = Undefined
- [2] = Int32(5)
- [3] = Int32(1)
- [4] = Int32(3)
- [5] = Int32(2)
+ [0] = Undefined
+ [1] = Int32(0)
+ [2] = Int32(2)
+ [3] = <Empty>
+ [4] = Int32(1)
+ [5] = Int32(5)
[6] = String("bad")
block0:
[ 0] Enter
- [ 8] SetGlobal `i`, src:Int32(0)
- [ 18] MovSrcUndefined dst:reg5
- [ 20] Jump target:block3
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:Undefined
+ [ 28] SetGlobal `i`, src:Int32(0)
+ [ 38] Jump target:block10
block1:
- [ 28] MovSrcUndefined dst:reg6
- [ 30] Jump target:block8
+ [ 40] Mov dst:reg5, src:Undefined
block2:
- [ 38] GetGlobal value_feedback:1, dst:reg7, `i`
- [ 48] PostfixIncrement arith_feedback:1, dst:reg6, src:reg7
- [ 58] SetGlobal `i`, src:reg7
+ [ 50] Mov dst:reg6, src:Int32(2)
+ [ 60] Jump target:block5
block3:
- [ 68] GetGlobal value_feedback:0, dst:reg6, `i`
- [ 78] JumpLessThanLoopRhsInt32 arith_feedback:0, lhs:reg6, rhs:5, true_target:block1, false_target:block4
+ [ 68] Catch value_feedback:0, dst:reg8
+ [ 70] Mov dst:reg5, src:Undefined
+ [ 80] Mov dst:e~0, src:<Empty>
+ [ 90] Mov dst:e~0, src:reg8
+ [ a0] Mov dst:reg6, src:Int32(0)
+ [ b0] Jump target:block5
block4:
- [ 90] GetGlobal value_feedback:4, dst:reg6, `i`
- [ a0] StrictlyInequalsRhsInt32 arith_feedback:5, dst:reg9, lhs:reg6, rhs:5
- [ b0] MovSrcUndefined dst:reg6
- [ b8] JumpIf condition:reg9, true_target:block14, false_target:block15
+ [ b8] Catch value_feedback:1, dst:reg7
+ [ c0] Mov dst:reg6, src:Int32(1)
block5:
- [ c8] Catch value_feedback:2, dst:reg8
- [ d0] Mov dst:reg7, src:Int32(1)
+ [ d0] Mov dst:reg8, src:reg5
+ [ e0] Mov dst:reg5, src:Undefined
+ [ f0] Mov dst:reg5, src:reg8
+ [ 100] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg6, rhs:0, true_target:block9, false_target:block6
block6:
- [ e0] MovSrcUndefined dst:reg10
- [ e8] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:reg7, rhs:0, true_target:block9, false_target:block10
+ [ 118] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg6, rhs:2, true_target:block7, false_target:block8
block7:
- [ 100] Catch value_feedback:3, dst:reg9
- [ 108] Mov3 c0_dst:e~0, c0_src:reg9, c1_dst:reg10, c1_src:Undefined, c2_dst:reg6, c2_src:reg10
- [ 128] Mov dst:reg7, src:Int32(0)
- [ 138] JumpLoop target:block6
+ [ 130] Jump target:block9
block8:
- [ 140] Mov3 c0_dst:reg9, c0_src:Undefined, c1_dst:reg5, c1_src:reg9, c2_dst:reg7, c2_src:Int32(3)
- [ 160] JumpLoop target:block6
+ [ 138] Throw src:reg7
block9:
- [ 168] Mov dst:reg5, src:reg6
- [ 178] JumpLoop target:block2
+ [ 140] GetGlobal value_feedback:2, dst:reg6, `i`
+ [ 150] PostfixIncrement arith_feedback:2, dst:reg7, src:reg6
+ [ 160] SetGlobal `i`, src:reg6
block10:
- [ 180] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:3, lhs:reg7, rhs:3, true_target:block2, false_target:block11
+ [ 170] GetGlobal value_feedback:3, dst:reg6, `i`
+ [ 180] JumpLessThanLoopRhsInt32 arith_feedback:3, lhs:reg6, rhs:5, true_target:block1, false_target:block11
block11:
- [ 198] JumpStrictlyEqualsRhsInt32 arith_feedback:4, lhs:reg7, rhs:2, true_target:block12, false_target:block13
+ [ 198] GetGlobal value_feedback:4, dst:reg6, `i`
+ [ 1a8] StrictlyInequalsRhsInt32 arith_feedback:4, dst:reg6, lhs:reg6, rhs:5
+ [ 1b8] Mov dst:reg5, src:Undefined
+ [ 1c8] JumpFalse condition:reg6, target:block13
block12:
- [ 1b0] Return value:reg8
+ [ 1d8] Throw src:String("bad")
block13:
- [ 1b8] Throw src:reg8
-
-block14:
- [ 1c0] Throw src:String("bad")
-
-block15:
- [ 1c8] End value:reg6
+ [ 1e0] End value:reg5
Exception handlers:
- [ 100 .. 140] => handler block5
- [ 140 .. 168] => handler block7
+ [ 50 .. 68] => handler block3
+ [ 68 .. b8] => handler block4
diff --git a/Tests/LibJS/Bytecode/expected/function-decl-source-order.txt b/Tests/LibJS/Bytecode/expected/function-decl-source-order.txt
index a7a3eb31602..43c2ebe7364 100644
--- a/Tests/LibJS/Bytecode/expected/function-decl-source-order.txt
+++ b/Tests/LibJS/Bytecode/expected/function-decl-source-order.txt
@@ -1,25 +1,26 @@
-$5559fb0a function-decl-source-order.js:17:1
- Registers: 14
+$581dec1a function-decl-source-order.js:17:1
+ Registers: 13
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `alpha`
- [ 40] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, alpha
- [ 60] GetGlobal value_feedback:4, dst:reg10, `beta`
- [ 70] Call value_feedback:5, call_feedback:1, dst:reg9, callee:reg10, this_value:Undefined, beta
- [ 90] GetGlobal value_feedback:6, dst:reg11, `gamma`
- [ a0] Call value_feedback:7, call_feedback:2, dst:reg10, callee:reg11, this_value:Undefined, gamma
- [ c0] GetGlobal value_feedback:8, dst:reg12, `delta`
- [ d0] Call value_feedback:9, call_feedback:3, dst:reg11, callee:reg12, this_value:Undefined, delta
- [ f0] GetGlobal value_feedback:10, dst:reg13, `dup`
- [ 100] Call value_feedback:11, call_feedback:4, dst:reg12, callee:reg13, this_value:Undefined, dup
- [ 120] Call value_feedback:12, call_feedback:5, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8, reg9, reg10, reg11, reg12]
- [ 158] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `alpha`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined
+ [ 70] GetGlobal value_feedback:4, dst:reg9, `beta`
+ [ 80] Call value_feedback:5, call_feedback:1, dst:reg9, callee:reg9, this_value:Undefined
+ [ a0] GetGlobal value_feedback:6, dst:reg10, `gamma`
+ [ b0] Call value_feedback:7, call_feedback:2, dst:reg10, callee:reg10, this_value:Undefined
+ [ d0] GetGlobal value_feedback:8, dst:reg11, `delta`
+ [ e0] Call value_feedback:9, call_feedback:3, dst:reg11, callee:reg11, this_value:Undefined
+ [ 100] GetGlobal value_feedback:10, dst:reg12, `dup`
+ [ 110] Call value_feedback:11, call_feedback:4, dst:reg12, callee:reg12, this_value:Undefined
+ [ 130] Call value_feedback:12, call_feedback:5, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8, reg9, reg10, reg11, reg12]
+ [ 168] End value:reg5
alpha$ae0829f8 function-decl-source-order.js:5:20
diff --git a/Tests/LibJS/Bytecode/expected/generator-yield-call.txt b/Tests/LibJS/Bytecode/expected/generator-yield-call.txt
index fbb75836d57..0e3f9806cf7 100644
--- a/Tests/LibJS/Bytecode/expected/generator-yield-call.txt
+++ b/Tests/LibJS/Bytecode/expected/generator-yield-call.txt
@@ -1,4 +1,4 @@
-$9ff65435 generator-yield-call.js:9:1
+$92229ee5 generator-yield-call.js:9:1
Registers: 9
Blocks: 1
Constants:
@@ -8,18 +8,19 @@ $9ff65435 generator-yield-call.js:9:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] NewObject dst:reg7
- [ 28] InitObjectLiteralProperty object:reg7, `x`, src:Int32(1), shape_cache_index:0, property_slot:0
- [ 40] CacheObjectShape object:reg7
- [ 50] NewObject dst:reg8
- [ 60] InitObjectLiteralProperty object:reg8, `y`, src:Int32(2), shape_cache_index:1, property_slot:0
- [ 78] CacheObjectShape object:reg8
- [ 88] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[reg7, reg8]
- [ b0] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] NewObject dst:reg7
+ [ 38] InitObjectLiteralProperty object:reg7, `x`, src:Int32(1), shape_cache_index:0, property_slot:0
+ [ 50] CacheObjectShape object:reg7
+ [ 60] NewObject dst:reg8
+ [ 70] InitObjectLiteralProperty object:reg8, `y`, src:Int32(2), shape_cache_index:1, property_slot:0
+ [ 88] CacheObjectShape object:reg8
+ [ 98] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7, reg8]
+ [ c0] End value:reg5
-f$12acc2ab generator-yield-call.js:6:5
+f$1dbc86eb generator-yield-call.js:6:5
Registers: 11
Blocks: 12
Constants:
@@ -32,40 +33,46 @@ block0:
[ 8] Yield continuation_label:block1, value:Undefined
block1:
- [ 18] GetById value_feedback:0, dst:reg8, base:arg0, `x` (a.x)
- [ 30] Yield continuation_label:block2, value:reg8
+ [ 18] GetById value_feedback:0, dst:reg5, base:arg0, `x`
+ [ 30] Yield continuation_label:block2, value:reg5
block2:
- [ 40] Mov dst:reg5, src:reg0
- [ 50] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
- [ 60] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg6, rhs:1, true_target:block3, false_target:block4
+ [ 40] Mov dst:reg6, src:reg0
+ [ 50] GetCompletionFields type_dst:reg7, value_dst:reg8, completion:reg6
+ [ 60] StrictlyEqualsRhsInt32 arith_feedback:0, dst:reg9, lhs:reg7, rhs:1
+ [ 70] JumpIf condition:reg9, true_target:block6, false_target:block3
block3:
- [ 78] GetById value_feedback:1, dst:reg8, base:arg1, `y` (b.y)
- [ 90] Yield continuation_label:block7, value:reg8
+ [ 80] StrictlyEqualsRhsInt32 arith_feedback:1, dst:reg10, lhs:reg7, rhs:5
+ [ 90] JumpIf condition:reg10, true_target:block4, false_target:block5
block4:
- [ a0] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg6, rhs:5, true_target:block5, false_target:block6
+ [ a0] Throw src:reg8
block5:
- [ b8] Throw src:reg7
+ [ a8] Yield value:reg8
block6:
- [ c0] Yield value:reg7
+ [ b8] Mov dst:reg5, src:reg8
+ [ c8] GetById value_feedback:1, dst:reg5, base:arg1, `y`
+ [ e0] Yield continuation_label:block7, value:reg5
block7:
- [ d0] Mov dst:reg7, src:reg0
- [ e0] GetCompletionFields type_dst:reg5, value_dst:reg6, completion:reg7
- [ f0] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:reg5, rhs:1, true_target:block8, false_target:block9
+ [ f0] Mov dst:reg6, src:reg0
+ [ 100] GetCompletionFields type_dst:reg7, value_dst:reg8, completion:reg6
+ [ 110] StrictlyEqualsRhsInt32 arith_feedback:2, dst:reg9, lhs:reg7, rhs:1
+ [ 120] JumpIf condition:reg9, true_target:block11, false_target:block8
block8:
- [ 108] Yield value:Undefined
+ [ 130] StrictlyEqualsRhsInt32 arith_feedback:3, dst:reg10, lhs:reg7, rhs:5
+ [ 140] JumpIf condition:reg10, true_target:block9, false_target:block10
block9:
- [ 118] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg5, rhs:5, true_target:block10, false_target:block11
+ [ 150] Throw src:reg8
block10:
- [ 130] Throw src:reg6
+ [ 158] Yield value:reg8
block11:
- [ 138] Yield value:reg6
+ [ 168] Mov dst:reg5, src:reg8
+ [ 178] Yield value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/generator-yield-finally.txt b/Tests/LibJS/Bytecode/expected/generator-yield-finally.txt
index 9033d765f17..3b919684820 100644
--- a/Tests/LibJS/Bytecode/expected/generator-yield-finally.txt
+++ b/Tests/LibJS/Bytecode/expected/generator-yield-finally.txt
@@ -1,4 +1,4 @@
-$ba9d77cf generator-yield-finally.js:11:1
+$b7d986bf generator-yield-finally.js:11:1
Registers: 7
Blocks: 1
Constants:
@@ -6,14 +6,15 @@ $ba9d77cf generator-yield-finally.js:11:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-f$e6f200ac generator-yield-finally.js:4:5
- Registers: 13
- Blocks: 24
+f$9823b308 generator-yield-finally.js:4:9
+ Registers: 12
+ Blocks: 23
Constants:
[0] = Undefined
[1] = Int32(1)
@@ -27,84 +28,91 @@ block0:
[ 8] Yield continuation_label:block1, value:Undefined
block1:
- [ 18] Jump target:block4
+ [ 18] Yield continuation_label:block2, value:Int32(1)
block2:
- [ 20] Catch value_feedback:0, dst:reg6
- [ 28] Mov dst:reg5, src:Int32(1)
+ [ 28] Mov dst:reg7, src:reg0
+ [ 38] GetCompletionFields type_dst:reg8, value_dst:reg9, completion:reg7
+ [ 48] StrictlyEqualsRhsInt32 arith_feedback:0, dst:reg10, lhs:reg8, rhs:1
+ [ 58] JumpIf condition:reg10, true_target:block6, false_target:block3
block3:
- [ 38] Mov dst:reg10, src:reg1
- [ 48] Yield continuation_label:block15, value:Int32(3)
+ [ 68] StrictlyEqualsRhsInt32 arith_feedback:1, dst:reg11, lhs:reg8, rhs:5
+ [ 78] JumpIf condition:reg11, true_target:block4, false_target:block5
block4:
- [ 58] Yield continuation_label:block5, value:Int32(1)
+ [ 88] Throw src:reg9
block5:
- [ 68] Mov dst:reg7, src:reg0
- [ 78] GetCompletionFields type_dst:reg8, value_dst:reg9, completion:reg7
- [ 88] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg8, rhs:1, true_target:block6, false_target:block7
+ [ 90] Mov dst:reg6, src:reg9
+ [ a0] Mov dst:reg5, src:Int32(2)
+ [ b0] Jump target:block13
block6:
- [ a0] Yield continuation_label:block10, value:Int32(2)
+ [ b8] Mov dst:reg7, src:reg9
+ [ c8] Yield continuation_label:block7, value:Int32(2)
block7:
- [ b0] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg8, rhs:5, true_target:block8, false_target:block9
+ [ d8] Mov dst:reg7, src:reg0
+ [ e8] GetCompletionFields type_dst:reg8, value_dst:reg9, completion:reg7
+ [ f8] StrictlyEqualsRhsInt32 arith_feedback:2, dst:reg10, lhs:reg8, rhs:1
+ [ 108] JumpIf condition:reg10, true_target:block11, false_target:block8
block8:
- [ c8] Throw src:reg9
+ [ 118] StrictlyEqualsRhsInt32 arith_feedback:3, dst:reg11, lhs:reg8, rhs:5
+ [ 128] JumpIf condition:reg11, true_target:block9, false_target:block10
block9:
- [ d0] Mov2 c0_dst:reg6, c0_src:reg9, c1_dst:reg5, c1_src:Int32(2)
- [ e8] JumpLoop target:block3
+ [ 138] Throw src:reg9
block10:
- [ f0] Mov dst:reg9, src:reg0
- [ 100] GetCompletionFields type_dst:reg7, value_dst:reg8, completion:reg9
- [ 110] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:reg7, rhs:1, true_target:block11, false_target:block12
+ [ 140] Mov dst:reg6, src:reg9
+ [ 150] Mov dst:reg5, src:Int32(2)
+ [ 160] Jump target:block13
block11:
- [ 128] Mov dst:reg5, src:Int32(0)
- [ 138] JumpLoop target:block3
+ [ 168] Mov dst:reg7, src:reg9
+ [ 178] Mov dst:reg5, src:Int32(0)
+ [ 188] Jump target:block13
block12:
- [ 140] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg7, rhs:5, true_target:block13, false_target:block14
+ [ 190] Catch value_feedback:0, dst:reg6
+ [ 198] Mov dst:reg5, src:Int32(1)
block13:
- [ 158] Throw src:reg8
+ [ 1a8] Yield continuation_label:block14, value:Int32(3)
block14:
- [ 160] Mov2 c0_dst:reg6, c0_src:reg8, c1_dst:reg5, c1_src:Int32(2)
- [ 178] JumpLoop target:block3
+ [ 1b8] Mov dst:reg7, src:reg0
+ [ 1c8] GetCompletionFields type_dst:reg8, value_dst:reg9, completion:reg7
+ [ 1d8] StrictlyEqualsRhsInt32 arith_feedback:4, dst:reg10, lhs:reg8, rhs:1
+ [ 1e8] JumpIf condition:reg10, true_target:block18, false_target:block15
block15:
- [ 180] Mov2 c0_dst:reg1, c0_src:reg10, c1_dst:reg8, c1_src:reg0
- [ 198] GetCompletionFields type_dst:reg9, value_dst:reg7, completion:reg8
- [ 1a8] JumpStrictlyEqualsRhsInt32 arith_feedback:4, lhs:reg9, rhs:1, true_target:block16, false_target:block17
+ [ 1f8] StrictlyEqualsRhsInt32 arith_feedback:5, dst:reg11, lhs:reg8, rhs:5
+ [ 208] JumpIf condition:reg11, true_target:block16, false_target:block17
block16:
- [ 1c0] JumpStrictlyEqualsRhsInt32 arith_feedback:6, lhs:reg5, rhs:0, true_target:block20, false_target:block21
+ [ 218] Throw src:reg9
block17:
- [ 1d8] JumpStrictlyEqualsRhsInt32 arith_feedback:5, lhs:reg9, rhs:5, true_target:block18, false_target:block19
+ [ 220] Yield value:reg9
block18:
- [ 1f0] Throw src:reg7
+ [ 230] Mov dst:reg7, src:reg9
+ [ 240] JumpStrictlyEqualsRhsInt32 arith_feedback:6, lhs:reg5, rhs:0, true_target:block22, false_target:block19
block19:
- [ 1f8] Yield value:reg7
+ [ 258] JumpStrictlyEqualsRhsInt32 arith_feedback:7, lhs:reg5, rhs:2, true_target:block20, false_target:block21
block20:
- [ 208] Yield value:Undefined
+ [ 270] Yield value:reg6
block21:
- [ 218] JumpStrictlyEqualsRhsInt32 arith_feedback:7, lhs:reg5, rhs:2, true_target:block22, false_target:block23
+ [ 280] Throw src:reg6
block22:
- [ 230] Yield value:reg6
-
-block23:
- [ 240] Throw src:reg6
+ [ 288] Yield value:Undefined
Exception handlers:
- [ 58 .. 180] => handler block2
+ [ 18 .. 190] => handler block12
diff --git a/Tests/LibJS/Bytecode/expected/generator-yield-star.txt b/Tests/LibJS/Bytecode/expected/generator-yield-star.txt
index 26c7c8ab6c5..369ac4a26c1 100644
--- a/Tests/LibJS/Bytecode/expected/generator-yield-star.txt
+++ b/Tests/LibJS/Bytecode/expected/generator-yield-star.txt
@@ -1,18 +1,21 @@
-$6fbbc21a generator-yield-star.js:6:1
+$6cf7d10a generator-yield-star.js:6:1
Registers: 8
Blocks: 1
Constants:
[0] = Undefined
+ [1] = Int32(1)
+ [2] = Int32(2)
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] NewPrimitiveArray dst:reg7, elements:[1, 2]
- [ 38] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[reg7]
- [ 60] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] NewPrimitiveArray dst:reg7, elements:[1, 2]
+ [ 48] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 70] End value:reg5
-f$7baf90a4 generator-yield-star.js:4:5
+f$acc28e9f generator-yield-star.js:4:5
Registers: 21
Blocks: 19
Constants:
@@ -26,73 +29,78 @@ block0:
block1:
[ 18] GetIterator dst_iterator_object:reg8, dst_iterator_next:reg9, dst_iterator_done:reg10, iterable:arg0, fast_array_mode_allowed:false
- [ 38] Mov2 c0_dst:reg6, c0_src:Int32(1), c1_dst:reg7, c1_src:Undefined
+ [ 38] Mov dst:reg6, src:Int32(1)
+ [ 48] Mov dst:reg7, src:Undefined
+ [ 58] Jump target:block2
block2:
- [ 50] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg6, rhs:1, true_target:block5, false_target:block6
+ [ 60] StrictlyEqualsRhsInt32 arith_feedback:0, dst:reg11, lhs:reg6, rhs:1
+ [ 70] JumpIf condition:reg11, true_target:block3, false_target:block6
block3:
- [ 68] Mov dst:reg5, src:reg0
- [ 78] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
- [ 88] JumpLoop target:block2
+ [ 80] Call value_feedback:0, call_feedback:0, dst:reg12, callee:reg9, this_value:reg8, arguments:[reg7]
+ [ a8] ThrowIfNotObject src:reg12
+ [ b0] GetById value_feedback:1, dst:reg13, base:reg12, `done`
+ [ c8] JumpIf condition:reg13, true_target:block4, false_target:block5
block4:
- [ 90] Yield value:Undefined
+ [ d8] GetById value_feedback:2, dst:reg14, base:reg12, `value`
+ [ f0] Jump target:block18
block5:
- [ a0] Call value_feedback:0, call_feedback:0, dst:reg12, callee:reg9, this_value:reg8, arguments:[reg7]
- [ c8] ThrowIfNotObject src:reg12
- [ d0] GetById value_feedback:1, dst:reg13, base:reg12, `done`
- [ e8] JumpIf condition:reg13, true_target:block7, false_target:block8
+ [ f8] YieldIteratorResult continuation_label:block17, value:reg12
block6:
- [ f8] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg6, rhs:5, true_target:block9, false_target:block10
+ [ 108] StrictlyEqualsRhsInt32 arith_feedback:1, dst:reg15, lhs:reg6, rhs:5
+ [ 118] JumpIf condition:reg15, true_target:block7, false_target:block12
block7:
- [ 110] GetById value_feedback:2, dst:reg14, base:reg12, `value`
- [ 128] JumpLoop target:block4
+ [ 128] GetMethod dst:reg16, object:reg8, `throw`
+ [ 140] JumpUndefined condition:reg16, true_target:block11, false_target:block8
block8:
- [ 130] YieldIteratorResult continuation_label:block3, value:reg12
+ [ 150] Call value_feedback:3, call_feedback:1, dst:reg12, callee:reg16, this_value:reg8, arguments:[reg7]
+ [ 178] ThrowIfNotObject src:reg12
+ [ 180] GetById value_feedback:4, dst:reg13, base:reg12, `done`
+ [ 198] JumpIf condition:reg13, true_target:block9, false_target:block10
block9:
- [ 140] GetMethod dst:reg16, object:reg8, `throw`
- [ 158] JumpUndefined condition:reg16, true_target:block12, false_target:block11
+ [ 1a8] GetById value_feedback:5, dst:reg14, base:reg12, `value`
+ [ 1c0] Jump target:block18
block10:
- [ 168] GetMethod dst:reg18, object:reg8, `return`
- [ 180] JumpUndefined condition:reg18, true_target:block15, false_target:block16
+ [ 1c8] YieldIteratorResult continuation_label:block17, value:reg12
block11:
- [ 190] Call value_feedback:3, call_feedback:1, dst:reg12, callee:reg16, this_value:reg8, arguments:[reg7]
- [ 1b8] ThrowIfNotObject src:reg12
- [ 1c0] GetById value_feedback:4, dst:reg13, base:reg12, `done`
- [ 1d8] JumpIf condition:reg13, true_target:block13, false_target:block14
+ [ 1d8] IteratorClose iterator_object:reg8, iterator_next:reg9, iterator_done:reg10, completion_value:Undefined
+ [ 1f8] NewTypeError dst:reg17, yield* protocol violation: iterator must have a throw method
+ [ 208] Throw src:reg17
block12:
- [ 1e8] IteratorClose iterator_object:reg8, iterator_next:reg9, iterator_done:reg10, completion_value:Undefined
- [ 208] NewTypeError dst:reg17, yield* protocol violation: iterator must have a throw method
- [ 218] Throw src:reg17
+ [ 210] GetMethod dst:reg18, object:reg8, `return`
+ [ 228] JumpUndefined condition:reg18, true_target:block13, false_target:block14
block13:
- [ 220] GetById value_feedback:5, dst:reg14, base:reg12, `value`
- [ 238] JumpLoop target:block4
+ [ 238] Yield value:reg7
block14:
- [ 240] YieldIteratorResult continuation_label:block3, value:reg12
+ [ 248] Call value_feedback:6, call_feedback:2, dst:reg19, callee:reg18, this_value:reg8, arguments:[reg7]
+ [ 270] ThrowIfNotObject src:reg19
+ [ 278] GetById value_feedback:7, dst:reg13, base:reg19, `done`
+ [ 290] JumpIf condition:reg13, true_target:block15, false_target:block16
block15:
- [ 250] Yield value:reg7
+ [ 2a0] GetById value_feedback:8, dst:reg20, base:reg19, `value`
+ [ 2b8] Yield value:reg20
block16:
- [ 260] Call value_feedback:6, call_feedback:2, dst:reg19, callee:reg18, this_value:reg8, arguments:[reg7]
- [ 288] ThrowIfNotObject src:reg19
- [ 290] GetById value_feedback:7, dst:reg13, base:reg19, `done`
- [ 2a8] JumpFalse condition:reg13, target:block18
+ [ 2c8] YieldIteratorResult continuation_label:block17, value:reg19
block17:
- [ 2b8] GetById value_feedback:8, dst:reg20, base:reg19, `value`
- [ 2d0] Yield value:reg20
+ [ 2d8] Mov dst:reg5, src:reg0
+ [ 2e8] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
+ [ 2f8] Jump target:block2
block18:
- [ 2e0] YieldIteratorResult continuation_label:block3, value:reg19
+ [ 300] Mov dst:reg5, src:reg14
+ [ 310] Yield value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/generator-yield.txt b/Tests/LibJS/Bytecode/expected/generator-yield.txt
index ff030909bea..86360194195 100644
--- a/Tests/LibJS/Bytecode/expected/generator-yield.txt
+++ b/Tests/LibJS/Bytecode/expected/generator-yield.txt
@@ -1,24 +1,25 @@
-$aa05d16f generator-yield.js:11:1
- Registers: 9
+$47dbec5b generator-yield.js:11:5
+ Registers: 8
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `multi_yield`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, multi_yield
- [ 38] SetGlobal `g`, src:reg5
- [ 48] GetGlobal value_feedback:2, dst:reg6, `g`
- [ 58] GetById value_feedback:3, dst:reg7, base:reg6, `next` (g.next)
- [ 70] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, g.next
- [ 90] GetGlobal value_feedback:5, dst:reg6, `g`
- [ a0] GetById value_feedback:6, dst:reg8, base:reg6, `next` (g.next)
- [ b8] Call value_feedback:7, call_feedback:2, dst:reg7, callee:reg8, this_value:reg6, g.next
- [ d8] End value:reg7
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `multi_yield`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg6, callee:reg6, this_value:Undefined
+ [ 48] SetGlobal `g`, src:reg6
+ [ 58] GetGlobal value_feedback:2, dst:reg6, `g`
+ [ 68] GetById value_feedback:3, dst:reg7, base:reg6, `next`
+ [ 80] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6
+ [ a0] GetGlobal value_feedback:5, dst:reg6, `g`
+ [ b0] GetById value_feedback:6, dst:reg7, base:reg6, `next`
+ [ c8] Call value_feedback:7, call_feedback:2, dst:reg5, callee:reg7, this_value:reg6
+ [ e8] End value:reg5
-multi_yield$ff8f10c7 generator-yield.js:7:5
+multi_yield$0a9ed507 generator-yield.js:7:5
Registers: 10
Blocks: 12
Constants:
@@ -37,33 +38,39 @@ block1:
block2:
[ 28] Mov dst:reg5, src:reg0
[ 38] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
- [ 48] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg6, rhs:1, true_target:block3, false_target:block4
+ [ 48] StrictlyEqualsRhsInt32 arith_feedback:0, dst:reg8, lhs:reg6, rhs:1
+ [ 58] JumpIf condition:reg8, true_target:block6, false_target:block3
block3:
- [ 60] Yield continuation_label:block7, value:Int32(2)
+ [ 68] StrictlyEqualsRhsInt32 arith_feedback:1, dst:reg9, lhs:reg6, rhs:5
+ [ 78] JumpIf condition:reg9, true_target:block4, false_target:block5
block4:
- [ 70] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg6, rhs:5, true_target:block5, false_target:block6
+ [ 88] Throw src:reg7
block5:
- [ 88] Throw src:reg7
+ [ 90] Yield value:reg7
block6:
- [ 90] Yield value:reg7
+ [ a0] Mov dst:reg5, src:reg7
+ [ b0] Yield continuation_label:block7, value:Int32(2)
block7:
- [ a0] Mov dst:reg7, src:reg0
- [ b0] GetCompletionFields type_dst:reg5, value_dst:reg6, completion:reg7
- [ c0] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:reg5, rhs:1, true_target:block8, false_target:block9
+ [ c0] Mov dst:reg5, src:reg0
+ [ d0] GetCompletionFields type_dst:reg6, value_dst:reg7, completion:reg5
+ [ e0] StrictlyEqualsRhsInt32 arith_feedback:2, dst:reg8, lhs:reg6, rhs:1
+ [ f0] JumpIf condition:reg8, true_target:block11, false_target:block8
block8:
- [ d8] Yield value:Undefined
+ [ 100] StrictlyEqualsRhsInt32 arith_feedback:3, dst:reg9, lhs:reg6, rhs:5
+ [ 110] JumpIf condition:reg9, true_target:block9, false_target:block10
block9:
- [ e8] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg5, rhs:5, true_target:block10, false_target:block11
+ [ 120] Throw src:reg7
block10:
- [ 100] Throw src:reg6
+ [ 128] Yield value:reg7
block11:
- [ 108] Yield value:reg6
+ [ 138] Mov dst:reg5, src:reg7
+ [ 148] Yield value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/global-variables.txt b/Tests/LibJS/Bytecode/expected/global-variables.txt
index 2e21a536268..7cfbe20d4ef 100644
--- a/Tests/LibJS/Bytecode/expected/global-variables.txt
+++ b/Tests/LibJS/Bytecode/expected/global-variables.txt
@@ -1,17 +1,19 @@
-$2089ba50 global-variables.js:4:1
+$bf8a56c4 global-variables.js:4:5
Registers: 9
Blocks: 1
Constants:
- [0] = Int32(1)
+ [0] = Undefined
+ [1] = Int32(1)
block0:
[ 0] Enter
- [ 8] SetGlobal `x`, src:Int32(1)
- [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 40] GetGlobal value_feedback:2, dst:reg8, `x`
- [ 50] Call value_feedback:3, call_feedback:0, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 78] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] SetGlobal `x`, src:Int32(1)
+ [ 28] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 38] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 50] GetGlobal value_feedback:2, dst:reg8, `x`
+ [ 60] Call value_feedback:3, call_feedback:0, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 88] End value:reg5
1
diff --git a/Tests/LibJS/Bytecode/expected/if-else-register-lifetime.txt b/Tests/LibJS/Bytecode/expected/if-else-register-lifetime.txt
index 131b46fc329..304ec93cf07 100644
--- a/Tests/LibJS/Bytecode/expected/if-else-register-lifetime.txt
+++ b/Tests/LibJS/Bytecode/expected/if-else-register-lifetime.txt
@@ -1,77 +1,73 @@
-$c02559ef if-else-register-lifetime.js:11:1
+$bd6168df if-else-register-lifetime.js:11:1
Registers: 8
Blocks: 1
Constants:
[0] = Undefined
+ [1] = Int32(1)
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `test`
- [ 18] NewPrimitiveArray dst:reg7, elements:[1]
- [ 30] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, test, arguments:[reg7]
- [ 58] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `test`
+ [ 28] NewPrimitiveArray dst:reg7, elements:[1]
+ [ 40] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 68] End value:reg5
-test$622236ea if-else-register-lifetime.js:2:5
- Registers: 12
- Blocks: 12
+test$4c58d9cb if-else-register-lifetime.js:2:9
+ Registers: 7
+ Blocks: 10
Locals: a~0, i~1, j~2
Constants:
[0] = Undefined
[1] = Int32(1)
[2] = Int32(0)
- [3] = Int32(10)
- [4] = Int32(5)
- [5] = Int32(3)
+ [3] = Int32(5)
+ [4] = Int32(3)
+ [5] = Int32(10)
block0:
[ 0] Enter
- [ 8] MovUndefined3 c0_dst:a~0, c1_dst:i~1, c2_dst:j~2
- [ 18] Mov2 c0_dst:a~0, c0_src:Int32(1), c1_dst:i~1, c1_src:Int32(0)
- [ 30] Jump target:block3
+ [ 8] Mov dst:a~0, src:Undefined
+ [ 18] Mov dst:i~1, src:Undefined
+ [ 28] Mov dst:j~2, src:Undefined
+ [ 38] Mov dst:a~0, src:Int32(1)
+ [ 48] Mov dst:i~1, src:Int32(0)
+ [ 58] Jump target:block8
block1:
- [ 38] Mov dst:j~2, src:Int32(0)
- [ 48] Jump target:block7
+ [ 60] Mov dst:j~2, src:Int32(0)
+ [ 70] Jump target:block6
block2:
- [ 50] PostfixIncrement arith_feedback:1, dst:reg5, src:i~1
+ [ 78] JumpLessThanRhsInt32 arith_feedback:0, lhs:j~2, rhs:5, true_target:block3, false_target:block4
block3:
- [ 60] JumpLessThanLoopRhsInt32 arith_feedback:0, lhs:i~1, rhs:10, true_target:block1, false_target:block4
+ [ 90] Add arith_feedback:1, dst:reg5, lhs:i~1, rhs:j~2
+ [ a0] GetByValue value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0, property:reg5
+ [ c0] PutByValue keyed_feedback:1, base:arg0, property:j~2, src:reg5, kind:Normal
+ [ e0] Jump target:block5
block4:
- [ 78] GetGlobal value_feedback:4, dst:reg7, `parseInt`
- [ 88] Mov dst:reg9, src:a~0
- [ 98] Call value_feedback:5, call_feedback:1, dst:reg5, callee:reg7, this_value:Undefined, parseInt, arguments:[reg9]
- [ c0] Return value:reg5
+ [ e8] GetGlobal value_feedback:1, dst:reg5, `parseInt`
+ [ f8] SubRhsInt32 arith_feedback:2, dst:reg6, lhs:j~2, rhs:3
+ [ 108] GetByValue value_feedback:2, keyed_feedback:2, dst:reg6, base:arg0, property:reg6
+ [ 128] Call value_feedback:3, call_feedback:0, dst:reg5, callee:reg5, this_value:Undefined, arguments:[reg6, Int32(1)]
+ [ 150] PutByValue keyed_feedback:3, base:arg0, property:j~2, src:reg5, kind:Normal
block5:
- [ c8] JumpLessThanRhsInt32 arith_feedback:4, lhs:j~2, rhs:5, true_target:block9, false_target:block10
+ [ 170] Increment arith_feedback:3, dst:j~2
block6:
- [ e0] PostfixIncrement arith_feedback:3, dst:reg5, src:j~2
+ [ 178] JumpLessThanLoopRhsInt32 arith_feedback:4, lhs:j~2, rhs:10, true_target:block2, false_target:block7
block7:
- [ f0] JumpLessThanLoopRhsInt32 arith_feedback:2, lhs:j~2, rhs:10, true_target:block5, false_target:block8
+ [ 190] Increment arith_feedback:5, dst:i~1
block8:
- [ 108] JumpLoop target:block2
+ [ 198] JumpLessThanLoopRhsInt32 arith_feedback:6, lhs:i~1, rhs:10, true_target:block1, false_target:block9
block9:
- [ 110] Mov2 c0_dst:reg6, c0_src:arg0, c1_dst:reg7, c1_src:j~2
- [ 128] Add arith_feedback:5, dst:reg8, lhs:i~1, rhs:j~2
- [ 138] GetByValue value_feedback:0, keyed_feedback:0, dst:reg9, base:arg0, property:reg8 (x[reg8])
- [ 158] PutByValue keyed_feedback:1, base:reg6, property:reg7, src:reg9, kind:Normal (x[reg7])
- [ 178] Jump target:block11
-
-block10:
- [ 180] Mov2 c0_dst:reg9, c0_src:arg0, c1_dst:reg6, c1_src:j~2
- [ 198] GetGlobal value_feedback:1, dst:reg8, `parseInt`
- [ 1a8] SubRhsInt32 arith_feedback:6, dst:reg10, lhs:j~2, rhs:3
- [ 1b8] GetByValue value_feedback:2, keyed_feedback:2, dst:reg11, base:arg0, property:reg10 (x[reg10])
- [ 1d8] Call value_feedback:3, call_feedback:0, dst:reg7, callee:reg8, this_value:Undefined, parseInt, arguments:[reg11, Int32(1)]
- [ 200] PutByValue keyed_feedback:3, base:reg9, property:reg6, src:reg7, kind:Normal (x[reg6])
-
-block11:
- [ 220] JumpLoop target:block6
+ [ 1b0] GetGlobal value_feedback:4, dst:reg5, `parseInt`
+ [ 1c0] Call value_feedback:5, call_feedback:1, dst:reg5, callee:reg5, this_value:Undefined, arguments:[a~0]
+ [ 1e8] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/imported-bindings.txt b/Tests/LibJS/Bytecode/expected/imported-bindings.txt
index 713b5b6c7de..babcab13a4a 100644
--- a/Tests/LibJS/Bytecode/expected/imported-bindings.txt
+++ b/Tests/LibJS/Bytecode/expected/imported-bindings.txt
@@ -1,19 +1,19 @@
-call$c4ed6ba9 imported-bindings.mjs:11:5
- Registers: 8
+call$40c78211 imported-bindings.mjs:11:5
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetImport dst:reg6, `importedRead`, import_index:2
- [ 18] MovSrcUndefined dst:reg7
- [ 20] Call value_feedback:0, call_feedback:0, dst:reg5, callee:reg6, this_value:reg7, importedRead
- [ 40] Return value:reg5
+ [ 8] GetImport dst:reg5, `importedRead`, import_index:2
+ [ 18] Mov dst:reg6, src:Undefined
+ [ 28] Call value_feedback:0, call_feedback:0, dst:reg5, callee:reg5, this_value:reg6
+ [ 48] Return value:reg5
read$75aa611d imported-bindings.mjs:7:5
- Registers: 8
+ Registers: 7
Blocks: 1
block0:
@@ -21,5 +21,5 @@ block0:
[ 8] GetImport dst:reg5, `namespace`, import_index:0
[ 18] Typeof dst:reg5, src:reg5
[ 28] GetImport dst:reg6, `importedValue`, import_index:1
- [ 38] Add arith_feedback:0, dst:reg7, lhs:reg5, rhs:reg6
- [ 48] Return value:reg7
+ [ 38] Add arith_feedback:0, dst:reg5, lhs:reg5, rhs:reg6
+ [ 48] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/indexed-append-guards.txt b/Tests/LibJS/Bytecode/expected/indexed-append-guards.txt
index ae80bb3847c..8fadef6f9bf 100644
--- a/Tests/LibJS/Bytecode/expected/indexed-append-guards.txt
+++ b/Tests/LibJS/Bytecode/expected/indexed-append-guards.txt
@@ -1,127 +1,131 @@
-$8829d5d5 indexed-append-guards.js:16:1
- Registers: 11
+$f1d87d01 indexed-append-guards.js:1:1
+ Registers: 10
Blocks: 7
Constants:
- [0] = String("use strict")
- [1] = Int32(0)
+ [0] = Undefined
+ [1] = String("use strict")
[2] = Int32(1)
- [3] = Undefined
+ [3] = Int32(0)
[4] = String("Indexed object append mutated")
- [5] = String("length")
- [6] = Bool(false)
- [7] = Int32(2)
+ [5] = Int32(2)
+ [6] = String("length")
+ [7] = Bool(false)
[8] = String("Array length changed")
[9] = String("Array append mutated")
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `Object`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `preventExtensions` (Object.preventExtensions)
- [ 30] NewObject dst:reg8
- [ 40] PutByValue keyed_feedback:0, base:reg8, property:Int32(0), src:Int32(1), kind:Own
- [ 60] Call value_feedback:2, call_feedback:0, dst:reg5, callee:reg7, this_value:reg6, Object.preventExtensions, arguments:[reg8]
- [ 88] DynamicInitializeLexicalBinding `object`, src:reg5
- [ 98] GetGlobal value_feedback:3, dst:reg7, `expect_type_error`
- [ a8] NewFunction dst:reg6, shared_function_data_index:0
- [ c0] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:Undefined, expect_type_error, arguments:[reg6]
- [ e8] GetGlobal value_feedback:5, dst:reg7, `object`
- [ f8] GetByValue value_feedback:6, keyed_feedback:1, dst:reg6, base:reg7, property:Int32(1) (object[Int32(1)])
- [ 118] StrictlyInequals arith_feedback:0, dst:reg7, lhs:reg6, rhs:Undefined
- [ 128] MovSrcUndefined dst:reg6
- [ 130] JumpFalse condition:reg7, target:block2
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:String("use strict")
+ [ 28] GetGlobal value_feedback:0, dst:reg6, `Object`
+ [ 38] GetById value_feedback:1, dst:reg7, base:reg6, `preventExtensions`
+ [ 50] NewObject dst:reg8
+ [ 60] PutByValue keyed_feedback:0, base:reg8, property:Int32(0), src:Int32(1), kind:Own
+ [ 80] Call value_feedback:2, call_feedback:0, dst:reg6, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ a8] DynamicInitializeLexicalBinding `object`, src:reg6
+ [ b8] GetGlobal value_feedback:3, dst:reg6, `expect_type_error`
+ [ c8] NewFunction dst:reg7, shared_function_data_index:0
+ [ e0] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 108] GetGlobal value_feedback:5, dst:reg6, `object`
+ [ 118] GetByValue value_feedback:6, keyed_feedback:1, dst:reg6, base:reg6, property:Int32(1)
+ [ 138] StrictlyInequals arith_feedback:0, dst:reg6, lhs:reg6, rhs:Undefined
+ [ 148] Mov dst:reg5, src:Undefined
+ [ 158] JumpFalse condition:reg6, target:block2
block1:
- [ 140] GetGlobal value_feedback:7, dst:reg9, `Error`
- [ 150] CallConstruct value_feedback:8, call_feedback:2, dst:reg8, callee:reg9, Error, arguments:[String("Indexed object append mutated")]
- [ 178] Throw src:reg8
+ [ 168] GetGlobal value_feedback:7, dst:reg6, `Error`
+ [ 178] CallConstruct value_feedback:8, call_feedback:2, dst:reg6, callee:reg6, arguments:[String("Indexed object append mutated")]
+ [ 1a0] Throw src:reg6
block2:
- [ 180] NewPrimitiveArray dst:reg5, elements:[1, 2]
- [ 1a0] DynamicInitializeLexicalBinding `array`, src:reg5
- [ 1b0] GetGlobal value_feedback:9, dst:reg7, `Object`
- [ 1c0] GetById value_feedback:10, dst:reg8, base:reg7, `defineProperty` (Object.defineProperty)
- [ 1d8] GetGlobal value_feedback:11, dst:reg9, `array`
- [ 1e8] NewObject dst:reg10
- [ 1f8] InitObjectLiteralProperty object:reg10, `writable`, src:Bool(false), shape_cache_index:0, property_slot:0
- [ 210] CacheObjectShape object:reg10
- [ 220] Call value_feedback:12, call_feedback:3, dst:reg5, callee:reg8, this_value:reg7, Object.defineProperty, arguments:[reg9, String("length"), reg10]
- [ 250] GetGlobal value_feedback:13, dst:reg8, `expect_type_error`
- [ 260] NewFunction dst:reg7, shared_function_data_index:1
- [ 278] Call value_feedback:14, call_feedback:4, dst:reg6, callee:reg8, this_value:Undefined, expect_type_error, arguments:[reg7]
- [ 2a0] GetGlobal value_feedback:15, dst:reg5, `array`
- [ 2b0] GetLength value_feedback:16, keyed_feedback:2, dst:reg8, base:reg5 (array.length)
- [ 2c8] StrictlyInequalsRhsInt32 arith_feedback:1, dst:reg5, lhs:reg8, rhs:2
- [ 2d8] MovSrcUndefined dst:reg8
- [ 2e0] JumpFalse condition:reg5, target:block4
+ [ 1a8] NewPrimitiveArray dst:reg6, elements:[1, 2]
+ [ 1c8] DynamicInitializeLexicalBinding `array`, src:reg6
+ [ 1d8] GetGlobal value_feedback:9, dst:reg6, `Object`
+ [ 1e8] GetById value_feedback:10, dst:reg7, base:reg6, `defineProperty`
+ [ 200] GetGlobal value_feedback:11, dst:reg8, `array`
+ [ 210] NewObject dst:reg9
+ [ 220] InitObjectLiteralProperty object:reg9, `writable`, src:Bool(false), shape_cache_index:0, property_slot:0
+ [ 238] CacheObjectShape object:reg9
+ [ 248] Call value_feedback:12, call_feedback:3, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8, String("length"), reg9]
+ [ 278] GetGlobal value_feedback:13, dst:reg6, `expect_type_error`
+ [ 288] NewFunction dst:reg7, shared_function_data_index:1
+ [ 2a0] Call value_feedback:14, call_feedback:4, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 2c8] GetGlobal value_feedback:15, dst:reg6, `array`
+ [ 2d8] GetLength value_feedback:16, keyed_feedback:2, dst:reg6, base:reg6
+ [ 2f0] StrictlyInequalsRhsInt32 arith_feedback:1, dst:reg6, lhs:reg6, rhs:2
+ [ 300] Mov dst:reg5, src:Undefined
+ [ 310] JumpFalse condition:reg6, target:block4
block3:
- [ 2f0] GetGlobal value_feedback:17, dst:reg10, `Error`
- [ 300] CallConstruct value_feedback:18, call_feedback:5, dst:reg7, callee:reg10, Error, arguments:[String("Array length changed")]
- [ 328] Throw src:reg7
+ [ 320] GetGlobal value_feedback:17, dst:reg6, `Error`
+ [ 330] CallConstruct value_feedback:18, call_feedback:5, dst:reg6, callee:reg6, arguments:[String("Array length changed")]
+ [ 358] Throw src:reg6
block4:
- [ 330] GetGlobal value_feedback:19, dst:reg6, `array`
- [ 340] GetByValue value_feedback:20, keyed_feedback:3, dst:reg5, base:reg6, property:Int32(2) (array[Int32(2)])
- [ 360] StrictlyInequals arith_feedback:2, dst:reg6, lhs:reg5, rhs:Undefined
- [ 370] MovSrcUndefined dst:reg5
- [ 378] JumpFalse condition:reg6, target:block6
+ [ 360] GetGlobal value_feedback:19, dst:reg6, `array`
+ [ 370] GetByValue value_feedback:20, keyed_feedback:3, dst:reg6, base:reg6, property:Int32(2)
+ [ 390] StrictlyInequals arith_feedback:2, dst:reg6, lhs:reg6, rhs:Undefined
+ [ 3a0] Mov dst:reg5, src:Undefined
+ [ 3b0] JumpFalse condition:reg6, target:block6
block5:
- [ 388] GetGlobal value_feedback:21, dst:reg10, `Error`
- [ 398] CallConstruct value_feedback:22, call_feedback:6, dst:reg7, callee:reg10, Error, arguments:[String("Array append mutated")]
- [ 3c0] Throw src:reg7
+ [ 3c0] GetGlobal value_feedback:21, dst:reg6, `Error`
+ [ 3d0] CallConstruct value_feedback:22, call_feedback:6, dst:reg6, callee:reg6, arguments:[String("Array append mutated")]
+ [ 3f8] Throw src:reg6
block6:
- [ 3c8] End value:reg5
+ [ 400] End value:reg5
-expect_type_error$fc915998 indexed-append-guards.js:4:5
- Registers: 9
+expect_type_error$5a5dde14 indexed-append-guards.js:4:9
+ Registers: 7
Blocks: 8
- Locals: error~0, did_throw~1
+ Locals: did_throw~0, error~1
Constants:
[0] = Bool(false)
- [1] = Bool(true)
- [2] = Undefined
- [3] = String("Expected TypeError")
+ [1] = Undefined
+ [2] = <Empty>
+ [3] = Bool(true)
+ [4] = String("Expected TypeError")
block0:
[ 0] Enter
- [ 8] Mov dst:did_throw~1, src:Bool(false)
- [ 18] Jump target:block5
+ [ 8] Mov dst:did_throw~0, src:Bool(false)
block1:
- [ 20] Catch value_feedback:0, dst:reg5
- [ 28] Mov dst:error~0, src:reg5
- [ 38] GetGlobal value_feedback:1, dst:reg7, `TypeError`
- [ 48] InstanceOf dst:reg8, lhs:error~0, rhs:reg7
- [ 58] Not dst:reg6, src:reg8
- [ 68] JumpFalse condition:reg6, target:block3
+ [ 18] Call value_feedback:0, call_feedback:0, dst:reg5, callee:arg0, this_value:Undefined
+ [ 38] Jump target:block5
block2:
- [ 78] Throw src:error~0
+ [ 40] Catch value_feedback:1, dst:reg5
+ [ 48] Mov dst:error~1, src:<Empty>
+ [ 58] Mov dst:error~1, src:reg5
+ [ 68] GetGlobal value_feedback:2, dst:reg6, `TypeError`
+ [ 78] InstanceOf dst:reg6, lhs:error~1, rhs:reg6
+ [ 88] Not dst:reg6, src:reg6
+ [ 98] JumpFalse condition:reg6, target:block4
block3:
- [ 80] Mov dst:did_throw~1, src:Bool(true)
+ [ a8] Throw src:error~1
block4:
- [ 90] Not dst:reg5, src:did_throw~1
- [ a0] JumpIf condition:reg5, true_target:block6, false_target:block7
+ [ b0] Mov dst:did_throw~0, src:Bool(true)
+ [ c0] Jump target:block5
block5:
- [ b0] Call value_feedback:2, call_feedback:0, dst:reg5, callee:arg0, this_value:Undefined, callback
- [ d0] JumpLoop target:block4
+ [ c8] Not dst:reg5, src:did_throw~0
+ [ d8] JumpFalse condition:reg5, target:block7
block6:
- [ d8] GetGlobal value_feedback:3, dst:reg8, `Error`
- [ e8] CallConstruct value_feedback:4, call_feedback:1, dst:reg6, callee:reg8, Error, arguments:[String("Expected TypeError")]
- [ 110] Throw src:reg6
+ [ e8] GetGlobal value_feedback:3, dst:reg5, `Error`
+ [ f8] CallConstruct value_feedback:4, call_feedback:1, dst:reg5, callee:reg5, arguments:[String("Expected TypeError")]
+ [ 120] Throw src:reg5
block7:
- [ 118] End value:Undefined
+ [ 128] End value:Undefined
Exception handlers:
- [ b0 .. d8] => handler block1
+ [ 18 .. 40] => handler block2
$e425a642 indexed-append-guards.js:18:5
@@ -135,12 +139,12 @@ $e425a642 indexed-append-guards.js:18:5
block0:
[ 0] Enter
[ 8] GetGlobal value_feedback:0, dst:reg5, `object`
- [ 18] PutByValue keyed_feedback:0, base:reg5, property:Int32(1), src:Int32(2), kind:Normal (object[Int32(1)])
+ [ 18] PutByValue keyed_feedback:0, base:reg5, property:Int32(1), src:Int32(2), kind:Normal
[ 38] End value:Undefined
$f99f4d22 indexed-append-guards.js:26:5
- Registers: 8
+ Registers: 7
Blocks: 1
Constants:
[0] = Int32(3)
@@ -150,6 +154,6 @@ block0:
[ 0] Enter
[ 8] GetGlobal value_feedback:0, dst:reg5, `array`
[ 18] GetGlobal value_feedback:1, dst:reg6, `array`
- [ 28] GetLength value_feedback:2, keyed_feedback:0, dst:reg7, base:reg6 (array.length)
- [ 40] PutByValue keyed_feedback:1, base:reg5, property:reg7, src:Int32(3), kind:Normal (array[reg7])
+ [ 28] GetLength value_feedback:2, keyed_feedback:0, dst:reg6, base:reg6
+ [ 40] PutByValue keyed_feedback:1, base:reg5, property:reg6, src:Int32(3), kind:Normal
[ 60] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/int32-binary-specializations.txt b/Tests/LibJS/Bytecode/expected/int32-binary-specializations.txt
index 414fe88e41d..f8b83734c29 100644
--- a/Tests/LibJS/Bytecode/expected/int32-binary-specializations.txt
+++ b/Tests/LibJS/Bytecode/expected/int32-binary-specializations.txt
@@ -1,4 +1,4 @@
-$e5c27a28 int32-binary-specializations.js:20:1
+$e8866b38 int32-binary-specializations.js:20:1
Registers: 7
Blocks: 1
Constants:
@@ -7,9 +7,10 @@ $e5c27a28 int32-binary-specializations.js:20:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `int32_binary_specializations`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, int32_binary_specializations, arguments:[Int32(8)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `int32_binary_specializations`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(8)]
+ [ 50] End value:reg5
int32_binary_specializations$61f68510 int32-binary-specializations.js:2:5
diff --git a/Tests/LibJS/Bytecode/expected/int32-comparison-specializations.txt b/Tests/LibJS/Bytecode/expected/int32-comparison-specializations.txt
index be38ca13c55..a0e2cecfdd9 100644
--- a/Tests/LibJS/Bytecode/expected/int32-comparison-specializations.txt
+++ b/Tests/LibJS/Bytecode/expected/int32-comparison-specializations.txt
@@ -1,5 +1,5 @@
-$6e98afa7 int32-comparison-specializations.js:35:1
- Registers: 8
+$6bd4be97 int32-comparison-specializations.js:35:1
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
@@ -7,11 +7,12 @@ $6e98afa7 int32-comparison-specializations.js:35:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `comparison_results`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, comparison_results, arguments:[Int32(1)]
- [ 40] GetGlobal value_feedback:2, dst:reg7, `comparison_jumps`
- [ 50] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, comparison_jumps, arguments:[Int32(1)]
- [ 78] End value:reg6
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `comparison_results`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(1)]
+ [ 50] GetGlobal value_feedback:2, dst:reg6, `comparison_jumps`
+ [ 60] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(1)]
+ [ 88] End value:reg5
comparison_results$4f7ca3ae int32-comparison-specializations.js:2:5
@@ -34,8 +35,8 @@ block0:
[ b8] Return value:reg13
-comparison_jumps$6bad112e int32-comparison-specializations.js:15:5
- Registers: 8
+comparison_jumps$cd6069df int32-comparison-specializations.js:15:9
+ Registers: 6
Blocks: 17
Locals: result~0
Constants:
@@ -55,65 +56,49 @@ block0:
[ 18] JumpLessThanRhsInt32 arith_feedback:0, lhs:arg0, rhs:2, true_target:block1, false_target:block2
block1:
- [ 30] Mov dst:reg6, src:result~0
- [ 40] AddRhsInt32 arith_feedback:1, dst:reg7, lhs:reg6, rhs:1
- [ 50] Mov dst:result~0, src:reg7
+ [ 30] AddRhsInt32 arith_feedback:1, dst:result~0, lhs:result~0, rhs:1
block2:
- [ 60] JumpLessThanEqualsRhsInt32 arith_feedback:2, lhs:arg0, rhs:2, true_target:block3, false_target:block4
+ [ 40] JumpLessThanEqualsRhsInt32 arith_feedback:2, lhs:arg0, rhs:2, true_target:block3, false_target:block4
block3:
- [ 78] Mov dst:reg7, src:result~0
- [ 88] AddRhsInt32 arith_feedback:3, dst:reg6, lhs:reg7, rhs:2
- [ 98] Mov dst:result~0, src:reg6
+ [ 58] AddRhsInt32 arith_feedback:3, dst:result~0, lhs:result~0, rhs:2
block4:
- [ a8] JumpGreaterThanRhsInt32 arith_feedback:4, lhs:arg0, rhs:2, true_target:block5, false_target:block6
+ [ 68] JumpGreaterThanRhsInt32 arith_feedback:4, lhs:arg0, rhs:2, true_target:block5, false_target:block6
block5:
- [ c0] Mov dst:reg6, src:result~0
- [ d0] AddRhsInt32 arith_feedback:5, dst:reg7, lhs:reg6, rhs:4
- [ e0] Mov dst:result~0, src:reg7
+ [ 80] AddRhsInt32 arith_feedback:5, dst:result~0, lhs:result~0, rhs:4
block6:
- [ f0] JumpGreaterThanEqualsRhsInt32 arith_feedback:6, lhs:arg0, rhs:2, true_target:block7, false_target:block8
+ [ 90] JumpGreaterThanEqualsRhsInt32 arith_feedback:6, lhs:arg0, rhs:2, true_target:block7, false_target:block8
block7:
- [ 108] Mov dst:reg7, src:result~0
- [ 118] AddRhsInt32 arith_feedback:7, dst:reg6, lhs:reg7, rhs:8
- [ 128] Mov dst:result~0, src:reg6
+ [ a8] AddRhsInt32 arith_feedback:7, dst:result~0, lhs:result~0, rhs:8
block8:
- [ 138] JumpStrictlyEqualsRhsInt32 arith_feedback:8, lhs:arg0, rhs:2, true_target:block9, false_target:block10
+ [ b8] JumpStrictlyEqualsRhsInt32 arith_feedback:8, lhs:arg0, rhs:2, true_target:block9, false_target:block10
block9:
- [ 150] Mov dst:reg6, src:result~0
- [ 160] AddRhsInt32 arith_feedback:9, dst:reg7, lhs:reg6, rhs:16
- [ 170] Mov dst:result~0, src:reg7
+ [ d0] AddRhsInt32 arith_feedback:9, dst:result~0, lhs:result~0, rhs:16
block10:
- [ 180] JumpStrictlyInequalsRhsInt32 arith_feedback:10, lhs:arg0, rhs:2, true_target:block11, false_target:block12
+ [ e0] JumpStrictlyInequalsRhsInt32 arith_feedback:10, lhs:arg0, rhs:2, true_target:block11, false_target:block12
block11:
- [ 198] Mov dst:reg7, src:result~0
- [ 1a8] AddRhsInt32 arith_feedback:11, dst:reg6, lhs:reg7, rhs:32
- [ 1b8] Mov dst:result~0, src:reg6
+ [ f8] AddRhsInt32 arith_feedback:11, dst:result~0, lhs:result~0, rhs:32
block12:
- [ 1c8] JumpLooselyEqualsRhsInt32 arith_feedback:12, lhs:arg0, rhs:2, true_target:block13, false_target:block14
+ [ 108] JumpLooselyEqualsRhsInt32 arith_feedback:12, lhs:arg0, rhs:2, true_target:block13, false_target:block14
block13:
- [ 1e0] Mov dst:reg6, src:result~0
- [ 1f0] AddRhsInt32 arith_feedback:13, dst:reg7, lhs:reg6, rhs:64
- [ 200] Mov dst:result~0, src:reg7
+ [ 120] AddRhsInt32 arith_feedback:13, dst:result~0, lhs:result~0, rhs:64
block14:
- [ 210] JumpLooselyInequalsRhsInt32 arith_feedback:14, lhs:arg0, rhs:2, true_target:block15, false_target:block16
+ [ 130] JumpLooselyInequalsRhsInt32 arith_feedback:14, lhs:arg0, rhs:2, true_target:block15, false_target:block16
block15:
- [ 228] Mov dst:reg7, src:result~0
- [ 238] AddRhsInt32 arith_feedback:15, dst:reg6, lhs:reg7, rhs:128
- [ 248] Mov dst:result~0, src:reg6
+ [ 148] AddRhsInt32 arith_feedback:15, dst:result~0, lhs:result~0, rhs:128
block16:
- [ 258] Return value:result~0
+ [ 158] Return value:result~0
diff --git a/Tests/LibJS/Bytecode/expected/invalid-lhs-assignment-no-dead-code.txt b/Tests/LibJS/Bytecode/expected/invalid-lhs-assignment-no-dead-code.txt
index 4c27875f722..f3c11a8d5fa 100644
--- a/Tests/LibJS/Bytecode/expected/invalid-lhs-assignment-no-dead-code.txt
+++ b/Tests/LibJS/Bytecode/expected/invalid-lhs-assignment-no-dead-code.txt
@@ -1,29 +1,30 @@
-$b8c00624 invalid-lhs-assignment-no-dead-code.js:8:1
- Registers: 10
- Blocks: 3
+$bb83f734 invalid-lhs-assignment-no-dead-code.js:8:1
+ Registers: 8
+ Blocks: 4
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:reg5
- [ 10] Jump target:block2
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:Undefined
block1:
- [ 18] Catch value_feedback:0, dst:reg6
- [ 20] Mov2 c0_dst:reg7, c0_src:Undefined, c1_dst:reg5, c1_src:reg7
- [ 38] End value:reg5
+ [ 28] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 38] NewFunction dst:reg7, shared_function_data_index:0
+ [ 50] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 78] Jump target:block3
block2:
- [ 40] MovSrcUndefined dst:reg6
- [ 48] GetGlobal value_feedback:1, dst:reg8, `f`
- [ 58] NewFunction dst:reg9, shared_function_data_index:0
- [ 70] Call value_feedback:2, call_feedback:0, dst:reg7, callee:reg8, this_value:Undefined, f, arguments:[reg9]
- [ 98] Mov2 c0_dst:reg6, c0_src:reg7, c1_dst:reg5, c1_src:reg6
- [ b0] End value:reg5
+ [ 80] Catch value_feedback:2, dst:reg6
+ [ 88] Mov dst:reg5, src:Undefined
+ [ 98] Jump target:block3
+
+block3:
+ [ a0] End value:reg5
Exception handlers:
- [ 40 .. b8] => handler block1
+ [ 28 .. 80] => handler block2
f$cb5318f8 invalid-lhs-assignment-no-dead-code.js:5:6
@@ -31,10 +32,11 @@ f$cb5318f8 invalid-lhs-assignment-no-dead-code.js:5:6
Blocks: 1
Constants:
[0] = Undefined
+ [1] = String("foo")
block0:
[ 0] Enter
- [ 8] Call value_feedback:0, call_feedback:0, dst:reg5, callee:arg0, this_value:Undefined, x
+ [ 8] Call value_feedback:0, call_feedback:0, dst:reg5, callee:arg0, this_value:Undefined
[ 28] NewReferenceError dst:reg5, Invalid left-hand side in assignment
[ 38] Throw src:reg5
diff --git a/Tests/LibJS/Bytecode/expected/invalid-lhs-forin-no-dead-code.txt b/Tests/LibJS/Bytecode/expected/invalid-lhs-forin-no-dead-code.txt
index ec2a8edfdff..8d9a0a4b031 100644
--- a/Tests/LibJS/Bytecode/expected/invalid-lhs-forin-no-dead-code.txt
+++ b/Tests/LibJS/Bytecode/expected/invalid-lhs-forin-no-dead-code.txt
@@ -1,33 +1,28 @@
-$067de6f5 invalid-lhs-forin-no-dead-code.js:6:6
- Registers: 14
- Blocks: 6
+$87dfdf7d invalid-lhs-forin-no-dead-code.js:6:6
+ Registers: 13
+ Blocks: 4
Constants:
[0] = Undefined
[1] = Int32(0)
block0:
[ 0] Enter
- [ 8] NewArray dst:reg5
- [ 18] MovSrcUndefined dst:reg9
- [ 20] JumpNullish condition:reg5, true_target:block3, false_target:block4
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] NewArray dst:reg6
+ [ 28] Mov dst:reg5, src:Undefined
+ [ 38] JumpNullish condition:reg6, true_target:block3, false_target:block1
block1:
- [ 30] End value:reg9
+ [ 48] GetObjectPropertyIterator dst_keys:reg8, dst_receiver:reg7, object:reg6
+ [ 60] Mov dst:reg9, src:Int32(0)
+ [ 70] ObjectPropertyIteratorNext dst_value:reg10, dst_done:reg11, receiver:reg7, keys:reg8, cursor:reg9
+ [ 88] JumpTrue condition:reg11, target:block3
block2:
- [ 38] ObjectPropertyIteratorNext dst_value:reg10, dst_done:reg11, receiver:reg6, keys:reg7, cursor:reg8
- [ 50] JumpIfLoop condition:reg11, true_target:block1, false_target:block5
-
-block3:
- [ 60] End value:reg9
-
-block4:
- [ 68] GetObjectPropertyIterator dst_keys:reg7, dst_receiver:reg6, object:reg5
- [ 80] Mov dst:reg8, src:Int32(0)
- [ 90] JumpLoop target:block2
-
-block5:
- [ 98] GetGlobal value_feedback:0, dst:reg13, `f`
- [ a8] Call value_feedback:1, call_feedback:0, dst:reg12, callee:reg13, this_value:Undefined, f
+ [ 98] GetGlobal value_feedback:0, dst:reg12, `f`
+ [ a8] Call value_feedback:1, call_feedback:0, dst:reg12, callee:reg12, this_value:Undefined
[ c8] NewReferenceError dst:reg12, Invalid left-hand side in assignment
[ d8] Throw src:reg12
+
+block3:
+ [ e0] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/lexical-env-teardown.txt b/Tests/LibJS/Bytecode/expected/lexical-env-teardown.txt
index 30b53340ebb..8bba4e50bcd 100644
--- a/Tests/LibJS/Bytecode/expected/lexical-env-teardown.txt
+++ b/Tests/LibJS/Bytecode/expected/lexical-env-teardown.txt
@@ -1,5 +1,5 @@
-$660d7780 lexical-env-teardown.js:13:1
- Registers: 11
+$63498670 lexical-env-teardown.js:13:1
+ Registers: 9
Blocks: 1
Constants:
[0] = Undefined
@@ -7,202 +7,190 @@ $660d7780 lexical-env-teardown.js:13:1
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 20] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 38] GetGlobal value_feedback:2, dst:reg9, `withTeardown`
- [ 48] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, withTeardown
- [ 68] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 90] GetGlobal value_feedback:5, dst:reg6, `console`
- [ a0] GetById value_feedback:6, dst:reg8, base:reg6, `log` (console.log)
- [ b8] GetGlobal value_feedback:7, dst:reg10, `blockTeardown`
- [ c8] Call value_feedback:8, call_feedback:2, dst:reg9, callee:reg10, this_value:Undefined, blockTeardown
- [ e8] Call value_feedback:9, call_feedback:3, dst:reg7, callee:reg8, this_value:reg6, console.log, arguments:[reg9]
- [ 110] GetGlobal value_feedback:10, dst:reg8, `console`
- [ 120] GetById value_feedback:11, dst:reg6, base:reg8, `log` (console.log)
- [ 138] GetGlobal value_feedback:12, dst:reg10, `forInTeardown`
- [ 148] Call value_feedback:13, call_feedback:4, dst:reg9, callee:reg10, this_value:Undefined, forInTeardown
- [ 168] Call value_feedback:14, call_feedback:5, dst:reg5, callee:reg6, this_value:reg8, console.log, arguments:[reg9]
- [ 190] GetGlobal value_feedback:15, dst:reg6, `console`
- [ 1a0] GetById value_feedback:16, dst:reg8, base:reg6, `log` (console.log)
- [ 1b8] GetGlobal value_feedback:17, dst:reg10, `forOfTeardown`
- [ 1c8] Call value_feedback:18, call_feedback:6, dst:reg9, callee:reg10, this_value:Undefined, forOfTeardown
- [ 1e8] Call value_feedback:19, call_feedback:7, dst:reg7, callee:reg8, this_value:reg6, console.log, arguments:[reg9]
- [ 210] GetGlobal value_feedback:20, dst:reg8, `console`
- [ 220] GetById value_feedback:21, dst:reg6, base:reg8, `log` (console.log)
- [ 238] GetGlobal value_feedback:22, dst:reg10, `catchTeardown`
- [ 248] Call value_feedback:23, call_feedback:8, dst:reg9, callee:reg10, this_value:Undefined, catchTeardown
- [ 268] Call value_feedback:24, call_feedback:9, dst:reg5, callee:reg6, this_value:reg8, console.log, arguments:[reg9]
- [ 290] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
- [ 2a8] CreateVariable `myName`, is_immutable:true, is_global:false, is_strict:false
- [ 2b8] NewFunction dst:reg6, shared_function_data_index:0
- [ 2d0] InitializeLexicalBinding `myName`, src:reg6
- [ 2e8] SetLexicalEnvironment environment:reg4
- [ 2f0] SetGlobal `namedFn`, src:reg6
- [ 300] GetGlobal value_feedback:25, dst:reg7, `console`
- [ 310] GetById value_feedback:26, dst:reg8, base:reg7, `log` (console.log)
- [ 328] GetGlobal value_feedback:27, dst:reg10, `namedFn`
- [ 338] Call value_feedback:28, call_feedback:10, dst:reg9, callee:reg10, this_value:Undefined, namedFn
- [ 358] Call value_feedback:29, call_feedback:11, dst:reg6, callee:reg8, this_value:reg7, console.log, arguments:[reg9]
- [ 380] End value:reg6
-
-
-withTeardown$f8b3e64d lexical-env-teardown.js:7:5
- Registers: 10
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 30] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 48] GetGlobal value_feedback:2, dst:reg8, `withTeardown`
+ [ 58] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined
+ [ 78] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ a0] GetGlobal value_feedback:5, dst:reg6, `console`
+ [ b0] GetById value_feedback:6, dst:reg7, base:reg6, `log`
+ [ c8] GetGlobal value_feedback:7, dst:reg8, `blockTeardown`
+ [ d8] Call value_feedback:8, call_feedback:2, dst:reg8, callee:reg8, this_value:Undefined
+ [ f8] Call value_feedback:9, call_feedback:3, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 120] GetGlobal value_feedback:10, dst:reg6, `console`
+ [ 130] GetById value_feedback:11, dst:reg7, base:reg6, `log`
+ [ 148] GetGlobal value_feedback:12, dst:reg8, `forInTeardown`
+ [ 158] Call value_feedback:13, call_feedback:4, dst:reg8, callee:reg8, this_value:Undefined
+ [ 178] Call value_feedback:14, call_feedback:5, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 1a0] GetGlobal value_feedback:15, dst:reg6, `console`
+ [ 1b0] GetById value_feedback:16, dst:reg7, base:reg6, `log`
+ [ 1c8] GetGlobal value_feedback:17, dst:reg8, `forOfTeardown`
+ [ 1d8] Call value_feedback:18, call_feedback:6, dst:reg8, callee:reg8, this_value:Undefined
+ [ 1f8] Call value_feedback:19, call_feedback:7, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 220] GetGlobal value_feedback:20, dst:reg6, `console`
+ [ 230] GetById value_feedback:21, dst:reg7, base:reg6, `log`
+ [ 248] GetGlobal value_feedback:22, dst:reg8, `catchTeardown`
+ [ 258] Call value_feedback:23, call_feedback:8, dst:reg8, callee:reg8, this_value:Undefined
+ [ 278] Call value_feedback:24, call_feedback:9, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 2a0] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 2b8] CreateVariable `myName`, is_immutable:true, is_global:false, is_strict:false
+ [ 2c8] NewFunction dst:reg6, shared_function_data_index:0
+ [ 2e0] InitializeLexicalBinding `myName`, src:reg6
+ [ 2f8] SetLexicalEnvironment environment:reg4
+ [ 300] SetGlobal `namedFn`, src:reg6
+ [ 310] GetGlobal value_feedback:25, dst:reg6, `console`
+ [ 320] GetById value_feedback:26, dst:reg7, base:reg6, `log`
+ [ 338] GetGlobal value_feedback:27, dst:reg8, `namedFn`
+ [ 348] Call value_feedback:28, call_feedback:10, dst:reg8, callee:reg8, this_value:Undefined
+ [ 368] Call value_feedback:29, call_feedback:11, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 390] End value:reg5
+
+
+withTeardown$fdddfea9 lexical-env-teardown.js:7:9
+ Registers: 9
Blocks: 1
Locals: inner~0
Constants:
[0] = Int32(1)
[1] = Int32(10)
- [2] = Undefined
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `outer`, is_immutable:false, is_global:false, is_strict:false
- [ 38] InitializeLexicalBinding `outer`, src:Int32(1)
- [ 50] NewObject dst:reg6
- [ 60] InitObjectLiteralProperty object:reg6, `x`, src:Int32(10), shape_cache_index:0, property_slot:0
- [ 78] CacheObjectShape object:reg6
- [ 88] EnterObjectEnvironment dst:reg7, object:reg6
- [ 98] DynamicGetBinding value_feedback:0, dst:reg8, `x`
- [ a8] DynamicGetBinding value_feedback:1, dst:reg9, `outer`
- [ b8] Add arith_feedback:0, dst:inner~0, lhs:reg8, rhs:reg9
- [ c8] SetLexicalEnvironment environment:reg5
- [ d0] GetBinding value_feedback:2, dst:reg6, `outer`
- [ e8] Return value:reg6
-
-
-blockTeardown$3857bd78 lexical-env-teardown.js:17:5
+ [ 8] CreateVariable `outer`, is_immutable:false, is_global:false, is_strict:false
+ [ 18] GetLexicalEnvironment dst:reg4
+ [ 20] InitializeLexicalBinding `outer`, src:Int32(1)
+ [ 38] NewObject dst:reg5
+ [ 48] InitObjectLiteralProperty object:reg5, `x`, src:Int32(10), shape_cache_index:0, property_slot:0
+ [ 60] CacheObjectShape object:reg5
+ [ 70] EnterObjectEnvironment dst:reg6, object:reg5
+ [ 80] DynamicGetBinding value_feedback:0, dst:reg7, `x`
+ [ 90] DynamicGetBinding value_feedback:1, dst:reg8, `outer`
+ [ a0] Add arith_feedback:0, dst:inner~0, lhs:reg7, rhs:reg8
+ [ b0] SetLexicalEnvironment environment:reg4
+ [ b8] GetBinding value_feedback:2, dst:reg5, `outer`
+ [ d0] Return value:reg5
+
+
+blockTeardown$14c2496c lexical-env-teardown.js:17:9
Registers: 5
Blocks: 1
- Locals: inner~0, outer~1
+ Locals: outer~0, inner~1
Constants:
[0] = Int32(2)
[1] = Int32(3)
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:outer~1, c0_src:Int32(2), c1_dst:inner~0, c1_src:Int32(3)
- [ 20] Return value:outer~1
+ [ 8] Mov dst:outer~0, src:Int32(2)
+ [ 18] Mov dst:inner~1, src:Int32(3)
+ [ 28] Return value:outer~0
-forInTeardown$820d7930 lexical-env-teardown.js:28:5
+forInTeardown$67161a97 lexical-env-teardown.js:28:9
Registers: 11
- Blocks: 6
- Locals: k~0, outer~1
+ Blocks: 5
+ Locals: outer~0, k~1
Constants:
[0] = Int32(4)
- [1] = Int32(1)
- [2] = Int32(2)
- [3] = Int32(0)
+ [1] = <Empty>
+ [2] = Int32(1)
+ [3] = Int32(2)
+ [4] = Int32(0)
block0:
[ 0] Enter
- [ 8] Mov dst:outer~1, src:Int32(4)
- [ 18] NewObject dst:reg5
- [ 28] InitObjectLiteralProperty object:reg5, `a`, src:Int32(1), shape_cache_index:0, property_slot:0
- [ 40] InitObjectLiteralProperty object:reg5, `b`, src:Int32(2), shape_cache_index:0, property_slot:1
- [ 58] CacheObjectShape object:reg5
- [ 68] JumpNullish condition:reg5, true_target:block3, false_target:block4
+ [ 8] Mov dst:outer~0, src:Int32(4)
+ [ 18] Mov dst:k~1, src:<Empty>
+ [ 28] NewObject dst:reg6
+ [ 38] InitObjectLiteralProperty object:reg6, `a`, src:Int32(1), shape_cache_index:0, property_slot:0
+ [ 50] InitObjectLiteralProperty object:reg6, `b`, src:Int32(2), shape_cache_index:0, property_slot:1
+ [ 68] CacheObjectShape object:reg6
+ [ 78] Mov dst:reg5, src:reg6
+ [ 88] JumpNullish condition:reg5, true_target:block4, false_target:block1
block1:
- [ 78] Return value:outer~1
+ [ 98] GetObjectPropertyIterator dst_keys:reg7, dst_receiver:reg6, object:reg5
+ [ b0] Mov dst:reg8, src:Int32(0)
block2:
- [ 80] ObjectPropertyIteratorNext dst_value:reg9, dst_done:reg10, receiver:reg6, keys:reg7, cursor:reg8
- [ 98] JumpIfLoop condition:reg10, true_target:block1, false_target:block5
+ [ c0] ObjectPropertyIteratorNext dst_value:reg9, dst_done:reg10, receiver:reg6, keys:reg7, cursor:reg8
+ [ d8] JumpTrue condition:reg10, target:block4
block3:
- [ a8] Return value:outer~1
+ [ e8] Mov dst:k~1, src:reg9
+ [ f8] JumpLoop target:block2
block4:
- [ b0] GetObjectPropertyIterator dst_keys:reg7, dst_receiver:reg6, object:reg5
- [ c8] Mov dst:reg8, src:Int32(0)
- [ d8] JumpLoop target:block2
+ [ 100] Return value:outer~0
-block5:
- [ e0] Mov dst:k~0, src:reg9
- [ f0] JumpLoop target:block2
-
-forOfTeardown$1340b60f lexical-env-teardown.js:38:5
+forOfTeardown$26f278e0 lexical-env-teardown.js:38:9
Registers: 12
- Blocks: 9
- Locals: v~0, outer~1
+ Blocks: 5
+ Locals: outer~0, v~1
Constants:
[0] = Int32(5)
- [1] = Int32(1)
- [2] = Undefined
- [3] = Int32(2)
+ [1] = <Empty>
+ [2] = Int32(10)
+ [3] = Int32(20)
block0:
[ 0] Enter
- [ 8] Mov dst:outer~1, src:Int32(5)
- [ 18] NewPrimitiveArray dst:reg5, elements:[10, 20]
- [ 38] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true
- [ 58] Jump target:block2
+ [ 8] Mov dst:outer~0, src:Int32(5)
+ [ 18] Mov dst:v~1, src:<Empty>
+ [ 28] NewPrimitiveArray dst:reg5, elements:[10, 20]
+ [ 48] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true
block1:
- [ 60] Return value:outer~1
+ [ 68] IteratorNextUnpack dst_value:reg9, dst_done:reg10, iterator_object:reg6, iterator_next:reg7, iterator_done:reg8
+ [ 80] JumpTrue condition:reg10, target:block4
block2:
- [ 68] IteratorNextUnpack dst_value:reg10, dst_done:reg11, iterator_object:reg6, iterator_next:reg7, iterator_done:reg8
- [ 80] JumpIfLoop condition:reg11, true_target:block1, false_target:block4
+ [ 90] Mov dst:v~1, src:reg9
+ [ a0] JumpLoop target:block1
block3:
- [ 90] Catch value_feedback:0, dst:reg9
- [ 98] Mov dst:reg5, src:Int32(1)
- [ a8] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg5, rhs:1, true_target:block5, false_target:block6
+ [ a8] Catch value_feedback:0, dst:reg11
+ [ b0] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:reg11
+ [ d0] Throw src:reg11
block4:
- [ c0] Mov dst:v~0, src:reg10
- [ d0] JumpLoop target:block2
-
-block5:
- [ d8] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:reg9
- [ f8] Throw src:reg9
-
-block6:
- [ 100] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:Undefined
- [ 120] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg5, rhs:2, true_target:block7, false_target:block8
-
-block7:
- [ 138] Return value:reg9
-
-block8:
- [ 140] Throw src:reg9
+ [ d8] Return value:outer~0
Exception handlers:
- [ c0 .. d8] => handler block3
+ [ 90 .. a8] => handler block3
-catchTeardown$6b833e8d lexical-env-teardown.js:48:5
- Registers: 7
- Blocks: 3
- Locals: e~0, outer~1
+catchTeardown$082ed7f1 lexical-env-teardown.js:48:9
+ Registers: 6
+ Blocks: 4
+ Locals: outer~0, e~1
Constants:
[0] = Int32(6)
- [1] = Undefined
- [2] = String("test")
+ [1] = String("test")
+ [2] = <Empty>
block0:
[ 0] Enter
- [ 8] Mov dst:outer~1, src:Int32(6)
- [ 18] Jump target:block2
+ [ 8] Mov dst:outer~0, src:Int32(6)
block1:
- [ 20] Catch value_feedback:0, dst:reg5
- [ 28] Mov dst:e~0, src:reg5
- [ 38] Return value:outer~1
+ [ 18] GetGlobal value_feedback:0, dst:reg5, `Error`
+ [ 28] CallConstruct value_feedback:1, call_feedback:0, dst:reg5, callee:reg5, arguments:[String("test")]
+ [ 50] Throw src:reg5
block2:
- [ 40] GetGlobal value_feedback:1, dst:reg6, `Error`
- [ 50] CallConstruct value_feedback:2, call_feedback:0, dst:reg5, callee:reg6, Error, arguments:[String("test")]
- [ 78] Throw src:reg5
+ [ 58] Catch value_feedback:2, dst:reg5
+ [ 60] Mov dst:e~1, src:<Empty>
+ [ 70] Mov dst:e~1, src:reg5
+ [ 80] Jump target:block3
+
+block3:
+ [ 88] Return value:outer~0
Exception handlers:
- [ 40 .. 80] => handler block1
+ [ 18 .. 58] => handler block2
myName$36b03aef lexical-env-teardown.js:60:5
diff --git a/Tests/LibJS/Bytecode/expected/local-source-order.txt b/Tests/LibJS/Bytecode/expected/local-source-order.txt
index 16ead2f4d63..6008536eb76 100644
--- a/Tests/LibJS/Bytecode/expected/local-source-order.txt
+++ b/Tests/LibJS/Bytecode/expected/local-source-order.txt
@@ -1,4 +1,4 @@
-$c7fd0018 local-source-order.js:12:1
+$c5390f08 local-source-order.js:12:1
Registers: 7
Blocks: 1
Constants:
@@ -6,13 +6,14 @@ $c7fd0018 local-source-order.js:12:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `source_order_locals`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, source_order_locals
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `source_order_locals`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-source_order_locals$c9b8f2fb local-source-order.js:6:5
- Registers: 7
+source_order_locals$465fc127 local-source-order.js:6:9
+ Registers: 6
Blocks: 1
Locals: zebra~0, yak~1, aardvark~2
Constants:
@@ -22,7 +23,9 @@ source_order_locals$c9b8f2fb local-source-order.js:6:5
block0:
[ 0] Enter
- [ 8] Mov3 c0_dst:zebra~0, c0_src:Int32(1), c1_dst:yak~1, c1_src:Int32(2), c2_dst:aardvark~2, c2_src:Int32(3)
- [ 28] Add arith_feedback:0, dst:reg5, lhs:zebra~0, rhs:yak~1
- [ 38] Add arith_feedback:1, dst:reg6, lhs:reg5, rhs:aardvark~2
- [ 48] Return value:reg6
+ [ 8] Mov dst:zebra~0, src:Int32(1)
+ [ 18] Mov dst:yak~1, src:Int32(2)
+ [ 28] Mov dst:aardvark~2, src:Int32(3)
+ [ 38] Add arith_feedback:0, dst:reg5, lhs:zebra~0, rhs:yak~1
+ [ 48] Add arith_feedback:1, dst:reg5, lhs:reg5, rhs:aardvark~2
+ [ 58] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/local-variables.txt b/Tests/LibJS/Bytecode/expected/local-variables.txt
index e11f15ddf42..a97fcf0ee28 100644
--- a/Tests/LibJS/Bytecode/expected/local-variables.txt
+++ b/Tests/LibJS/Bytecode/expected/local-variables.txt
@@ -1,21 +1,22 @@
-$53c8db40 local-variables.js:20:1
- Registers: 8
+$568ccc50 local-variables.js:20:1
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `simple_let`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, simple_let
- [ 38] GetGlobal value_feedback:2, dst:reg7, `simple_const`
- [ 48] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, simple_const
- [ 68] GetGlobal value_feedback:4, dst:reg7, `multiple_locals`
- [ 78] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg7, this_value:Undefined, multiple_locals
- [ 98] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `simple_let`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] GetGlobal value_feedback:2, dst:reg6, `simple_const`
+ [ 58] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined
+ [ 78] GetGlobal value_feedback:4, dst:reg6, `multiple_locals`
+ [ 88] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined
+ [ a8] End value:reg5
-simple_let$bee58da9 local-variables.js:5:5
+simple_let$49601125 local-variables.js:5:9
Registers: 5
Blocks: 1
Locals: x~0
@@ -28,7 +29,7 @@ block0:
[ 18] Return value:x~0
-simple_const$f7280be6 local-variables.js:10:5
+simple_const$bcfa8e68 local-variables.js:10:11
Registers: 5
Blocks: 1
Locals: y~0
@@ -41,7 +42,7 @@ block0:
[ 18] Return value:y~0
-multiple_locals$f8b7974e local-variables.js:15:5
+multiple_locals$f526ee7a local-variables.js:15:9
Registers: 6
Blocks: 1
Locals: a~0, b~1
@@ -51,6 +52,7 @@ multiple_locals$f8b7974e local-variables.js:15:5
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:a~0, c0_src:Int32(1), c1_dst:b~1, c1_src:Int32(2)
- [ 20] Add arith_feedback:0, dst:reg5, lhs:a~0, rhs:b~1
- [ 30] Return value:reg5
+ [ 8] Mov dst:a~0, src:Int32(1)
+ [ 18] Mov dst:b~1, src:Int32(2)
+ [ 28] Add arith_feedback:0, dst:reg5, lhs:a~0, rhs:b~1
+ [ 38] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/logical-assignment-register-order.txt b/Tests/LibJS/Bytecode/expected/logical-assignment-register-order.txt
index fddbc9fc11a..d466c1830d2 100644
--- a/Tests/LibJS/Bytecode/expected/logical-assignment-register-order.txt
+++ b/Tests/LibJS/Bytecode/expected/logical-assignment-register-order.txt
@@ -1,18 +1,20 @@
-$11cb31b0 logical-assignment-register-order.js:2:7
- Registers: 8
+$973653fe logical-assignment-register-order.js:2:1
+ Registers: 9
Blocks: 3
+ Constants:
+ [0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg5, `value`
- [ 18] JumpFalse condition:reg5, target:block2
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `value`
+ [ 28] Mov dst:reg7, src:reg6
+ [ 38] JumpFalse condition:reg7, target:block2
block1:
- [ 28] NewFunction dst:reg6, shared_function_data_index:0 (value)
- [ 40] Mov dst:reg7, src:reg6
- [ 50] SetGlobal `value`, src:reg7
- [ 60] End value:reg7
+ [ 48] NewFunction dst:reg7, shared_function_data_index:0 (value)
+ [ 60] SetGlobal `value`, src:reg7
block2:
- [ 68] Mov dst:reg7, src:reg5
- [ 78] End value:reg7
+ [ 70] Mov dst:reg5, src:reg7
+ [ 80] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/logical-constant-folding.txt b/Tests/LibJS/Bytecode/expected/logical-constant-folding.txt
index 98c9b60afb2..13c111648d5 100644
--- a/Tests/LibJS/Bytecode/expected/logical-constant-folding.txt
+++ b/Tests/LibJS/Bytecode/expected/logical-constant-folding.txt
@@ -1,21 +1,71 @@
-$8230da25 logical-constant-folding.js:1:1
- Registers: 6
- Blocks: 1
+$de5c50b6 logical-constant-folding.js:1:5
+ Registers: 7
+ Blocks: 15
Constants:
- [0] = Null
- [1] = Int32(42)
- [2] = Undefined
+ [0] = Undefined
+ [1] = Null
+ [2] = Int32(42)
[3] = Int32(0)
[4] = Bool(false)
[5] = Bool(true)
block0:
[ 0] Enter
- [ 8] SetGlobal `a`, src:Int32(42)
- [ 18] SetGlobal `b`, src:Int32(42)
- [ 28] SetGlobal `c`, src:Int32(0)
- [ 38] SetGlobal `d`, src:Int32(42)
- [ 48] SetGlobal `e`, src:Bool(true)
- [ 58] SetGlobal `f`, src:Int32(42)
- [ 68] SetGlobal `g`, src:Bool(false)
- [ 78] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg6, src:Null
+ [ 28] JumpNullish condition:reg6, true_target:block1, false_target:block2
+
+block1:
+ [ 38] Mov dst:reg6, src:Int32(42)
+
+block2:
+ [ 48] SetGlobal `a`, src:reg6
+ [ 58] Mov dst:reg6, src:Undefined
+ [ 68] JumpNullish condition:reg6, true_target:block3, false_target:block4
+
+block3:
+ [ 78] Mov dst:reg6, src:Int32(42)
+
+block4:
+ [ 88] SetGlobal `b`, src:reg6
+ [ 98] Mov dst:reg6, src:Int32(0)
+ [ a8] JumpNullish condition:reg6, true_target:block5, false_target:block6
+
+block5:
+ [ b8] Mov dst:reg6, src:Int32(42)
+
+block6:
+ [ c8] SetGlobal `c`, src:reg6
+ [ d8] Mov dst:reg6, src:Bool(false)
+ [ e8] JumpTrue condition:reg6, target:block8
+
+block7:
+ [ f8] Mov dst:reg6, src:Int32(42)
+
+block8:
+ [ 108] SetGlobal `d`, src:reg6
+ [ 118] Mov dst:reg6, src:Bool(true)
+ [ 128] JumpTrue condition:reg6, target:block10
+
+block9:
+ [ 138] Mov dst:reg6, src:Int32(42)
+
+block10:
+ [ 148] SetGlobal `e`, src:reg6
+ [ 158] Mov dst:reg6, src:Bool(true)
+ [ 168] JumpFalse condition:reg6, target:block12
+
+block11:
+ [ 178] Mov dst:reg6, src:Int32(42)
+
+block12:
+ [ 188] SetGlobal `f`, src:reg6
+ [ 198] Mov dst:reg6, src:Bool(false)
+ [ 1a8] JumpFalse condition:reg6, target:block14
+
+block13:
+ [ 1b8] Mov dst:reg6, src:Int32(42)
+
+block14:
+ [ 1c8] SetGlobal `g`, src:reg6
+ [ 1d8] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/logical-or-in-if-condition.txt b/Tests/LibJS/Bytecode/expected/logical-or-in-if-condition.txt
index 17d540a1ada..46bc3a59d2a 100644
--- a/Tests/LibJS/Bytecode/expected/logical-or-in-if-condition.txt
+++ b/Tests/LibJS/Bytecode/expected/logical-or-in-if-condition.txt
@@ -1,4 +1,4 @@
-$469b0790 logical-or-in-if-condition.js:12:1
+$43d71680 logical-or-in-if-condition.js:12:1
Registers: 7
Blocks: 1
Constants:
@@ -7,14 +7,15 @@ $469b0790 logical-or-in-if-condition.js:12:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `blocked`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, blocked, arguments:[Bool(false)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `blocked`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Bool(false)]
+ [ 50] End value:reg5
-blocked$70fe0bcb logical-or-in-if-condition.js:7:9
+blocked$36a96b15 logical-or-in-if-condition.js:6:14
Registers: 6
- Blocks: 7
+ Blocks: 8
Constants:
[0] = Undefined
@@ -23,19 +24,22 @@ block0:
block1:
[ 8] Mov dst:reg5, src:arg0
- [ 18] JumpIf condition:arg0, true_target:block4, false_target:block3
+ [ 18] JumpTrue condition:reg5, target:block3
block2:
- [ 28] End value:Undefined
+ [ 28] Mov dst:reg5, src:arg0
block3:
- [ 30] Mov dst:reg5, src:arg0
+ [ 38] JumpFalse condition:reg5, target:block5
block4:
- [ 40] JumpFalse condition:reg5, target:block6
+ [ 48] Jump target:block6
block5:
- [ 50] JumpLoop target:block1
+ [ 50] Jump target:block7
block6:
- [ 58] JumpLoop target:block2
+ [ 58] JumpLoop target:block1
+
+block7:
+ [ 60] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/logical-or-preferred-dst.txt b/Tests/LibJS/Bytecode/expected/logical-or-preferred-dst.txt
index 9645bd6318b..255bea67af2 100644
--- a/Tests/LibJS/Bytecode/expected/logical-or-preferred-dst.txt
+++ b/Tests/LibJS/Bytecode/expected/logical-or-preferred-dst.txt
@@ -1,4 +1,4 @@
-$393b7f47 logical-or-preferred-dst.js:11:1
+$36778e37 logical-or-preferred-dst.js:11:1
Registers: 7
Blocks: 1
Constants:
@@ -7,14 +7,15 @@ $393b7f47 logical-or-preferred-dst.js:11:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `blocked`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, blocked, arguments:[Bool(false)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `blocked`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Bool(false)]
+ [ 50] End value:reg5
-blocked$89c7bdba logical-or-preferred-dst.js:6:9
- Registers: 6
- Blocks: 7
+blocked$3c995b46 logical-or-preferred-dst.js:5:14
+ Registers: 7
+ Blocks: 8
Constants:
[0] = Int32(0)
[1] = Undefined
@@ -24,19 +25,22 @@ block0:
block1:
[ 8] Mov dst:reg5, src:arg0
- [ 18] JumpIf condition:arg0, true_target:block4, false_target:block3
+ [ 18] JumpTrue condition:reg5, target:block3
block2:
- [ 28] End value:Undefined
+ [ 28] GreaterThanRhsInt32 arith_feedback:0, dst:reg5, lhs:arg0, rhs:0
block3:
- [ 30] GreaterThanRhsInt32 arith_feedback:0, dst:reg5, lhs:arg0, rhs:0
+ [ 38] JumpFalse condition:reg5, target:block5
block4:
- [ 40] JumpFalse condition:reg5, target:block6
+ [ 48] Jump target:block6
block5:
- [ 50] JumpLoop target:block1
+ [ 50] Jump target:block7
block6:
- [ 58] JumpLoop target:block2
+ [ 58] JumpLoop target:block1
+
+block7:
+ [ 60] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/mapped-arguments-parameter-bindings.txt b/Tests/LibJS/Bytecode/expected/mapped-arguments-parameter-bindings.txt
index f8390a53b1c..dfdbd904d8b 100644
--- a/Tests/LibJS/Bytecode/expected/mapped-arguments-parameter-bindings.txt
+++ b/Tests/LibJS/Bytecode/expected/mapped-arguments-parameter-bindings.txt
@@ -1,4 +1,4 @@
-$28d58d80 mapped-arguments-parameter-bindings.js:4:1
+$312160b0 mapped-arguments-parameter-bindings.js:4:1
Registers: 7
Blocks: 1
Constants:
@@ -9,13 +9,14 @@ $28d58d80 mapped-arguments-parameter-bindings.js:4:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `forward`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, forward, arguments:[Int32(1), Int32(2), Int32(3)]
- [ 48] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `forward`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(1), Int32(2), Int32(3)]
+ [ 58] End value:reg5
forward$5577a08e mapped-arguments-parameter-bindings.js:2:5
- Registers: 8
+ Registers: 7
Blocks: 1
Locals: arguments~0
Constants:
@@ -25,13 +26,13 @@ block0:
[ 0] Enter
[ 8] CreateArguments dst:arguments~0, is_immutable:false, creates_parameter_bindings:true
[ 18] InitializeLexicalBinding `a`, src:Undefined
- [ 30] InitializeLexicalBinding `b`, src:Undefined
- [ 48] SetLexicalBinding `a`, src:arg0
+ [ 30] SetLexicalBinding `a`, src:arg0
+ [ 48] InitializeLexicalBinding `b`, src:Undefined
[ 60] SetLexicalBinding `b`, src:arg1
[ 78] SetLexicalBinding `a`, src:arg2
- [ 90] GetLength value_feedback:0, keyed_feedback:0, dst:reg5, base:arguments~0 (arguments.length)
+ [ 90] GetLength value_feedback:0, keyed_feedback:0, dst:reg5, base:arguments~0
[ a8] GetBinding value_feedback:1, dst:reg6, `a`
- [ c0] Add arith_feedback:0, dst:reg7, lhs:reg5, rhs:reg6
- [ d0] GetBinding value_feedback:2, dst:reg5, `b`
- [ e8] Add arith_feedback:1, dst:reg6, lhs:reg7, rhs:reg5
- [ f8] Return value:reg6
+ [ c0] Add arith_feedback:0, dst:reg5, lhs:reg5, rhs:reg6
+ [ d0] GetBinding value_feedback:2, dst:reg6, `b`
+ [ e8] Add arith_feedback:1, dst:reg5, lhs:reg5, rhs:reg6
+ [ f8] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/module-level-bindings.txt b/Tests/LibJS/Bytecode/expected/module-level-bindings.txt
index 8b1401a8785..9e2e9dbe7b4 100644
--- a/Tests/LibJS/Bytecode/expected/module-level-bindings.txt
+++ b/Tests/LibJS/Bytecode/expected/module-level-bindings.txt
@@ -9,18 +9,18 @@ block0:
inner$24238fde module-level-bindings.mjs:7:18
- Registers: 8
+ Registers: 7
Blocks: 1
block0:
[ 0] Enter
[ 8] GetBinding value_feedback:0, dst:reg5, `lexical`
[ 20] GetBinding value_feedback:1, dst:reg6, `constant`
- [ 38] Add arith_feedback:0, dst:reg7, lhs:reg5, rhs:reg6
- [ 48] SetLexicalBinding `variable`, src:reg7
+ [ 38] Add arith_feedback:0, dst:reg5, lhs:reg5, rhs:reg6
+ [ 48] SetLexicalBinding `variable`, src:reg5
[ 60] GetCalleeAndThisFromEnvironment value_feedback:2, callee:reg5, this_value:reg6, `declared`
- [ 78] Call value_feedback:3, call_feedback:0, dst:reg7, callee:reg5, this_value:reg6, declared
- [ 98] Return value:reg7
+ [ 78] Call value_feedback:3, call_feedback:0, dst:reg5, callee:reg5, this_value:reg6
+ [ 98] Return value:reg5
declared$581f69d1 module-level-bindings.mjs:13:5
diff --git a/Tests/LibJS/Bytecode/expected/mov-merging.txt b/Tests/LibJS/Bytecode/expected/mov-merging.txt
index e1b682d3d31..7549f67675a 100644
--- a/Tests/LibJS/Bytecode/expected/mov-merging.txt
+++ b/Tests/LibJS/Bytecode/expected/mov-merging.txt
@@ -1,25 +1,26 @@
-$b64866f5 mov-merging.js:14:1
- Registers: 11
+$be943a25 mov-merging.js:14:1
+ Registers: 9
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `twoLocals`
- [ 40] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, twoLocals
- [ 60] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 88] GetGlobal value_feedback:5, dst:reg6, `console`
- [ 98] GetById value_feedback:6, dst:reg8, base:reg6, `log` (console.log)
- [ b0] GetGlobal value_feedback:7, dst:reg10, `threeLocals`
- [ c0] Call value_feedback:8, call_feedback:2, dst:reg9, callee:reg10, this_value:Undefined, threeLocals
- [ e0] Call value_feedback:9, call_feedback:3, dst:reg7, callee:reg8, this_value:reg6, console.log, arguments:[reg9]
- [ 108] End value:reg7
-
-
-twoLocals$032d6b80 mov-merging.js:2:5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `twoLocals`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined
+ [ 70] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 98] GetGlobal value_feedback:5, dst:reg6, `console`
+ [ a8] GetById value_feedback:6, dst:reg7, base:reg6, `log`
+ [ c0] GetGlobal value_feedback:7, dst:reg8, `threeLocals`
+ [ d0] Call value_feedback:8, call_feedback:2, dst:reg8, callee:reg8, this_value:Undefined
+ [ f0] Call value_feedback:9, call_feedback:3, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 118] End value:reg5
+
+
+twoLocals$0c45f674 mov-merging.js:2:9
Registers: 6
Blocks: 1
Locals: a~0, b~1
@@ -29,13 +30,14 @@ twoLocals$032d6b80 mov-merging.js:2:5
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:a~0, c0_src:Int32(1), c1_dst:b~1, c1_src:Int32(2)
- [ 20] Add arith_feedback:0, dst:reg5, lhs:a~0, rhs:b~1
- [ 30] Return value:reg5
+ [ 8] Mov dst:a~0, src:Int32(1)
+ [ 18] Mov dst:b~1, src:Int32(2)
+ [ 28] Add arith_feedback:0, dst:reg5, lhs:a~0, rhs:b~1
+ [ 38] Return value:reg5
-threeLocals$7625f4d0 mov-merging.js:8:5
- Registers: 7
+threeLocals$c35ad2ec mov-merging.js:8:9
+ Registers: 6
Blocks: 1
Locals: a~0, b~1, c~2
Constants:
@@ -45,10 +47,12 @@ threeLocals$7625f4d0 mov-merging.js:8:5
block0:
[ 0] Enter
- [ 8] Mov3 c0_dst:a~0, c0_src:Int32(1), c1_dst:b~1, c1_src:Int32(2), c2_dst:c~2, c2_src:Int32(3)
- [ 28] Add arith_feedback:0, dst:reg5, lhs:a~0, rhs:b~1
- [ 38] Add arith_feedback:1, dst:reg6, lhs:reg5, rhs:c~2
- [ 48] Return value:reg6
+ [ 8] Mov dst:a~0, src:Int32(1)
+ [ 18] Mov dst:b~1, src:Int32(2)
+ [ 28] Mov dst:c~2, src:Int32(3)
+ [ 38] Add arith_feedback:0, dst:reg5, lhs:a~0, rhs:b~1
+ [ 48] Add arith_feedback:1, dst:reg5, lhs:reg5, rhs:c~2
+ [ 58] Return value:reg5
3
diff --git a/Tests/LibJS/Bytecode/expected/named-class-expression-no-lhs-name-leak.txt b/Tests/LibJS/Bytecode/expected/named-class-expression-no-lhs-name-leak.txt
index c37b0663fdb..298e7c75f26 100644
--- a/Tests/LibJS/Bytecode/expected/named-class-expression-no-lhs-name-leak.txt
+++ b/Tests/LibJS/Bytecode/expected/named-class-expression-no-lhs-name-leak.txt
@@ -1,83 +1,58 @@
-$752dc5b7 named-class-expression-no-lhs-name-leak.js:1:1
- Registers: 15
- Blocks: 18
+$ca340182 named-class-expression-no-lhs-name-leak.js:1:1
+ Registers: 14
+ Blocks: 12
Constants:
- [0] = Bool(false)
- [1] = Undefined
- [2] = Int32(1)
- [3] = Int32(2)
+ [0] = Undefined
+ [1] = Bool(false)
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] NewArray dst:reg5
- [ 20] Mov dst:reg6, src:Bool(false)
- [ 30] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5, fast_array_mode_allowed:true
- [ 50] Jump target:block3
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] NewArray dst:reg6
+ [ 30] Mov dst:reg7, src:Bool(false)
+ [ 40] GetIterator dst_iterator_object:reg8, dst_iterator_next:reg9, dst_iterator_done:reg10, iterable:reg6, fast_array_mode_allowed:true
+ [ 60] IteratorNextUnpack dst_value:reg11, dst_done:reg7, iterator_object:reg8, iterator_next:reg9, iterator_done:reg10
block1:
- [ 58] Catch value_feedback:0, dst:reg11
- [ 60] SetLexicalEnvironment environment:reg4
- [ 68] Mov dst:reg10, src:Int32(1)
- [ 78] JumpIf condition:reg9, true_target:block13, false_target:block12
+ [ 78] JumpFalse condition:reg7, target:block3
block2:
- [ 88] End value:Undefined
+ [ 88] Mov dst:reg11, src:Undefined
block3:
- [ 90] Jump target:block5
+ [ 98] JumpUndefined condition:reg11, true_target:block4, false_target:block5
block4:
- [ 98] MovSrcUndefined dst:reg12
- [ a0] Jump target:block6
+ [ a8] CreateLexicalEnvironment dst:reg13, parent:reg4, capacity:1, is_catch_environment:false
+ [ c0] CreateVariable `Foo`, is_immutable:true, is_global:false, is_strict:true
+ [ d0] SetLexicalEnvironment environment:reg4
+ [ d8] NewClass dst:reg12, class_environment:reg13, class_blueprint_index:0
+ [ 100] Mov dst:reg11, src:reg12
block5:
- [ a8] IteratorNextUnpack dst_value:reg12, dst_done:reg6, iterator_object:reg7, iterator_next:reg8, iterator_done:reg9
- [ c0] JumpTrueLoop condition:reg6, target:block4
+ [ 110] SetGlobal `C`, src:reg11
block6:
- [ d0] JumpUndefined condition:reg12, true_target:block7, false_target:block8
+ [ 120] JumpTrue condition:reg10, target:block11
block7:
- [ e0] CreateLexicalEnvironment dst:reg13, parent:reg4, capacity:1, is_catch_environment:false
- [ f8] CreateVariable `Foo`, is_immutable:true, is_global:false, is_strict:true
- [ 108] SetLexicalEnvironment environment:reg4
- [ 110] NewClass dst:reg14, class_environment:reg13, class_blueprint_index:0
- [ 138] Mov dst:reg12, src:reg14
+ [ 130] IteratorClose iterator_object:reg8, iterator_next:reg9, iterator_done:reg10, completion_value:Undefined
+ [ 150] Jump target:block11
block8:
- [ 148] SetGlobal `C`, src:reg12
+ [ 158] Catch value_feedback:0, dst:reg11
+ [ 160] SetLexicalEnvironment environment:reg4
+ [ 168] JumpTrue condition:reg10, target:block10
block9:
- [ 158] JumpFalse condition:reg9, target:block11
+ [ 178] IteratorClose iterator_object:reg8, iterator_next:reg9, iterator_done:reg10, completion_value:reg11
block10:
- [ 168] JumpLoop target:block2
+ [ 198] Throw src:reg11
block11:
- [ 170] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:Undefined
- [ 190] JumpLoop target:block10
-
-block12:
- [ 198] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg10, rhs:1, true_target:block14, false_target:block15
-
-block13:
- [ 1b0] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg10, rhs:2, true_target:block16, false_target:block17
-
-block14:
- [ 1c8] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:reg11
- [ 1e8] Throw src:reg11
-
-block15:
- [ 1f0] IteratorClose iterator_object:reg7, iterator_next:reg8, iterator_done:reg9, completion_value:Undefined
- [ 210] JumpLoop target:block13
-
-block16:
- [ 218] Return value:reg11
-
-block17:
- [ 220] Throw src:reg11
+ [ 1a0] End value:reg5
Exception handlers:
- [ 90 .. a8] => handler block1
- [ d0 .. 158] => handler block1
+ [ 78 .. 120] => handler block8
diff --git a/Tests/LibJS/Bytecode/expected/named-function-expression-unused-name.txt b/Tests/LibJS/Bytecode/expected/named-function-expression-unused-name.txt
index 92d019564c8..0860d868fad 100644
--- a/Tests/LibJS/Bytecode/expected/named-function-expression-unused-name.txt
+++ b/Tests/LibJS/Bytecode/expected/named-function-expression-unused-name.txt
@@ -1,5 +1,5 @@
-$cacfda54 named-function-expression-unused-name.js:24:1
- Registers: 8
+$eec31824 named-function-expression-unused-name.js:24:1
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
@@ -7,37 +7,39 @@ $cacfda54 named-function-expression-unused-name.js:24:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `outer`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, outer, arguments:[Int32(1)]
- [ 40] GetGlobal value_feedback:2, dst:reg7, `outerWithEval`
- [ 50] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, outerWithEval
- [ 70] End value:reg6
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `outer`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(1)]
+ [ 50] GetGlobal value_feedback:2, dst:reg6, `outerWithEval`
+ [ 60] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined
+ [ 80] End value:reg5
outer$cd1004f1 named-function-expression-unused-name.js:6:20
- Registers: 9
+ Registers: 7
Blocks: 1
Locals: unused~0, used~1, nested~2
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
- [ 20] InitializeLexicalBinding `x`, src:arg0
+ [ 8] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
+ [ 18] InitializeLexicalBinding `x`, src:arg0
+ [ 30] GetLexicalEnvironment dst:reg4
[ 38] NewFunction dst:unused~0, shared_function_data_index:0
- [ 50] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
+ [ 50] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:1, is_catch_environment:false
[ 68] CreateVariable `g`, is_immutable:true, is_global:false, is_strict:false
- [ 78] NewFunction dst:used~1, shared_function_data_index:1
- [ 90] InitializeLexicalBinding `g`, src:used~1
+ [ 78] NewFunction dst:reg5, shared_function_data_index:1
+ [ 90] InitializeLexicalBinding `g`, src:reg5
[ a8] SetLexicalEnvironment environment:reg4
- [ b0] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ c8] CreateVariable `h`, is_immutable:true, is_global:false, is_strict:false
- [ d8] NewFunction dst:nested~2, shared_function_data_index:2
- [ f0] InitializeLexicalBinding `h`, src:nested~2
- [ 108] SetLexicalEnvironment environment:reg4
- [ 110] Mov3 c0_dst:reg5, c0_src:unused~0, c1_dst:reg6, c1_src:used~1, c2_dst:reg7, c2_src:nested~2
- [ 130] NewArray dst:reg8, elements:[reg5, reg6, reg7]
- [ 150] Return value:reg8
+ [ b0] Mov dst:used~1, src:reg5
+ [ c0] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:1, is_catch_environment:false
+ [ d8] CreateVariable `h`, is_immutable:true, is_global:false, is_strict:false
+ [ e8] NewFunction dst:reg5, shared_function_data_index:2
+ [ 100] InitializeLexicalBinding `h`, src:reg5
+ [ 118] SetLexicalEnvironment environment:reg4
+ [ 120] Mov dst:nested~2, src:reg5
+ [ 130] NewArray dst:reg5, elements:[unused~0, used~1, nested~2]
+ [ 150] Return value:reg5
outerWithEval$fdb37c36 named-function-expression-unused-name.js:19:5
@@ -47,9 +49,9 @@ outerWithEval$fdb37c36 named-function-expression-unused-name.js:19:5
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
+ [ 10] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:1, is_catch_environment:false
[ 28] CreateVariable `i`, is_immutable:true, is_global:false, is_strict:false
- [ 38] NewFunction dst:reg6, shared_function_data_index:0
- [ 50] InitializeLexicalBinding `i`, src:reg6
+ [ 38] NewFunction dst:reg5, shared_function_data_index:0
+ [ 50] InitializeLexicalBinding `i`, src:reg5
[ 68] SetLexicalEnvironment environment:reg4
- [ 70] Return value:reg6
+ [ 70] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/named-function-expression.txt b/Tests/LibJS/Bytecode/expected/named-function-expression.txt
index 4809829ba42..3301e67802c 100644
--- a/Tests/LibJS/Bytecode/expected/named-function-expression.txt
+++ b/Tests/LibJS/Bytecode/expected/named-function-expression.txt
@@ -1,16 +1,20 @@
-$e2be3867 named-function-expression.js:4:6
+$12b60500 named-function-expression.js:4:1
Registers: 8
Blocks: 1
+ Constants:
+ [0] = Undefined
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `Oops`, is_immutable:true, is_global:false, is_strict:false
- [ 38] NewFunction dst:reg6, shared_function_data_index:0
- [ 50] InitializeLexicalBinding `Oops`, src:reg6
- [ 68] SetLexicalEnvironment environment:reg4
- [ 70] SetGlobal `Oops`, src:reg6
- [ 80] GetGlobal value_feedback:0, dst:reg5, `Oops`
- [ 90] GetById value_feedback:1, dst:reg7, base:reg5, `x` (Oops.x)
- [ a8] End value:reg7
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `Oops`, is_immutable:true, is_global:false, is_strict:false
+ [ 48] NewFunction dst:reg6, shared_function_data_index:0
+ [ 60] InitializeLexicalBinding `Oops`, src:reg6
+ [ 78] SetLexicalEnvironment environment:reg4
+ [ 80] SetGlobal `Oops`, src:reg6
+ [ 90] Mov dst:reg5, src:reg6
+ [ a0] GetGlobal value_feedback:0, dst:reg6, `Oops`
+ [ b0] GetById value_feedback:1, dst:reg5, base:reg6, `x`
+ [ c8] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/nested-for-loop-completion.txt b/Tests/LibJS/Bytecode/expected/nested-for-loop-completion.txt
index ccec586cd56..9004cced1d3 100644
--- a/Tests/LibJS/Bytecode/expected/nested-for-loop-completion.txt
+++ b/Tests/LibJS/Bytecode/expected/nested-for-loop-completion.txt
@@ -1,46 +1,43 @@
-$f42dfd93 nested-for-loop-completion.js:4:1
- Registers: 9
- Blocks: 8
+$f09d54bf nested-for-loop-completion.js:4:5
+ Registers: 8
+ Blocks: 7
Constants:
- [0] = Int32(4)
- [1] = Undefined
- [2] = Int32(7)
- [3] = Int32(1)
- [4] = Int32(0)
- [5] = Int32(2)
+ [0] = Undefined
+ [1] = Int32(4)
+ [2] = Int32(0)
+ [3] = Int32(2)
+ [4] = Int32(1)
+ [5] = Int32(7)
block0:
[ 0] Enter
- [ 8] SetGlobal `n`, src:Int32(4)
- [ 18] MovSrcUndefined dst:reg5
- [ 20] Jump target:block3
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:Undefined
+ [ 28] SetGlobal `n`, src:Int32(4)
+ [ 38] Jump target:block5
block1:
- [ 28] SetGlobal `depth`, src:Int32(0)
- [ 38] MovSrcUndefined dst:reg6
- [ 40] Jump target:block6
+ [ 40] Mov dst:reg5, src:Undefined
+ [ 50] SetGlobal `depth`, src:Int32(0)
+ [ 60] Jump target:block3
block2:
- [ 48] GetGlobal value_feedback:1, dst:reg7, `n`
- [ 58] AddRhsInt32 arith_feedback:1, dst:reg6, lhs:reg7, rhs:1
- [ 68] SetGlobal `n`, src:reg6
+ [ 68] GetGlobal value_feedback:0, dst:reg6, `depth`
+ [ 78] AddRhsInt32 arith_feedback:0, dst:reg7, lhs:reg6, rhs:2
+ [ 88] SetGlobal `depth`, src:reg7
block3:
- [ 78] GetGlobal value_feedback:0, dst:reg6, `n`
- [ 88] JumpLessThanEqualsLoopRhsInt32 arith_feedback:0, lhs:reg6, rhs:7, true_target:block1, false_target:block4
+ [ 98] GetGlobal value_feedback:1, dst:reg6, `depth`
+ [ a8] JumpLessThanEqualsLoopRhsInt32 arith_feedback:1, lhs:reg6, rhs:0, true_target:block2, false_target:block4
block4:
- [ a0] End value:reg5
+ [ c0] GetGlobal value_feedback:2, dst:reg6, `n`
+ [ d0] AddRhsInt32 arith_feedback:2, dst:reg7, lhs:reg6, rhs:1
+ [ e0] SetGlobal `n`, src:reg7
block5:
- [ a8] GetGlobal value_feedback:3, dst:reg8, `depth`
- [ b8] AddRhsInt32 arith_feedback:3, dst:reg7, lhs:reg8, rhs:2
- [ c8] SetGlobal `depth`, src:reg7
+ [ f0] GetGlobal value_feedback:3, dst:reg6, `n`
+ [ 100] JumpLessThanEqualsLoopRhsInt32 arith_feedback:3, lhs:reg6, rhs:7, true_target:block1, false_target:block6
block6:
- [ d8] GetGlobal value_feedback:2, dst:reg7, `depth`
- [ e8] JumpLessThanEqualsLoopRhsInt32 arith_feedback:2, lhs:reg7, rhs:0, true_target:block5, false_target:block7
-
-block7:
- [ 100] Mov dst:reg5, src:reg6
- [ 110] JumpLoop target:block2
+ [ 118] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/nested-function-decl-source-order.txt b/Tests/LibJS/Bytecode/expected/nested-function-decl-source-order.txt
index aeab9affcd1..cc82a587b47 100644
--- a/Tests/LibJS/Bytecode/expected/nested-function-decl-source-order.txt
+++ b/Tests/LibJS/Bytecode/expected/nested-function-decl-source-order.txt
@@ -1,5 +1,5 @@
-$7fc74e7b nested-function-decl-source-order.js:15:1
- Registers: 11
+$881321ab nested-function-decl-source-order.js:15:1
+ Registers: 10
Blocks: 1
Constants:
[0] = Undefined
@@ -7,17 +7,18 @@ $7fc74e7b nested-function-decl-source-order.js:15:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg10, `outer`
- [ 40] Call value_feedback:3, call_feedback:0, dst:reg9, callee:reg10, this_value:Undefined, outer
- [ 60] GetById value_feedback:4, dst:reg10, base:reg9, `join`
- [ 78] Call value_feedback:5, call_feedback:1, dst:reg8, callee:reg10, this_value:reg9, <object>.join, arguments:[String(",")]
- [ a0] Call value_feedback:6, call_feedback:2, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ c8] End value:reg5
-
-
-outer$03dbfbaa nested-function-decl-source-order.js:12:5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `outer`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined
+ [ 70] GetById value_feedback:4, dst:reg9, base:reg8, `join`
+ [ 88] Call value_feedback:5, call_feedback:1, dst:reg8, callee:reg9, this_value:reg8, arguments:[String(",")]
+ [ b0] Call value_feedback:6, call_feedback:2, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ d8] End value:reg5
+
+
+outer$e725b1cc nested-function-decl-source-order.js:6:5
Registers: 11
Blocks: 1
Locals: alpha~0, beta~1, dup~2, gamma~3, delta~4
@@ -26,20 +27,24 @@ outer$03dbfbaa nested-function-decl-source-order.js:12:5
block0:
[ 0] Enter
- [ 8] MovUndefined3 c0_dst:alpha~0, c1_dst:beta~1, c2_dst:dup~2
- [ 18] MovUndefined2 c0_dst:gamma~3, c1_dst:delta~4
- [ 28] NewFunction dst:alpha~0, shared_function_data_index:0
+ [ 8] Mov dst:alpha~0, src:Undefined
+ [ 18] NewFunction dst:alpha~0, shared_function_data_index:0
+ [ 30] Mov dst:beta~1, src:Undefined
[ 40] NewFunction dst:beta~1, shared_function_data_index:1
- [ 58] NewFunction dst:gamma~3, shared_function_data_index:2
- [ 70] NewFunction dst:dup~2, shared_function_data_index:3
- [ 88] NewFunction dst:delta~4, shared_function_data_index:4
- [ a0] Call value_feedback:0, call_feedback:0, dst:reg5, callee:alpha~0, this_value:Undefined, alpha
- [ c0] Call value_feedback:1, call_feedback:1, dst:reg6, callee:beta~1, this_value:Undefined, beta
- [ e0] Call value_feedback:2, call_feedback:2, dst:reg7, callee:gamma~3, this_value:Undefined, gamma
- [ 100] Call value_feedback:3, call_feedback:3, dst:reg8, callee:delta~4, this_value:Undefined, delta
- [ 120] Call value_feedback:4, call_feedback:4, dst:reg9, callee:dup~2, this_value:Undefined, dup
- [ 140] NewArray dst:reg10, elements:[reg5, reg6, reg7, reg8, reg9]
- [ 168] Return value:reg10
+ [ 58] Mov dst:dup~2, src:Undefined
+ [ 68] NewFunction dst:dup~2, shared_function_data_index:2
+ [ 80] Mov dst:gamma~3, src:Undefined
+ [ 90] NewFunction dst:gamma~3, shared_function_data_index:3
+ [ a8] NewFunction dst:dup~2, shared_function_data_index:4
+ [ c0] Mov dst:delta~4, src:Undefined
+ [ d0] NewFunction dst:delta~4, shared_function_data_index:5
+ [ e8] Call value_feedback:0, call_feedback:0, dst:reg5, callee:alpha~0, this_value:Undefined
+ [ 108] Call value_feedback:1, call_feedback:1, dst:reg6, callee:beta~1, this_value:Undefined
+ [ 128] Call value_feedback:2, call_feedback:2, dst:reg7, callee:gamma~3, this_value:Undefined
+ [ 148] Call value_feedback:3, call_feedback:3, dst:reg8, callee:delta~4, this_value:Undefined
+ [ 168] Call value_feedback:4, call_feedback:4, dst:reg9, callee:dup~2, this_value:Undefined
+ [ 188] NewArray dst:reg10, elements:[reg5, reg6, reg7, reg8, reg9]
+ [ 1b0] Return value:reg10
alpha$5f53e227 nested-function-decl-source-order.js:6:24
diff --git a/Tests/LibJS/Bytecode/expected/nested-member-base-identifier.txt b/Tests/LibJS/Bytecode/expected/nested-member-base-identifier.txt
index 283d31b26e4..ba013d49027 100644
--- a/Tests/LibJS/Bytecode/expected/nested-member-base-identifier.txt
+++ b/Tests/LibJS/Bytecode/expected/nested-member-base-identifier.txt
@@ -1,4 +1,4 @@
-$9a6e7215 nested-member-base-identifier.js:9:1
+$a2ba4545 nested-member-base-identifier.js:9:1
Registers: 9
Blocks: 1
Constants:
@@ -7,17 +7,18 @@ $9a6e7215 nested-member-base-identifier.js:9:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `assign_nested`
- [ 18] NewObject dst:reg7
- [ 28] InitObjectLiteralProperty object:reg7, `shader`, src:Int32(1), shape_cache_index:0, property_slot:0
- [ 40] CacheObjectShape object:reg7
- [ 50] NewArray dst:reg8, elements:[reg7]
- [ 68] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, assign_nested, arguments:[reg8, Int32(1)]
- [ 90] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `assign_nested`
+ [ 28] NewObject dst:reg7
+ [ 38] InitObjectLiteralProperty object:reg7, `shader`, src:Int32(1), shape_cache_index:0, property_slot:0
+ [ 50] CacheObjectShape object:reg7
+ [ 60] NewArray dst:reg8, elements:[reg7]
+ [ 78] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg8, Int32(1)]
+ [ a0] End value:reg5
assign_nested$93cc3898 nested-member-base-identifier.js:6:8
- Registers: 7
+ Registers: 6
Blocks: 1
Constants:
[0] = Int32(1)
@@ -27,6 +28,6 @@ assign_nested$93cc3898 nested-member-base-identifier.js:6:8
block0:
[ 0] Enter
[ 8] SubRhsInt32 arith_feedback:0, dst:reg5, lhs:arg1, rhs:1
- [ 18] GetByValue value_feedback:0, keyed_feedback:0, dst:reg6, base:arg0, property:reg5 (arr[reg5])
- [ 38] PutById base:reg6, `shader`, src:Int32(0), kind:Normal (arr.shader)
+ [ 18] GetByValue value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0, property:reg5
+ [ 38] PutById base:reg5, `shader`, src:Int32(0), kind:Normal
[ 58] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/nested-try-finally-continue.txt b/Tests/LibJS/Bytecode/expected/nested-try-finally-continue.txt
index 5d8f9a3b9b8..18949a2f524 100644
--- a/Tests/LibJS/Bytecode/expected/nested-try-finally-continue.txt
+++ b/Tests/LibJS/Bytecode/expected/nested-try-finally-continue.txt
@@ -1,4 +1,4 @@
-$853568fa nested-try-finally-continue.js:14:1
+$827177ea nested-try-finally-continue.js:14:1
Registers: 7
Blocks: 1
Constants:
@@ -6,117 +6,96 @@ $853568fa nested-try-finally-continue.js:14:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `nestedTryFinallyContinue`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, nestedTryFinallyContinue
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `nestedTryFinallyContinue`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-nestedTryFinallyContinue$4142cb16 nested-try-finally-continue.js:2:5
- Registers: 13
- Blocks: 24
+nestedTryFinallyContinue$d349c595 nested-try-finally-continue.js:2:10
+ Registers: 11
+ Blocks: 18
Locals: i~0
Constants:
[0] = Int32(0)
- [1] = Int32(3)
- [2] = Int32(1)
+ [1] = Int32(1)
+ [2] = Int32(2)
[3] = String("inner")
- [4] = Int32(2)
- [5] = Undefined
- [6] = String("outer")
+ [4] = String("outer")
+ [5] = Int32(3)
+ [6] = Undefined
block0:
[ 0] Enter
[ 8] Mov dst:i~0, src:Int32(0)
- [ 18] Jump target:block3
+ [ 18] Jump target:block16
block1:
- [ 20] Jump target:block7
+ [ 20] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:i~0, rhs:1, true_target:block2, false_target:block3
block2:
- [ 28] PostfixIncrement arith_feedback:1, dst:reg5, src:i~0
+ [ 38] Mov dst:reg7, src:Int32(2)
+ [ 48] Jump target:block5
block3:
- [ 38] JumpLessThanLoopRhsInt32 arith_feedback:0, lhs:i~0, rhs:3, true_target:block1, false_target:block4
+ [ 50] Mov dst:reg7, src:Int32(0)
+ [ 60] Jump target:block5
block4:
- [ 50] End value:Undefined
+ [ 68] Catch value_feedback:0, dst:reg8
+ [ 70] Mov dst:reg7, src:Int32(1)
block5:
- [ 58] Catch value_feedback:0, dst:reg6
- [ 60] Mov dst:reg5, src:Int32(1)
+ [ 80] GetGlobal value_feedback:1, dst:reg9, `console`
+ [ 90] GetById value_feedback:2, dst:reg10, base:reg9, `log`
+ [ a8] Call value_feedback:3, call_feedback:0, dst:reg9, callee:reg10, this_value:reg9, arguments:[String("inner"), i~0]
+ [ d0] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg7, rhs:0, true_target:block9, false_target:block6
block6:
- [ 70] GetGlobal value_feedback:5, dst:reg8, `console`
- [ 80] GetById value_feedback:6, dst:reg9, base:reg8, `log` (console.log)
- [ 98] Mov dst:reg11, src:i~0
- [ a8] Call value_feedback:7, call_feedback:1, dst:reg7, callee:reg9, this_value:reg8, console.log, arguments:[String("outer"), reg11]
- [ d0] JumpStrictlyEqualsRhsInt32 arith_feedback:6, lhs:reg5, rhs:0, true_target:block19, false_target:block20
+ [ e8] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:reg7, rhs:2, true_target:block7, false_target:block8
block7:
- [ e8] Jump target:block10
+ [ 100] Mov dst:reg5, src:Int32(2)
+ [ 110] Jump target:block11
block8:
- [ f0] Catch value_feedback:1, dst:reg8
- [ f8] Mov dst:reg7, src:Int32(1)
+ [ 118] Throw src:reg8
block9:
- [ 108] GetGlobal value_feedback:2, dst:reg10, `console`
- [ 118] GetById value_feedback:3, dst:reg11, base:reg10, `log` (console.log)
- [ 130] Mov dst:reg12, src:i~0
- [ 140] Call value_feedback:4, call_feedback:0, dst:reg9, callee:reg11, this_value:reg10, console.log, arguments:[String("inner"), reg12]
- [ 168] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg7, rhs:0, true_target:block14, false_target:block15
+ [ 120] Mov dst:reg5, src:Int32(0)
+ [ 130] Jump target:block11
block10:
- [ 180] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:i~0, rhs:1, true_target:block11, false_target:block12
+ [ 138] Catch value_feedback:4, dst:reg6
+ [ 140] Mov dst:reg5, src:Int32(1)
block11:
- [ 198] Mov dst:reg7, src:Int32(3)
- [ 1a8] JumpLoop target:block9
+ [ 150] GetGlobal value_feedback:5, dst:reg7, `console`
+ [ 160] GetById value_feedback:6, dst:reg8, base:reg7, `log`
+ [ 178] Call value_feedback:7, call_feedback:1, dst:reg7, callee:reg8, this_value:reg7, arguments:[String("outer"), i~0]
+ [ 1a0] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg5, rhs:0, true_target:block15, false_target:block12
block12:
- [ 1b0] Mov dst:reg7, src:Int32(0)
- [ 1c0] JumpLoop target:block9
+ [ 1b8] JumpStrictlyEqualsRhsInt32 arith_feedback:4, lhs:reg5, rhs:2, true_target:block13, false_target:block14
block13:
- [ 1c8] Mov dst:reg5, src:Int32(3)
- [ 1d8] JumpLoop target:block6
+ [ 1d0] Jump target:block15
block14:
- [ 1e0] Mov dst:reg5, src:Int32(0)
- [ 1f0] JumpLoop target:block6
+ [ 1d8] Throw src:reg6
block15:
- [ 1f8] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:4, lhs:reg7, rhs:3, true_target:block13, false_target:block16
+ [ 1e0] Increment arith_feedback:5, dst:i~0
block16:
- [ 210] JumpStrictlyEqualsRhsInt32 arith_feedback:5, lhs:reg7, rhs:2, true_target:block17, false_target:block18
+ [ 1e8] JumpLessThanLoopRhsInt32 arith_feedback:6, lhs:i~0, rhs:3, true_target:block1, false_target:block17
block17:
- [ 228] Mov2 c0_dst:reg5, c0_src:reg7, c1_dst:reg6, c1_src:reg8
- [ 240] JumpLoop target:block6
-
-block18:
- [ 248] Throw src:reg8
-
-block19:
- [ 250] JumpLoop target:block2
-
-block20:
- [ 258] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:7, lhs:reg5, rhs:3, true_target:block2, false_target:block21
-
-block21:
- [ 270] JumpStrictlyEqualsRhsInt32 arith_feedback:8, lhs:reg5, rhs:2, true_target:block22, false_target:block23
-
-block22:
- [ 288] Return value:reg6
-
-block23:
- [ 290] Throw src:reg6
+ [ 200] End value:Undefined
Exception handlers:
- [ e8 .. 180] => handler block5
- [ 180 .. 1e0] => handler block8
- [ 1e0 .. 250] => handler block5
+ [ 20 .. 68] => handler block4
+ [ 68 .. 138] => handler block10
"inner" 0
diff --git a/Tests/LibJS/Bytecode/expected/numeric-class-field-name.txt b/Tests/LibJS/Bytecode/expected/numeric-class-field-name.txt
index e4c5a1dc44e..37accdc6fd0 100644
--- a/Tests/LibJS/Bytecode/expected/numeric-class-field-name.txt
+++ b/Tests/LibJS/Bytecode/expected/numeric-class-field-name.txt
@@ -1,23 +1,24 @@
-$79e506f5 numeric-class-field-name.js:1:1
- Registers: 7
+$2d2a9e5a numeric-class-field-name.js:1:1
+ Registers: 8
Blocks: 1
Constants:
- [0] = Int32(42)
- [1] = Undefined
+ [0] = Undefined
+ [1] = Int32(42)
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
- [ 38] SetLexicalEnvironment environment:reg4
- [ 40] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:Int32(42)]
- [ 70] DynamicInitializeLexicalBinding `C`, src:reg6
- [ 80] GetGlobal value_feedback:0, dst:reg5, `C`
- [ 90] CallConstruct value_feedback:1, call_feedback:0, dst:reg6, callee:reg5, C
- [ b0] GetByValue value_feedback:2, keyed_feedback:0, dst:reg5, base:reg6, property:Int32(42)
- [ d0] GetById value_feedback:3, dst:reg6, base:reg5, `name` ([42].name)
- [ e8] End value:reg6
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] SetLexicalEnvironment environment:reg4
+ [ 50] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0, element_keys:[element_keys:Int32(42)]
+ [ 80] DynamicInitializeLexicalBinding `C`, src:reg6
+ [ 90] GetGlobal value_feedback:0, dst:reg6, `C`
+ [ a0] CallConstruct value_feedback:1, call_feedback:0, dst:reg6, callee:reg6
+ [ c0] GetByValue value_feedback:2, keyed_feedback:0, dst:reg6, base:reg6, property:Int32(42)
+ [ e0] GetById value_feedback:3, dst:reg5, base:reg6, `name`
+ [ f8] End value:reg5
C$638b9046
@@ -38,7 +39,7 @@ field$b4a03b9f numeric-class-field-name.js:2:10
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:0, is_catch_environment:false
+ [ 10] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:0, is_catch_environment:false
[ 28] SetLexicalEnvironment environment:reg4
- [ 30] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0 (42)
- [ 58] Return value:reg6
+ [ 30] NewClass dst:reg5, class_environment:reg6, class_blueprint_index:0 (42)
+ [ 58] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/numeric-getter-no-lhs-name.txt b/Tests/LibJS/Bytecode/expected/numeric-getter-no-lhs-name.txt
index e64b5e18bab..4eeecf837d0 100644
--- a/Tests/LibJS/Bytecode/expected/numeric-getter-no-lhs-name.txt
+++ b/Tests/LibJS/Bytecode/expected/numeric-getter-no-lhs-name.txt
@@ -1,19 +1,21 @@
-$091ab4cd numeric-getter-no-lhs-name.js:1:1
- Registers: 7
+$90d14739 numeric-getter-no-lhs-name.js:1:5
+ Registers: 8
Blocks: 1
Constants:
- [0] = Int32(0)
+ [0] = Undefined
+ [1] = Int32(0)
block0:
[ 0] Enter
- [ 8] NewObject dst:reg5
- [ 18] NewFunction dst:reg6, shared_function_data_index:0, home_object:reg5
- [ 30] SetFunctionName function:reg6, name:Int32(0)
- [ 40] PutByValue keyed_feedback:0, base:reg5, property:Int32(0), src:reg6, kind:Getter
- [ 60] SetGlobal `obj`, src:reg5
- [ 70] GetGlobal value_feedback:0, dst:reg5, `obj`
- [ 80] GetByValue value_feedback:1, keyed_feedback:1, dst:reg6, base:reg5, property:Int32(0) (obj[Int32(0)])
- [ a0] End value:reg6
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] NewObject dst:reg6
+ [ 28] NewFunction dst:reg7, shared_function_data_index:0 (get 0), home_object:reg6
+ [ 40] PutByValue keyed_feedback:0, base:reg6, property:Int32(0), src:reg7, kind:Getter
+ [ 60] SetGlobal `obj`, src:reg6
+ [ 70] GetGlobal value_feedback:0, dst:reg6, `obj`
+ [ 80] GetByValue value_feedback:1, keyed_feedback:1, dst:reg6, base:reg6, property:Int32(0)
+ [ a0] Mov dst:reg5, src:reg6
+ [ b0] End value:reg5
get 0$d054d509 numeric-getter-no-lhs-name.js:3:9
diff --git a/Tests/LibJS/Bytecode/expected/numeric-index-object-literal.txt b/Tests/LibJS/Bytecode/expected/numeric-index-object-literal.txt
index 28f6e28b4b9..2fca4d24c8e 100644
--- a/Tests/LibJS/Bytecode/expected/numeric-index-object-literal.txt
+++ b/Tests/LibJS/Bytecode/expected/numeric-index-object-literal.txt
@@ -1,4 +1,4 @@
-$2b997e90 numeric-index-object-literal.js:4:1
+$28d58d80 numeric-index-object-literal.js:4:1
Registers: 7
Blocks: 1
Constants:
@@ -6,21 +6,22 @@ $2b997e90 numeric-index-object-literal.js:4:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `test`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, test
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `test`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
test$815e337c numeric-index-object-literal.js:2:5
Registers: 6
Blocks: 1
Constants:
- [0] = Int32(100)
- [1] = Int32(1)
- [2] = Int32(200)
- [3] = Int32(2)
- [4] = Int32(300)
- [5] = Int32(3)
+ [0] = Int32(1)
+ [1] = Int32(100)
+ [2] = Int32(2)
+ [3] = Int32(200)
+ [4] = Int32(3)
+ [5] = Int32(300)
block0:
[ 0] Enter
diff --git a/Tests/LibJS/Bytecode/expected/numeric-property-key.txt b/Tests/LibJS/Bytecode/expected/numeric-property-key.txt
index 6c9f34aced4..dd55b01bcc4 100644
--- a/Tests/LibJS/Bytecode/expected/numeric-property-key.txt
+++ b/Tests/LibJS/Bytecode/expected/numeric-property-key.txt
@@ -1,14 +1,15 @@
-$28d58d80 numeric-property-key.js:4:1
- Registers: 6
+$bcc665b4 numeric-property-key.js:4:5
+ Registers: 7
Blocks: 1
Constants:
- [0] = Int32(20)
+ [0] = Undefined
[1] = Int32(3)
- [2] = Undefined
+ [2] = Int32(20)
block0:
[ 0] Enter
- [ 8] NewObject dst:reg5
- [ 18] PutByValue keyed_feedback:0, base:reg5, property:Int32(20), src:Int32(3), kind:Own
- [ 38] SetGlobal `obj`, src:reg5
- [ 48] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] NewObject dst:reg6
+ [ 28] PutByValue keyed_feedback:0, base:reg6, property:Int32(20), src:Int32(3), kind:Own
+ [ 48] SetGlobal `obj`, src:reg6
+ [ 58] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/object-destructuring-rebinds-source-variable.txt b/Tests/LibJS/Bytecode/expected/object-destructuring-rebinds-source-variable.txt
index d1dde3adf40..dd8ba2ae5e8 100644
--- a/Tests/LibJS/Bytecode/expected/object-destructuring-rebinds-source-variable.txt
+++ b/Tests/LibJS/Bytecode/expected/object-destructuring-rebinds-source-variable.txt
@@ -1,5 +1,5 @@
-$def8dd96 object-destructuring-rebinds-source-variable.js:5:1
- Registers: 11
+$dc34ec86 object-destructuring-rebinds-source-variable.js:5:1
+ Registers: 10
Blocks: 1
Constants:
[0] = Undefined
@@ -9,21 +9,22 @@ $def8dd96 object-destructuring-rebinds-source-variable.js:5:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `run`
- [ 40] NewObject dst:reg10
- [ 50] InitObjectLiteralProperty object:reg10, `first`, src:Int32(1), shape_cache_index:0, property_slot:0
- [ 68] InitObjectLiteralProperty object:reg10, `second`, src:Int32(2), shape_cache_index:0, property_slot:1
- [ 80] InitObjectLiteralProperty object:reg10, `third`, src:Int32(3), shape_cache_index:0, property_slot:2
- [ 98] CacheObjectShape object:reg10
- [ a8] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, run, arguments:[reg10]
- [ d0] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ f8] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `run`
+ [ 50] NewObject dst:reg9
+ [ 60] InitObjectLiteralProperty object:reg9, `first`, src:Int32(1), shape_cache_index:0, property_slot:0
+ [ 78] InitObjectLiteralProperty object:reg9, `second`, src:Int32(2), shape_cache_index:0, property_slot:1
+ [ 90] InitObjectLiteralProperty object:reg9, `third`, src:Int32(3), shape_cache_index:0, property_slot:2
+ [ a8] CacheObjectShape object:reg9
+ [ b8] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined, arguments:[reg9]
+ [ e0] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 108] End value:reg5
-run$41ed7d93 object-destructuring-rebinds-source-variable.js:2:5
- Registers: 9
+run$36ddb953 object-destructuring-rebinds-source-variable.js:2:5
+ Registers: 7
Blocks: 1
Locals: first~0, third~1
Constants:
@@ -31,18 +32,15 @@ run$41ed7d93 object-destructuring-rebinds-source-variable.js:2:5
block0:
[ 0] Enter
- [ 8] MovUndefined2 c0_dst:first~0, c1_dst:third~1
- [ 18] ThrowIfNullish src:arg0
- [ 20] Mov dst:reg5, src:arg0
- [ 30] GetById value_feedback:0, dst:reg6, base:reg5, `first`
- [ 48] Mov dst:first~0, src:reg6
- [ 58] GetById value_feedback:1, dst:reg6, base:reg5, `second`
- [ 70] Mov dst:arg0, src:reg6
- [ 80] GetById value_feedback:2, dst:reg6, base:reg5, `third`
- [ 98] Mov3 c0_dst:third~1, c0_src:reg6, c1_dst:reg5, c1_src:first~0, c2_dst:reg6, c2_src:arg0
- [ b8] Mov dst:reg7, src:third~1
- [ c8] NewArray dst:reg8, elements:[reg5, reg6, reg7]
- [ e8] Return value:reg8
+ [ 8] Mov dst:first~0, src:Undefined
+ [ 18] Mov dst:third~1, src:Undefined
+ [ 28] ThrowIfNullish src:arg0
+ [ 30] Mov dst:reg5, src:arg0
+ [ 40] GetById value_feedback:0, dst:first~0, base:reg5, `first`
+ [ 58] GetById value_feedback:1, dst:arg0, base:reg5, `second`
+ [ 70] GetById value_feedback:2, dst:third~1, base:reg5, `third`
+ [ 88] NewArray dst:reg5, elements:[first~0, arg0, third~1]
+ [ a8] Return value:reg5
[ 1, 2, 3 ]
diff --git a/Tests/LibJS/Bytecode/expected/object-rest-computed-key.txt b/Tests/LibJS/Bytecode/expected/object-rest-computed-key.txt
index 250c7afc0cd..b0fbd3d0f1e 100644
--- a/Tests/LibJS/Bytecode/expected/object-rest-computed-key.txt
+++ b/Tests/LibJS/Bytecode/expected/object-rest-computed-key.txt
@@ -1,24 +1,25 @@
-$fb46ff7d object-rest-computed-key.js:1:1
- Registers: 9
+$39071a5e object-rest-computed-key.js:1:5
+ Registers: 10
Blocks: 1
Constants:
- [0] = String("foo")
- [1] = Int32(1)
- [2] = Int32(2)
- [3] = Undefined
+ [0] = Undefined
+ [1] = String("foo")
+ [2] = Int32(1)
+ [3] = Int32(2)
block0:
[ 0] Enter
- [ 8] SetGlobal `a`, src:String("foo")
- [ 18] NewObject dst:reg5
- [ 28] InitObjectLiteralProperty object:reg5, `foo`, src:Int32(1), shape_cache_index:0, property_slot:0
- [ 40] InitObjectLiteralProperty object:reg5, `bar`, src:Int32(2), shape_cache_index:0, property_slot:1
- [ 58] CacheObjectShape object:reg5
- [ 68] ThrowIfNullish src:reg5
- [ 70] GetGlobal value_feedback:0, dst:reg7, `a`
- [ 80] ToPrimitiveWithStringHint dst:reg8, value:reg7
- [ 90] GetByValue value_feedback:1, keyed_feedback:0, dst:reg6, base:reg5, property:reg8
- [ b0] SetGlobal `b`, src:reg6
- [ c0] CopyObjectExcludingProperties dst:reg6, from_object:reg5, excluded_names:[reg8]
- [ e0] SetGlobal `rest`, src:reg6
- [ f0] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] SetGlobal `a`, src:String("foo")
+ [ 28] NewObject dst:reg6
+ [ 38] InitObjectLiteralProperty object:reg6, `foo`, src:Int32(1), shape_cache_index:0, property_slot:0
+ [ 50] InitObjectLiteralProperty object:reg6, `bar`, src:Int32(2), shape_cache_index:0, property_slot:1
+ [ 68] CacheObjectShape object:reg6
+ [ 78] ThrowIfNullish src:reg6
+ [ 80] GetGlobal value_feedback:0, dst:reg7, `a`
+ [ 90] ToPrimitiveWithStringHint dst:reg8, value:reg7
+ [ a0] GetByValue value_feedback:1, keyed_feedback:0, dst:reg9, base:reg6, property:reg8
+ [ c0] SetGlobal `b`, src:reg9
+ [ d0] CopyObjectExcludingProperties dst:reg9, from_object:reg6, excluded_names:[reg8]
+ [ f0] SetGlobal `rest`, src:reg9
+ [ 100] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/optional-chain-base-identifier.txt b/Tests/LibJS/Bytecode/expected/optional-chain-base-identifier.txt
index e459472ddbb..77e2eea7213 100644
--- a/Tests/LibJS/Bytecode/expected/optional-chain-base-identifier.txt
+++ b/Tests/LibJS/Bytecode/expected/optional-chain-base-identifier.txt
@@ -1,30 +1,31 @@
-$32b2807a optional-chain-base-identifier.js:1:1
- Registers: 9
- Blocks: 3
+$3643294e optional-chain-base-identifier.js:1:5
+ Registers: 8
+ Blocks: 4
Constants:
- [0] = Int32(44)
- [1] = Undefined
+ [0] = Undefined
+ [1] = Int32(44)
block0:
[ 0] Enter
- [ 8] NewObject dst:reg5
+ [ 8] Mov dst:reg5, src:Undefined
[ 18] NewObject dst:reg6
- [ 28] InitObjectLiteralProperty object:reg6, `b`, src:Int32(44), shape_cache_index:1, property_slot:0
- [ 40] CacheObjectShape object:reg6
- [ 50] InitObjectLiteralProperty object:reg5, `a`, src:reg6, shape_cache_index:0, property_slot:0
- [ 68] CacheObjectShape object:reg5
- [ 78] SetGlobal `obj`, src:reg5
- [ 88] MovSrcUndefined dst:reg5
- [ 90] GetGlobal value_feedback:0, dst:reg7, `obj`
- [ a0] GetById value_feedback:1, dst:reg8, base:reg7, `a` (obj.a)
- [ b8] Mov2 c0_dst:reg5, c0_src:reg7, c1_dst:reg6, c1_src:reg8
- [ d0] JumpNullish condition:reg6, true_target:block1, false_target:block2
+ [ 28] NewObject dst:reg7
+ [ 38] InitObjectLiteralProperty object:reg7, `b`, src:Int32(44), shape_cache_index:1, property_slot:0
+ [ 50] CacheObjectShape object:reg7
+ [ 60] InitObjectLiteralProperty object:reg6, `a`, src:reg7, shape_cache_index:0, property_slot:0
+ [ 78] CacheObjectShape object:reg6
+ [ 88] SetGlobal `obj`, src:reg6
+ [ 98] GetGlobal value_feedback:0, dst:reg6, `obj`
+ [ a8] GetById value_feedback:1, dst:reg6, base:reg6, `a`
+ [ c0] JumpNullish condition:reg6, true_target:block2, false_target:block1
block1:
- [ e0] MovSrcUndefined dst:reg6
- [ e8] End value:reg6
+ [ d0] GetById value_feedback:2, dst:reg6, base:reg6, `b`
+ [ e8] Jump target:block3
block2:
- [ f0] Mov dst:reg5, src:reg6
- [ 100] GetById value_feedback:2, dst:reg6, base:reg6, `b`
- [ 118] End value:reg6
+ [ f0] Mov dst:reg6, src:Undefined
+
+block3:
+ [ 100] Mov dst:reg5, src:reg6
+ [ 110] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/optional-chain.txt b/Tests/LibJS/Bytecode/expected/optional-chain.txt
index e40c19b168a..8c6abdfd384 100644
--- a/Tests/LibJS/Bytecode/expected/optional-chain.txt
+++ b/Tests/LibJS/Bytecode/expected/optional-chain.txt
@@ -1,5 +1,5 @@
-$f1bd7c92 optional-chain.js:25:1
- Registers: 8
+$f4816da2 optional-chain.js:25:1
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
@@ -7,163 +7,161 @@ $f1bd7c92 optional-chain.js:25:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `member`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, member, arguments:[Null]
- [ 40] GetGlobal value_feedback:2, dst:reg7, `nested_member`
- [ 50] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, nested_member, arguments:[Null]
- [ 78] GetGlobal value_feedback:4, dst:reg7, `call_no_args`
- [ 88] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg7, this_value:Undefined, call_no_args, arguments:[Null]
- [ b0] GetGlobal value_feedback:6, dst:reg7, `call_with_args`
- [ c0] Call value_feedback:7, call_feedback:3, dst:reg6, callee:reg7, this_value:Undefined, call_with_args, arguments:[Null]
- [ e8] GetGlobal value_feedback:8, dst:reg7, `computed`
- [ f8] Call value_feedback:9, call_feedback:4, dst:reg5, callee:reg7, this_value:Undefined, computed, arguments:[Null]
- [ 120] GetGlobal value_feedback:10, dst:reg7, `member_then_call`
- [ 130] Call value_feedback:11, call_feedback:5, dst:reg6, callee:reg7, this_value:Undefined, member_then_call, arguments:[Null]
- [ 158] End value:reg6
-
-
-member$36eb39cf optional-chain.js:7:5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `member`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Null]
+ [ 50] GetGlobal value_feedback:2, dst:reg6, `nested_member`
+ [ 60] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Null]
+ [ 88] GetGlobal value_feedback:4, dst:reg6, `call_no_args`
+ [ 98] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Null]
+ [ c0] GetGlobal value_feedback:6, dst:reg6, `call_with_args`
+ [ d0] Call value_feedback:7, call_feedback:3, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Null]
+ [ f8] GetGlobal value_feedback:8, dst:reg6, `computed`
+ [ 108] Call value_feedback:9, call_feedback:4, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Null]
+ [ 130] GetGlobal value_feedback:10, dst:reg6, `member_then_call`
+ [ 140] Call value_feedback:11, call_feedback:5, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Null]
+ [ 168] End value:reg5
+
+
+member$342748bf optional-chain.js:7:5
Registers: 7
- Blocks: 3
+ Blocks: 4
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:reg5, c0_src:Undefined, c1_dst:reg6, c1_src:arg0
- [ 20] JumpNullish condition:reg6, true_target:block1, false_target:block2
+ [ 8] Mov dst:reg5, src:arg0
+ [ 18] JumpNullish condition:reg5, true_target:block2, false_target:block1
block1:
- [ 30] MovSrcUndefined dst:reg6
- [ 38] Return value:reg6
+ [ 28] GetById value_feedback:0, dst:reg6, base:reg5, `x`
+ [ 40] Jump target:block3
block2:
- [ 40] Mov dst:reg5, src:reg6
- [ 50] GetById value_feedback:0, dst:reg6, base:reg6, `x`
- [ 68] Return value:reg6
+ [ 48] Mov dst:reg6, src:Undefined
+
+block3:
+ [ 58] Return value:reg6
-nested_member$85d10998 optional-chain.js:10:5
+nested_member$8b58ebb8 optional-chain.js:10:5
Registers: 7
- Blocks: 4
+ Blocks: 5
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:reg5, c0_src:Undefined, c1_dst:reg6, c1_src:arg0
- [ 20] JumpNullish condition:reg6, true_target:block1, false_target:block2
+ [ 8] Mov dst:reg5, src:arg0
+ [ 18] JumpNullish condition:reg5, true_target:block3, false_target:block1
block1:
- [ 30] MovSrcUndefined dst:reg6
- [ 38] Return value:reg6
+ [ 28] GetById value_feedback:0, dst:reg6, base:reg5, `x`
+ [ 40] JumpNullish condition:reg6, true_target:block3, false_target:block2
block2:
- [ 40] Mov dst:reg5, src:reg6
- [ 50] GetById value_feedback:0, dst:reg6, base:reg6, `x`
- [ 68] JumpNullish condition:reg6, true_target:block1, false_target:block3
+ [ 50] GetById value_feedback:1, dst:reg6, base:reg6, `y`
+ [ 68] Jump target:block4
block3:
- [ 78] Mov dst:reg5, src:reg6
- [ 88] GetById value_feedback:1, dst:reg6, base:reg6, `y`
- [ a0] Return value:reg6
+ [ 70] Mov dst:reg6, src:Undefined
+block4:
+ [ 80] Return value:reg6
-call_no_args$70a09739 optional-chain.js:13:5
- Registers: 8
- Blocks: 3
+
+call_no_args$e9b6bc91 optional-chain.js:13:5
+ Registers: 7
+ Blocks: 4
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:reg5, c0_src:Undefined, c1_dst:reg6, c1_src:arg0
- [ 20] JumpNullish condition:reg6, true_target:block1, false_target:block2
+ [ 8] Mov dst:reg5, src:arg0
+ [ 18] JumpNullish condition:reg5, true_target:block2, false_target:block1
block1:
- [ 30] MovSrcUndefined dst:reg6
- [ 38] Return value:reg6
+ [ 28] GetById value_feedback:0, dst:reg6, base:reg5, `foo`
+ [ 40] Call value_feedback:1, call_feedback:0, dst:reg6, callee:reg6, this_value:reg5
+ [ 60] Jump target:block3
block2:
- [ 40] Mov dst:reg5, src:reg6
- [ 50] GetById value_feedback:0, dst:reg6, base:reg6, `foo`
- [ 68] NewArray dst:reg7
- [ 78] CallWithArgumentArray value_feedback:1, call_feedback:0, dst:reg6, callee:reg6, this_value:reg5, arguments:reg7
- [ 98] MovSrcUndefined dst:reg5
- [ a0] Return value:reg6
+ [ 68] Mov dst:reg6, src:Undefined
+
+block3:
+ [ 78] Return value:reg6
-call_with_args$b7c2071f optional-chain.js:16:5
- Registers: 11
- Blocks: 3
+call_with_args$416fd2d7 optional-chain.js:16:5
+ Registers: 7
+ Blocks: 4
Constants:
- [0] = Undefined
- [1] = Int32(1)
- [2] = Int32(2)
- [3] = Int32(3)
+ [0] = Int32(1)
+ [1] = Int32(2)
+ [2] = Int32(3)
+ [3] = Undefined
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:reg5, c0_src:Undefined, c1_dst:reg6, c1_src:arg0
- [ 20] JumpNullish condition:reg6, true_target:block1, false_target:block2
+ [ 8] Mov dst:reg5, src:arg0
+ [ 18] JumpNullish condition:reg5, true_target:block2, false_target:block1
block1:
- [ 30] MovSrcUndefined dst:reg6
- [ 38] Return value:reg6
+ [ 28] GetById value_feedback:0, dst:reg6, base:reg5, `foo`
+ [ 40] Call value_feedback:1, call_feedback:0, dst:reg6, callee:reg6, this_value:reg5, arguments:[Int32(1), Int32(2), Int32(3)]
+ [ 70] Jump target:block3
block2:
- [ 40] Mov dst:reg5, src:reg6
- [ 50] GetById value_feedback:0, dst:reg6, base:reg6, `foo`
- [ 68] Mov3 c0_dst:reg8, c0_src:Int32(1), c1_dst:reg9, c1_src:Int32(2), c2_dst:reg10, c2_src:Int32(3)
- [ 88] NewArray dst:reg7, elements:[reg8, reg9, reg10]
- [ a8] CallWithArgumentArray value_feedback:1, call_feedback:0, dst:reg6, callee:reg6, this_value:reg5, arguments:reg7
- [ c8] MovSrcUndefined dst:reg5
- [ d0] Return value:reg6
+ [ 78] Mov dst:reg6, src:Undefined
+
+block3:
+ [ 88] Return value:reg6
-computed$9ef8515a optional-chain.js:19:5
+computed$9c34604a optional-chain.js:19:5
Registers: 7
- Blocks: 3
+ Blocks: 4
Constants:
- [0] = Undefined
- [1] = String("hello")
+ [0] = String("hello")
+ [1] = Undefined
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:reg5, c0_src:Undefined, c1_dst:reg6, c1_src:arg0
- [ 20] JumpNullish condition:reg6, true_target:block1, false_target:block2
+ [ 8] Mov dst:reg5, src:arg0
+ [ 18] JumpNullish condition:reg5, true_target:block2, false_target:block1
block1:
- [ 30] MovSrcUndefined dst:reg6
- [ 38] Return value:reg6
+ [ 28] GetById value_feedback:0, dst:reg6, base:reg5, `hello`
+ [ 40] Jump target:block3
block2:
- [ 40] Mov dst:reg5, src:reg6
- [ 50] GetById value_feedback:0, dst:reg6, base:reg6, `hello`
- [ 68] Return value:reg6
+ [ 48] Mov dst:reg6, src:Undefined
+
+block3:
+ [ 58] Return value:reg6
-member_then_call$b60035e3 optional-chain.js:22:5
+member_then_call$4271f2ab optional-chain.js:22:5
Registers: 8
- Blocks: 3
+ Blocks: 4
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:reg5, c0_src:Undefined, c1_dst:reg6, c1_src:arg0
- [ 20] JumpNullish condition:reg6, true_target:block1, false_target:block2
+ [ 8] Mov dst:reg5, src:arg0
+ [ 18] JumpNullish condition:reg5, true_target:block2, false_target:block1
block1:
- [ 30] MovSrcUndefined dst:reg6
- [ 38] Return value:reg6
+ [ 28] GetById value_feedback:0, dst:reg6, base:reg5, `x`
+ [ 40] GetById value_feedback:1, dst:reg7, base:reg6, `foo`
+ [ 58] Call value_feedback:2, call_feedback:0, dst:reg6, callee:reg7, this_value:reg6
+ [ 78] Jump target:block3
block2:
- [ 40] Mov dst:reg5, src:reg6
- [ 50] GetById value_feedback:0, dst:reg6, base:reg6, `x`
- [ 68] Mov dst:reg5, src:reg6
- [ 78] GetById value_feedback:1, dst:reg6, base:reg6, `foo`
- [ 90] NewArray dst:reg7
- [ a0] CallWithArgumentArray value_feedback:2, call_feedback:0, dst:reg6, callee:reg6, this_value:reg5, arguments:reg7
- [ c0] MovSrcUndefined dst:reg5
- [ c8] Return value:reg6
+ [ 80] Mov dst:reg6, src:Undefined
+
+block3:
+ [ 90] Return value:reg6
diff --git a/Tests/LibJS/Bytecode/expected/parameter-createvariable-order.txt b/Tests/LibJS/Bytecode/expected/parameter-createvariable-order.txt
index d16c2579285..21152beea85 100644
--- a/Tests/LibJS/Bytecode/expected/parameter-createvariable-order.txt
+++ b/Tests/LibJS/Bytecode/expected/parameter-createvariable-order.txt
@@ -1,4 +1,4 @@
-$cd444473 parameter-createvariable-order.js:7:1
+$d59017a3 parameter-createvariable-order.js:7:1
Registers: 7
Blocks: 1
Constants:
@@ -9,12 +9,13 @@ $cd444473 parameter-createvariable-order.js:7:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[Int32(1), Int32(2), Int32(3)]
- [ 48] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(1), Int32(2), Int32(3)]
+ [ 58] End value:reg5
-f$8982c134 parameter-createvariable-order.js:2:5
+f$9434bbb0 parameter-createvariable-order.js:2:9
Registers: 6
Blocks: 1
Locals: inner~0
@@ -24,27 +25,26 @@ f$8982c134 parameter-createvariable-order.js:2:5
block0:
[ 0] Enter
[ 8] CreateVariable `a`, is_immutable:false, is_global:false, is_strict:false
- [ 18] CreateVariable `b`, is_immutable:false, is_global:false, is_strict:false
- [ 28] CreateVariable `c`, is_immutable:false, is_global:false, is_strict:false
- [ 38] InitializeLexicalBinding `a`, src:arg0
- [ 50] InitializeLexicalBinding `b`, src:arg1
+ [ 18] InitializeLexicalBinding `a`, src:arg0
+ [ 30] CreateVariable `b`, is_immutable:false, is_global:false, is_strict:false
+ [ 40] InitializeLexicalBinding `b`, src:arg1
+ [ 58] CreateVariable `c`, is_immutable:false, is_global:false, is_strict:false
[ 68] InitializeLexicalBinding `c`, src:arg2
- [ 80] MovSrcUndefined dst:inner~0
- [ 88] NewFunction dst:reg5, shared_function_data_index:0 (inner)
- [ a0] Mov dst:inner~0, src:reg5
- [ b0] Call value_feedback:0, call_feedback:0, dst:reg5, callee:inner~0, this_value:Undefined, inner
- [ d0] Return value:reg5
+ [ 80] Mov dst:inner~0, src:Undefined
+ [ 90] NewFunction dst:inner~0, shared_function_data_index:0 (inner)
+ [ a8] Call value_feedback:0, call_feedback:0, dst:reg5, callee:inner~0, this_value:Undefined
+ [ c8] Return value:reg5
inner$1fee03d9 parameter-createvariable-order.js:3:9
- Registers: 8
+ Registers: 7
Blocks: 1
block0:
[ 0] Enter
[ 8] GetBinding value_feedback:0, dst:reg5, `a`
[ 20] GetBinding value_feedback:1, dst:reg6, `b`
- [ 38] Add arith_feedback:0, dst:reg7, lhs:reg5, rhs:reg6
- [ 48] GetBinding value_feedback:2, dst:reg5, `c`
- [ 60] Add arith_feedback:1, dst:reg6, lhs:reg7, rhs:reg5
- [ 70] Return value:reg6
+ [ 38] Add arith_feedback:0, dst:reg5, lhs:reg5, rhs:reg6
+ [ 48] GetBinding value_feedback:2, dst:reg6, `c`
+ [ 60] Add arith_feedback:1, dst:reg5, lhs:reg5, rhs:reg6
+ [ 70] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/parameter-environment-capacity.txt b/Tests/LibJS/Bytecode/expected/parameter-environment-capacity.txt
index 2dae3705d37..e01f541d2bf 100644
--- a/Tests/LibJS/Bytecode/expected/parameter-environment-capacity.txt
+++ b/Tests/LibJS/Bytecode/expected/parameter-environment-capacity.txt
@@ -1,48 +1,47 @@
-$0cc5fae9 parameter-environment-capacity.js:10:1
- Registers: 9
+$0a0209d9 parameter-environment-capacity.js:10:1
+ Registers: 8
Blocks: 1
Constants:
- [0] = String("method")
- [1] = Undefined
+ [0] = Undefined
+ [1] = String("method")
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `Strict`, is_immutable:true, is_global:false, is_strict:true
- [ 38] SetLexicalEnvironment environment:reg4
- [ 40] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:String("method")]
- [ 70] DynamicInitializeLexicalBinding `Strict`, src:reg6
- [ 80] GetGlobal value_feedback:0, dst:reg5, `sloppy`
- [ 90] Call value_feedback:1, call_feedback:0, dst:reg6, callee:reg5, this_value:Undefined, sloppy
- [ b0] GetGlobal value_feedback:2, dst:reg8, `Strict`
- [ c0] CallConstruct value_feedback:3, call_feedback:1, dst:reg7, callee:reg8, Strict
- [ e0] GetById value_feedback:4, dst:reg8, base:reg7, `method`
- [ f8] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg8, this_value:reg7, <object>.method
- [ 118] End value:reg5
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `Strict`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] SetLexicalEnvironment environment:reg4
+ [ 50] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0, element_keys:[element_keys:String("method")]
+ [ 80] DynamicInitializeLexicalBinding `Strict`, src:reg6
+ [ 90] GetGlobal value_feedback:0, dst:reg6, `sloppy`
+ [ a0] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ c0] GetGlobal value_feedback:2, dst:reg6, `Strict`
+ [ d0] CallConstruct value_feedback:3, call_feedback:1, dst:reg6, callee:reg6
+ [ f0] GetById value_feedback:4, dst:reg7, base:reg6, `method`
+ [ 108] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg7, this_value:reg6
+ [ 128] End value:reg5
-sloppy$b222ab46 parameter-environment-capacity.js:7:5
- Registers: 7
+sloppy$1bf697a3 parameter-environment-capacity.js:6:17
+ Registers: 6
Blocks: 3
Constants:
[0] = Int32(1)
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:2, is_catch_environment:false
- [ 28] CreateVariable `a`, is_immutable:false, is_global:false, is_strict:false
- [ 38] CreateArguments is_immutable:false, creates_parameter_bindings:false
- [ 48] JumpUndefined condition:arg0, true_target:block1, false_target:block2
+ [ 8] CreateVariable `a`, is_immutable:false, is_global:false, is_strict:false
+ [ 18] CreateArguments is_immutable:false, creates_parameter_bindings:false
+ [ 28] JumpUndefined condition:arg0, true_target:block1, false_target:block2
block1:
- [ 58] Mov dst:arg0, src:Int32(1)
+ [ 38] Mov dst:arg0, src:Int32(1)
block2:
- [ 68] InitializeLexicalBinding `a`, src:arg0
- [ 80] NewFunction dst:reg6, shared_function_data_index:0
- [ 98] Return value:reg6
+ [ 48] InitializeLexicalBinding `a`, src:arg0
+ [ 60] NewFunction dst:reg5, shared_function_data_index:0
+ [ 78] Return value:reg5
Strict$80fdfc06
@@ -56,8 +55,8 @@ block0:
[ 8] End value:Undefined
-method$6a5f3dc4 parameter-environment-capacity.js:12:9
- Registers: 8
+method$df6331aa parameter-environment-capacity.js:11:12
+ Registers: 7
Blocks: 3
Constants:
[0] = String("x")
@@ -65,21 +64,22 @@ method$6a5f3dc4 parameter-environment-capacity.js:12:9
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:3, is_catch_environment:false
- [ 28] CreateVariable `mode`, is_immutable:false, is_global:false, is_strict:false
- [ 38] CreateVariable `index`, is_immutable:false, is_global:false, is_strict:false
- [ 48] JumpUndefined condition:arg0, true_target:block1, false_target:block2
+ [ 8] CreateVariable `mode`, is_immutable:false, is_global:false, is_strict:false
+ [ 18] CreateVariable `index`, is_immutable:false, is_global:false, is_strict:false
+ [ 28] GetLexicalEnvironment dst:reg4
+ [ 30] JumpUndefined condition:arg0, true_target:block1, false_target:block2
block1:
- [ 58] Mov dst:arg0, src:String("x")
+ [ 40] Mov dst:arg0, src:String("x")
block2:
- [ 68] InitializeLexicalBinding `mode`, src:arg0
- [ 80] InitializeLexicalBinding `index`, src:arg1
- [ 98] CreateVariable `active`, is_immutable:true, is_global:false, is_strict:true
- [ a8] GetBinding value_feedback:0, dst:reg6, `mode`
- [ c0] StrictlyEquals arith_feedback:0, dst:reg7, lhs:reg6, rhs:String("a")
- [ d0] InitializeLexicalBinding `active`, src:reg7
- [ e8] NewFunction dst:reg7, shared_function_data_index:0
- [ 100] Return value:reg7
+ [ 50] InitializeLexicalBinding `mode`, src:arg0
+ [ 68] InitializeLexicalBinding `index`, src:arg1
+ [ 80] CreateVariableEnvironment capacity:1
+ [ 88] GetLexicalEnvironment dst:reg5
+ [ 90] CreateVariable `active`, is_immutable:true, is_global:false, is_strict:true
+ [ a0] GetBinding value_feedback:0, dst:reg6, `mode`
+ [ b8] StrictlyEquals arith_feedback:0, dst:reg6, lhs:reg6, rhs:String("a")
+ [ c8] InitializeLexicalBinding `active`, src:reg6
+ [ e0] NewFunction dst:reg6, shared_function_data_index:0
+ [ f8] Return value:reg6
diff --git a/Tests/LibJS/Bytecode/expected/postfix-increment-private-member.txt b/Tests/LibJS/Bytecode/expected/postfix-increment-private-member.txt
index 88ea4bfd94c..24192491472 100644
--- a/Tests/LibJS/Bytecode/expected/postfix-increment-private-member.txt
+++ b/Tests/LibJS/Bytecode/expected/postfix-increment-private-member.txt
@@ -1,26 +1,27 @@
-$ae8c96e2 postfix-increment-private-member.js:1:1
+$abc8a5d2 postfix-increment-private-member.js:1:1
Registers: 8
Blocks: 1
Constants:
- [0] = String("nextId")
- [1] = Undefined
+ [0] = Undefined
+ [1] = String("nextId")
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
- [ 38] CreatePrivateEnvironment
- [ 40] AddPrivateName `#c`
- [ 48] SetLexicalEnvironment environment:reg4
- [ 50] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:String("nextId")]
- [ 80] LeavePrivateEnvironment
- [ 88] DynamicInitializeLexicalBinding `C`, src:reg6
- [ 98] GetGlobal value_feedback:0, dst:reg7, `C`
- [ a8] CallConstruct value_feedback:1, call_feedback:0, dst:reg5, callee:reg7, C
- [ c8] GetById value_feedback:2, dst:reg7, base:reg5, `nextId`
- [ e0] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:reg5, <object>.nextId
- [ 100] End value:reg6
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] CreatePrivateEnvironment
+ [ 50] AddPrivateName `#c`
+ [ 58] SetLexicalEnvironment environment:reg4
+ [ 60] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0, element_keys:[element_keys:String("nextId")]
+ [ 90] LeavePrivateEnvironment
+ [ 98] DynamicInitializeLexicalBinding `C`, src:reg6
+ [ a8] GetGlobal value_feedback:0, dst:reg6, `C`
+ [ b8] CallConstruct value_feedback:1, call_feedback:0, dst:reg6, callee:reg6
+ [ d8] GetById value_feedback:2, dst:reg7, base:reg6, `nextId`
+ [ f0] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6
+ [ 110] End value:reg5
C$638b9046
diff --git a/Tests/LibJS/Bytecode/expected/postfix-update-in-logical-and.txt b/Tests/LibJS/Bytecode/expected/postfix-update-in-logical-and.txt
index 1aa721216b0..3241a3cc683 100644
--- a/Tests/LibJS/Bytecode/expected/postfix-update-in-logical-and.txt
+++ b/Tests/LibJS/Bytecode/expected/postfix-update-in-logical-and.txt
@@ -1,4 +1,4 @@
-$acfb7718 postfix-update-in-logical-and.js:4:1
+$aa378608 postfix-update-in-logical-and.js:4:1
Registers: 7
Blocks: 1
Constants:
@@ -7,13 +7,14 @@ $acfb7718 postfix-update-in-logical-and.js:4:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `postfixInLogicalAnd`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, postfixInLogicalAnd, arguments:[Int32(5)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `postfixInLogicalAnd`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(5)]
+ [ 50] End value:reg5
-postfixInLogicalAnd$ff9880b2 postfix-update-in-logical-and.js:2:5
- Registers: 8
+postfixInLogicalAnd$025c71c2 postfix-update-in-logical-and.js:2:5
+ Registers: 7
Blocks: 3
Constants:
[0] = Int32(0)
@@ -21,12 +22,11 @@ postfixInLogicalAnd$ff9880b2 postfix-update-in-logical-and.js:2:5
block0:
[ 0] Enter
[ 8] GreaterThanRhsInt32 arith_feedback:0, dst:reg5, lhs:arg0, rhs:0
- [ 18] Mov dst:reg6, src:reg5
- [ 28] JumpFalse condition:reg5, target:block2
+ [ 18] JumpFalse condition:reg5, target:block2
block1:
- [ 38] PostfixDecrement arith_feedback:1, dst:reg7, src:arg0
- [ 48] Mov dst:reg6, src:reg7
+ [ 28] PostfixDecrement arith_feedback:1, dst:reg6, src:arg0
+ [ 38] Mov dst:reg5, src:reg6
block2:
- [ 58] Return value:reg6
+ [ 48] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/private-identifier-access-patterns.txt b/Tests/LibJS/Bytecode/expected/private-identifier-access-patterns.txt
index 50c9db3eabd..c09449aefbc 100644
--- a/Tests/LibJS/Bytecode/expected/private-identifier-access-patterns.txt
+++ b/Tests/LibJS/Bytecode/expected/private-identifier-access-patterns.txt
@@ -1,19 +1,20 @@
-$87b8bc45 private-identifier-access-patterns.js:1:1
- Registers: 7
+$84f4cb35 private-identifier-access-patterns.js:1:1
+ Registers: 8
Blocks: 1
Constants:
- [0] = String("method")
- [1] = Undefined
+ [0] = Undefined
+ [1] = String("method")
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
- [ 38] CreatePrivateEnvironment
- [ 40] AddPrivateName `#x`
- [ 48] SetLexicalEnvironment environment:reg4
- [ 50] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:String("method")]
- [ 80] LeavePrivateEnvironment
- [ 88] DynamicInitializeLexicalBinding `C`, src:reg6
- [ 98] End value:Undefined
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] CreatePrivateEnvironment
+ [ 50] AddPrivateName `#x`
+ [ 58] SetLexicalEnvironment environment:reg4
+ [ 60] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0, element_keys:[element_keys:String("method")]
+ [ 90] LeavePrivateEnvironment
+ [ 98] DynamicInitializeLexicalBinding `C`, src:reg6
+ [ a8] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/private-logical-assignment-register-order.txt b/Tests/LibJS/Bytecode/expected/private-logical-assignment-register-order.txt
index a3c117ac490..225e9a9fe93 100644
--- a/Tests/LibJS/Bytecode/expected/private-logical-assignment-register-order.txt
+++ b/Tests/LibJS/Bytecode/expected/private-logical-assignment-register-order.txt
@@ -1,26 +1,27 @@
-$ae8c96e2 private-logical-assignment-register-order.js:1:1
+$abc8a5d2 private-logical-assignment-register-order.js:1:1
Registers: 8
Blocks: 1
Constants:
- [0] = String("f")
- [1] = Undefined
+ [0] = Undefined
+ [1] = String("f")
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
- [ 38] CreatePrivateEnvironment
- [ 40] AddPrivateName `#x`
- [ 48] SetLexicalEnvironment environment:reg4
- [ 50] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:String("f")]
- [ 80] LeavePrivateEnvironment
- [ 88] DynamicInitializeLexicalBinding `C`, src:reg6
- [ 98] GetGlobal value_feedback:0, dst:reg7, `C`
- [ a8] CallConstruct value_feedback:1, call_feedback:0, dst:reg5, callee:reg7, C
- [ c8] GetById value_feedback:2, dst:reg7, base:reg5, `f`
- [ e0] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:reg5, <object>.f
- [ 100] End value:reg6
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] CreatePrivateEnvironment
+ [ 50] AddPrivateName `#x`
+ [ 58] SetLexicalEnvironment environment:reg4
+ [ 60] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0, element_keys:[element_keys:String("f")]
+ [ 90] LeavePrivateEnvironment
+ [ 98] DynamicInitializeLexicalBinding `C`, src:reg6
+ [ a8] GetGlobal value_feedback:0, dst:reg6, `C`
+ [ b8] CallConstruct value_feedback:1, call_feedback:0, dst:reg6, callee:reg6
+ [ d8] GetById value_feedback:2, dst:reg7, base:reg6, `f`
+ [ f0] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6
+ [ 110] End value:reg5
C$638b9046
@@ -34,9 +35,9 @@ block0:
[ 8] End value:Undefined
-f$ab557ac3 private-logical-assignment-register-order.js:3:19
+f$1fa31a28 private-logical-assignment-register-order.js:3:16
Registers: 7
- Blocks: 4
+ Blocks: 3
Constants:
[0] = Int32(1)
[1] = Undefined
@@ -44,15 +45,12 @@ f$ab557ac3 private-logical-assignment-register-order.js:3:19
block0:
[ 0] Enter
[ 8] GetPrivateById dst:reg5, base:this, `#x`
- [ 18] JumpFalse condition:reg5, target:block2
+ [ 18] Mov dst:reg6, src:reg5
+ [ 28] JumpFalse condition:reg6, target:block2
block1:
- [ 28] Mov dst:reg6, src:Int32(1)
- [ 38] PutPrivateById base:this, `#x`, src:reg6
- [ 48] Jump target:block3
+ [ 38] Mov dst:reg6, src:Int32(1)
+ [ 48] PutPrivateById base:this, `#x`, src:reg6
block2:
- [ 50] Mov dst:reg6, src:reg5
-
-block3:
- [ 60] End value:Undefined
+ [ 58] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/private-method-call-description.txt b/Tests/LibJS/Bytecode/expected/private-method-call-description.txt
index 768c0ae253c..475932a323f 100644
--- a/Tests/LibJS/Bytecode/expected/private-method-call-description.txt
+++ b/Tests/LibJS/Bytecode/expected/private-method-call-description.txt
@@ -1,26 +1,27 @@
-$ae8c96e2 private-method-call-description.js:1:1
+$abc8a5d2 private-method-call-description.js:1:1
Registers: 8
Blocks: 1
Constants:
- [0] = String("call")
- [1] = Undefined
+ [0] = Undefined
+ [1] = String("call")
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
- [ 38] CreatePrivateEnvironment
- [ 40] AddPrivateName `#m`
- [ 48] SetLexicalEnvironment environment:reg4
- [ 50] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:String("call")]
- [ 80] LeavePrivateEnvironment
- [ 88] DynamicInitializeLexicalBinding `C`, src:reg6
- [ 98] GetGlobal value_feedback:0, dst:reg7, `C`
- [ a8] CallConstruct value_feedback:1, call_feedback:0, dst:reg5, callee:reg7, C
- [ c8] GetById value_feedback:2, dst:reg7, base:reg5, `call`
- [ e0] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:reg5, <object>.call
- [ 100] End value:reg6
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] CreatePrivateEnvironment
+ [ 50] AddPrivateName `#m`
+ [ 58] SetLexicalEnvironment environment:reg4
+ [ 60] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0, element_keys:[element_keys:String("call")]
+ [ 90] LeavePrivateEnvironment
+ [ 98] DynamicInitializeLexicalBinding `C`, src:reg6
+ [ a8] GetGlobal value_feedback:0, dst:reg6, `C`
+ [ b8] CallConstruct value_feedback:1, call_feedback:0, dst:reg6, callee:reg6
+ [ d8] GetById value_feedback:2, dst:reg7, base:reg6, `call`
+ [ f0] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6
+ [ 110] End value:reg5
C$638b9046
@@ -35,13 +36,13 @@ block0:
call$4b20f1d0 private-method-call-description.js:6:9
- Registers: 7
+ Registers: 6
Blocks: 1
block0:
[ 0] Enter
- [ 8] GetPrivateById dst:reg6, base:this, `#m`
- [ 18] Call value_feedback:0, call_feedback:0, dst:reg5, callee:reg6, this_value:this, this.#m
+ [ 8] GetPrivateById dst:reg5, base:this, `#m`
+ [ 18] Call value_feedback:0, call_feedback:0, dst:reg5, callee:reg5, this_value:this
[ 38] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/regex-literals.txt b/Tests/LibJS/Bytecode/expected/regex-literals.txt
index 94d99eaf133..ab6c6791f99 100644
--- a/Tests/LibJS/Bytecode/expected/regex-literals.txt
+++ b/Tests/LibJS/Bytecode/expected/regex-literals.txt
@@ -1,33 +1,33 @@
-$99fa450e regex-literals.js:2:1
+$42e0243a regex-literals.js:2:5
Registers: 7
Blocks: 1
Constants:
- [0] = Int32(1)
- [1] = Undefined
+ [0] = Undefined
+ [1] = Int32(1)
[2] = String("abc123")
block0:
[ 0] Enter
- [ 8] NewRegExp dst:reg5, foo,
- [ 18] DynamicInitializeLexicalBinding `a`, src:reg5
- [ 28] NewRegExp dst:reg5, bar, gi
- [ 38] DynamicInitializeLexicalBinding `b`, src:reg5
- [ 48] NewRegExp dst:reg5, baz, i
- [ 58] AddLhsInt32 arith_feedback:0, dst:reg6, lhs:1, rhs:reg5
- [ 68] DynamicInitializeLexicalBinding `c`, src:reg6
- [ 78] GetGlobal value_feedback:0, dst:reg5, `matchDigits`
- [ 88] Call value_feedback:1, call_feedback:0, dst:reg6, callee:reg5, this_value:Undefined, matchDigits, arguments:[String("abc123")]
- [ b0] End value:reg6
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] NewRegExp dst:reg6, foo,
+ [ 28] DynamicInitializeLexicalBinding `a`, src:reg6
+ [ 38] NewRegExp dst:reg6, bar, gi
+ [ 48] DynamicInitializeLexicalBinding `b`, src:reg6
+ [ 58] NewRegExp dst:reg6, baz, i
+ [ 68] AddLhsInt32 arith_feedback:0, dst:reg6, lhs:1, rhs:reg6
+ [ 78] DynamicInitializeLexicalBinding `c`, src:reg6
+ [ 88] GetGlobal value_feedback:0, dst:reg6, `matchDigits`
+ [ 98] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[String("abc123")]
+ [ c0] End value:reg5
-matchDigits$cfe7cda7 regex-literals.js:8:5
- Registers: 9
+matchDigits$cd23dc97 regex-literals.js:8:5
+ Registers: 7
Blocks: 1
block0:
[ 0] Enter
- [ 8] NewRegExp dst:reg6, \d+, g
- [ 18] GetById value_feedback:0, dst:reg7, base:reg6, `test`
- [ 30] Mov dst:reg8, src:arg0
- [ 40] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg7, this_value:reg6, <object>.test, arguments:[reg8]
- [ 68] Return value:reg5
+ [ 8] NewRegExp dst:reg5, \d+, g
+ [ 18] GetById value_feedback:0, dst:reg6, base:reg5, `test`
+ [ 30] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:reg5, arguments:[arg0]
+ [ 58] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/resolve-this-caching.txt b/Tests/LibJS/Bytecode/expected/resolve-this-caching.txt
index 692b62ef4c7..880dc266e8d 100644
--- a/Tests/LibJS/Bytecode/expected/resolve-this-caching.txt
+++ b/Tests/LibJS/Bytecode/expected/resolve-this-caching.txt
@@ -1,4 +1,4 @@
-$2b997e90 resolve-this-caching.js:4:1
+$28d58d80 resolve-this-caching.js:4:1
Registers: 7
Blocks: 1
Constants:
@@ -6,32 +6,33 @@ $2b997e90 resolve-this-caching.js:4:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `foo`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, foo
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `foo`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
foo$9e71f40c resolve-this-caching.js:2:5
- Registers: 7
+ Registers: 6
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] NewFunction dst:reg6, shared_function_data_index:0
- [ 20] Call value_feedback:0, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 8] NewFunction dst:reg5, shared_function_data_index:0
+ [ 20] Call value_feedback:0, call_feedback:0, dst:reg5, callee:reg5, this_value:Undefined
[ 40] Return value:reg5
$1243b2a2 resolve-this-caching.js:2:13
- Registers: 8
+ Registers: 7
Blocks: 1
block0:
[ 0] Enter
[ 8] ResolveThisBinding
- [ 10] GetById value_feedback:0, dst:reg5, base:this, `x` (this.x)
- [ 28] GetById value_feedback:1, dst:reg6, base:this, `y` (this.y)
- [ 40] Add arith_feedback:0, dst:reg7, lhs:reg5, rhs:reg6
- [ 50] Return value:reg7
+ [ 10] GetById value_feedback:0, dst:reg5, base:this, `x`
+ [ 28] GetById value_feedback:1, dst:reg6, base:this, `y`
+ [ 40] Add arith_feedback:0, dst:reg5, lhs:reg5, rhs:reg6
+ [ 50] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/right-shift-by-zero.txt b/Tests/LibJS/Bytecode/expected/right-shift-by-zero.txt
index 599d1fc2bac..7191c3ae57e 100644
--- a/Tests/LibJS/Bytecode/expected/right-shift-by-zero.txt
+++ b/Tests/LibJS/Bytecode/expected/right-shift-by-zero.txt
@@ -1,4 +1,4 @@
-$9431c529 right-shift-by-zero.js:5:1
+$916dd419 right-shift-by-zero.js:5:1
Registers: 7
Blocks: 1
Constants:
@@ -7,9 +7,10 @@ $9431c529 right-shift-by-zero.js:5:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `foo`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, foo, arguments:[Double(1.5)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `foo`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Double(1.5)]
+ [ 50] End value:reg5
foo$17881964 right-shift-by-zero.js:2:5
diff --git a/Tests/LibJS/Bytecode/expected/sequential-try-blocks.txt b/Tests/LibJS/Bytecode/expected/sequential-try-blocks.txt
index 66bd1c017b8..483f7770277 100644
--- a/Tests/LibJS/Bytecode/expected/sequential-try-blocks.txt
+++ b/Tests/LibJS/Bytecode/expected/sequential-try-blocks.txt
@@ -1,66 +1,66 @@
-$bdbbce45 sequential-try-blocks.js:17:1
- Registers: 10
+$b56ffb15 sequential-try-blocks.js:17:1
+ Registers: 9
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `sequentialTryCatch`
- [ 40] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, sequentialTryCatch
- [ 60] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 88] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `sequentialTryCatch`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined
+ [ 70] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 98] End value:reg5
-sequentialTryCatch$0d4847fe sequential-try-blocks.js:2:5
- Registers: 8
- Blocks: 5
- Locals: e~0, e~1, result~2
+sequentialTryCatch$d96d6fd5 sequential-try-blocks.js:2:9
+ Registers: 6
+ Blocks: 6
+ Locals: result~0, e~1, e~2
Constants:
[0] = String("")
- [1] = String("b")
- [2] = String("a")
- [3] = Int32(1)
- [4] = String("d")
+ [1] = String("a")
+ [2] = Int32(1)
+ [3] = <Empty>
+ [4] = String("b")
[5] = String("c")
[6] = Int32(2)
+ [7] = String("d")
block0:
[ 0] Enter
- [ 8] Mov dst:result~2, src:String("")
- [ 18] Jump target:block2
+ [ 8] Mov dst:result~0, src:String("")
block1:
- [ 20] Catch value_feedback:0, dst:reg5
- [ 28] Mov2 c0_dst:e~0, c0_src:reg5, c1_dst:reg6, c1_src:result~2
- [ 40] Add arith_feedback:0, dst:reg7, lhs:reg6, rhs:String("b")
- [ 50] Mov dst:result~2, src:reg7
- [ 60] Jump target:block4
+ [ 18] Add arith_feedback:0, dst:result~0, lhs:result~0, rhs:String("a")
+ [ 28] Throw src:Int32(1)
block2:
- [ 68] Mov dst:reg5, src:result~2
- [ 78] Add arith_feedback:1, dst:reg7, lhs:reg5, rhs:String("a")
- [ 88] Mov dst:result~2, src:reg7
- [ 98] Throw src:Int32(1)
+ [ 30] Catch value_feedback:0, dst:reg5
+ [ 38] Mov dst:e~1, src:<Empty>
+ [ 48] Mov dst:e~1, src:reg5
+ [ 58] Add arith_feedback:1, dst:result~0, lhs:result~0, rhs:String("b")
+ [ 68] Jump target:block3
block3:
- [ a0] Catch value_feedback:1, dst:reg7
- [ a8] Mov2 c0_dst:e~1, c0_src:reg7, c1_dst:reg5, c1_src:result~2
- [ c0] Add arith_feedback:2, dst:reg6, lhs:reg5, rhs:String("d")
- [ d0] Mov dst:result~2, src:reg6
- [ e0] Return value:result~2
+ [ 70] Add arith_feedback:2, dst:result~0, lhs:result~0, rhs:String("c")
+ [ 80] Throw src:Int32(2)
block4:
- [ e8] Mov dst:reg7, src:result~2
- [ f8] Add arith_feedback:3, dst:reg6, lhs:reg7, rhs:String("c")
- [ 108] Mov dst:result~2, src:reg6
- [ 118] Throw src:Int32(2)
+ [ 88] Catch value_feedback:1, dst:reg5
+ [ 90] Mov dst:e~2, src:<Empty>
+ [ a0] Mov dst:e~2, src:reg5
+ [ b0] Add arith_feedback:3, dst:result~0, lhs:result~0, rhs:String("d")
+ [ c0] Jump target:block5
+
+block5:
+ [ c8] Return value:result~0
Exception handlers:
- [ 68 .. a0] => handler block1
- [ e8 .. 120] => handler block3
+ [ 18 .. 30] => handler block2
+ [ 70 .. 88] => handler block4
"abcd"
diff --git a/Tests/LibJS/Bytecode/expected/strict-global-assignment.txt b/Tests/LibJS/Bytecode/expected/strict-global-assignment.txt
index 1d8c32a2d7b..f2905207200 100644
--- a/Tests/LibJS/Bytecode/expected/strict-global-assignment.txt
+++ b/Tests/LibJS/Bytecode/expected/strict-global-assignment.txt
@@ -1,34 +1,42 @@
-$20e41fb6 strict-global-assignment.js:2:1
+$2d2a9e5a strict-global-assignment.js:1:1
Registers: 8
- Blocks: 6
+ Blocks: 7
Constants:
- [0] = String("use strict")
- [1] = Int32(0)
- [2] = Null
- [3] = Int32(1)
+ [0] = Undefined
+ [1] = String("use strict")
+ [2] = Int32(0)
+ [3] = Null
+ [4] = Int32(1)
block0:
[ 0] Enter
- [ 8] ResolveGlobalBinding dst:reg5, `counter`
- [ 18] JumpFalse condition:reg5, target:block2
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:String("use strict")
+ [ 28] ResolveGlobalBinding dst:reg6, `counter`
+ [ 38] JumpIf condition:reg6, true_target:block1, false_target:block2
block1:
- [ 28] SetGlobal `counter`, src:Int32(0)
- [ 38] Jump target:block3
+ [ 48] SetGlobal `counter`, src:Int32(0)
+ [ 58] Jump target:block3
block2:
- [ 40] SetResolvedBinding environment:Null, `counter`, src:Int32(0)
+ [ 60] SetResolvedBinding environment:Null, `counter`, src:Int32(0)
+ [ 70] Jump target:block3
block3:
- [ 50] ResolveGlobalBinding dst:reg5, `counter`
- [ 60] GetGlobal value_feedback:0, dst:reg6, `counter`
- [ 70] AddRhsInt32 arith_feedback:0, dst:reg7, lhs:reg6, rhs:1
- [ 80] JumpFalse condition:reg5, target:block5
+ [ 78] ResolveGlobalBinding dst:reg6, `counter`
+ [ 88] GetGlobal value_feedback:0, dst:reg7, `counter`
+ [ 98] AddRhsInt32 arith_feedback:0, dst:reg7, lhs:reg7, rhs:1
+ [ a8] JumpIf condition:reg6, true_target:block4, false_target:block5
block4:
- [ 90] SetGlobal `counter`, src:reg7
- [ a0] End value:reg7
+ [ b8] SetGlobal `counter`, src:reg7
+ [ c8] Jump target:block6
block5:
- [ a8] SetResolvedBinding environment:Null, `counter`, src:reg7
- [ b8] End value:reg7
+ [ d0] SetResolvedBinding environment:Null, `counter`, src:reg7
+ [ e0] Jump target:block6
+
+block6:
+ [ e8] Mov dst:reg5, src:reg7
+ [ f8] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/super-call-spread-register-order.txt b/Tests/LibJS/Bytecode/expected/super-call-spread-register-order.txt
index 7fcbd2fa87e..e2127c8aa79 100644
--- a/Tests/LibJS/Bytecode/expected/super-call-spread-register-order.txt
+++ b/Tests/LibJS/Bytecode/expected/super-call-spread-register-order.txt
@@ -1,5 +1,5 @@
-$745d24d5 super-call-spread-register-order.js:1:1
- Registers: 9
+$7ca8f805 super-call-spread-register-order.js:1:1
+ Registers: 11
Blocks: 1
Constants:
[0] = Undefined
@@ -7,20 +7,21 @@ $745d24d5 super-call-spread-register-order.js:1:1
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
- [ 38] GetGlobal value_feedback:0, dst:reg6, `Object`
- [ 48] GetClassProtoParent dst:reg7, super_class:reg6
- [ 58] SetLexicalEnvironment environment:reg4
- [ 60] NewClass dst:reg8, super_class:reg6, proto_parent:reg7, class_environment:reg5, class_blueprint_index:0
- [ 88] DynamicInitializeLexicalBinding `C`, src:reg8
- [ 98] GetGlobal value_feedback:1, dst:reg5, `C`
- [ a8] CallConstruct value_feedback:2, call_feedback:0, dst:reg8, callee:reg5, C
- [ c8] End value:reg8
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] GetGlobal value_feedback:0, dst:reg9, `Object`
+ [ 58] GetClassProtoParent dst:reg10, super_class:reg9
+ [ 68] SetLexicalEnvironment environment:reg4
+ [ 70] NewClass dst:reg6, super_class:reg9, proto_parent:reg10, class_environment:reg7, class_blueprint_index:0
+ [ 98] DynamicInitializeLexicalBinding `C`, src:reg6
+ [ a8] GetGlobal value_feedback:1, dst:reg6, `C`
+ [ b8] CallConstruct value_feedback:2, call_feedback:0, dst:reg5, callee:reg6
+ [ d8] End value:reg5
-C$3cf8ba4b super-call-spread-register-order.js:3:14
- Registers: 8
+C$c06f7c65 super-call-spread-register-order.js:2:17
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
@@ -31,5 +32,5 @@ block0:
[ 18] GetSuperConstructor dst:reg5
[ 20] NewArray dst:reg6
[ 30] ArrayAppend dst:reg6, src:arg0, is_spread:true
- [ 40] SuperCallWithArgumentArray value_feedback:0, call_feedback:0, dst:reg7, super_constructor:reg5, arguments:reg6, is_synthetic:false
+ [ 40] SuperCallWithArgumentArray value_feedback:0, call_feedback:0, dst:reg5, super_constructor:reg5, arguments:reg6, is_synthetic:false
[ 58] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/super-computed-eval-order.txt b/Tests/LibJS/Bytecode/expected/super-computed-eval-order.txt
index bd1d5598124..160bab42761 100644
--- a/Tests/LibJS/Bytecode/expected/super-computed-eval-order.txt
+++ b/Tests/LibJS/Bytecode/expected/super-computed-eval-order.txt
@@ -1,34 +1,35 @@
-$a640c3b2 super-computed-eval-order.js:1:1
- Registers: 9
+$c4ac1f62 super-computed-eval-order.js:1:1
+ Registers: 11
Blocks: 1
Constants:
- [0] = String("test")
- [1] = Undefined
+ [0] = Undefined
+ [1] = String("test")
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `Base`, is_immutable:true, is_global:false, is_strict:true
- [ 38] SetLexicalEnvironment environment:reg4
- [ 40] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0
- [ 68] DynamicInitializeLexicalBinding `Base`, src:reg6
- [ 78] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:1, is_catch_environment:false
- [ 90] CreateVariable `Derived`, is_immutable:true, is_global:false, is_strict:true
- [ a0] GetGlobal value_feedback:0, dst:reg5, `Base`
- [ b0] GetClassProtoParent dst:reg7, super_class:reg5
- [ c0] SetLexicalEnvironment environment:reg4
- [ c8] NewClass dst:reg8, super_class:reg5, proto_parent:reg7, class_environment:reg6, class_blueprint_index:1, element_keys:[element_keys:String("test")]
- [ f8] DynamicInitializeLexicalBinding `Derived`, src:reg8
- [ 108] GetGlobal value_feedback:1, dst:reg5, `Derived`
- [ 118] CallConstruct value_feedback:2, call_feedback:0, dst:reg6, callee:reg5, Derived
- [ 138] GetById value_feedback:3, dst:reg5, base:reg6, `test`
- [ 150] Call value_feedback:4, call_feedback:1, dst:reg8, callee:reg5, this_value:reg6, <object>.test
- [ 170] End value:reg8
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `Base`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] SetLexicalEnvironment environment:reg4
+ [ 50] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0
+ [ 78] DynamicInitializeLexicalBinding `Base`, src:reg6
+ [ 88] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ a0] CreateVariable `Derived`, is_immutable:true, is_global:false, is_strict:true
+ [ b0] GetGlobal value_feedback:0, dst:reg9, `Base`
+ [ c0] GetClassProtoParent dst:reg10, super_class:reg9
+ [ d0] SetLexicalEnvironment environment:reg4
+ [ d8] NewClass dst:reg6, super_class:reg9, proto_parent:reg10, class_environment:reg7, class_blueprint_index:1, element_keys:[element_keys:String("test")]
+ [ 108] DynamicInitializeLexicalBinding `Derived`, src:reg6
+ [ 118] GetGlobal value_feedback:1, dst:reg6, `Derived`
+ [ 128] CallConstruct value_feedback:2, call_feedback:0, dst:reg6, callee:reg6
+ [ 148] GetById value_feedback:3, dst:reg7, base:reg6, `test`
+ [ 160] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6
+ [ 180] End value:reg5
Derived$eee8d5da super-computed-eval-order.js:4:14
- Registers: 8
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
@@ -37,7 +38,7 @@ block0:
[ 0] Enter
[ 8] GetSuperConstructor dst:reg5
[ 10] NewArray dst:reg6
- [ 20] SuperCallWithArgumentArray value_feedback:0, call_feedback:0, dst:reg7, super_constructor:reg5, arguments:reg6, is_synthetic:false
+ [ 20] SuperCallWithArgumentArray value_feedback:0, call_feedback:0, dst:reg5, super_constructor:reg5, arguments:reg6, is_synthetic:false
[ 38] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/super-computed-string-to-id.txt b/Tests/LibJS/Bytecode/expected/super-computed-string-to-id.txt
index 01964aa3aa0..a13595c1d1d 100644
--- a/Tests/LibJS/Bytecode/expected/super-computed-string-to-id.txt
+++ b/Tests/LibJS/Bytecode/expected/super-computed-string-to-id.txt
@@ -1,5 +1,5 @@
-$745d24d5 super-computed-string-to-id.js:1:1
- Registers: 9
+$7ca8f805 super-computed-string-to-id.js:1:1
+ Registers: 11
Blocks: 1
Constants:
[0] = Undefined
@@ -7,20 +7,21 @@ $745d24d5 super-computed-string-to-id.js:1:1
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
- [ 38] GetGlobal value_feedback:0, dst:reg6, `Object`
- [ 48] GetClassProtoParent dst:reg7, super_class:reg6
- [ 58] SetLexicalEnvironment environment:reg4
- [ 60] NewClass dst:reg8, super_class:reg6, proto_parent:reg7, class_environment:reg5, class_blueprint_index:0
- [ 88] DynamicInitializeLexicalBinding `C`, src:reg8
- [ 98] GetGlobal value_feedback:1, dst:reg5, `C`
- [ a8] CallConstruct value_feedback:2, call_feedback:0, dst:reg8, callee:reg5, C
- [ c8] End value:reg8
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] GetGlobal value_feedback:0, dst:reg9, `Object`
+ [ 58] GetClassProtoParent dst:reg10, super_class:reg9
+ [ 68] SetLexicalEnvironment environment:reg4
+ [ 70] NewClass dst:reg6, super_class:reg9, proto_parent:reg10, class_environment:reg7, class_blueprint_index:0
+ [ 98] DynamicInitializeLexicalBinding `C`, src:reg6
+ [ a8] GetGlobal value_feedback:1, dst:reg6, `C`
+ [ b8] CallConstruct value_feedback:2, call_feedback:0, dst:reg5, callee:reg6
+ [ d8] End value:reg5
C$3a34c93b super-computed-string-to-id.js:3:14
- Registers: 8
+ Registers: 7
Blocks: 1
Constants:
[0] = String("foo")
@@ -31,8 +32,8 @@ block0:
[ 0] Enter
[ 8] GetSuperConstructor dst:reg5
[ 10] NewArray dst:reg6
- [ 20] SuperCallWithArgumentArray value_feedback:0, call_feedback:0, dst:reg7, super_constructor:reg5, arguments:reg6, is_synthetic:false
+ [ 20] SuperCallWithArgumentArray value_feedback:0, call_feedback:0, dst:reg5, super_constructor:reg5, arguments:reg6, is_synthetic:false
[ 38] ResolveThisBinding
- [ 40] ResolveSuperBase dst:reg7
- [ 48] PutByIdWithThis base:reg7, this_value:this, `foo`, src:Int32(1), kind:Normal
+ [ 40] ResolveSuperBase dst:reg5
+ [ 48] PutByIdWithThis base:reg5, this_value:this, `foo`, src:Int32(1), kind:Normal
[ 68] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/super-constructor-call.txt b/Tests/LibJS/Bytecode/expected/super-constructor-call.txt
index c19c7d8a11c..ac8aba29d95 100644
--- a/Tests/LibJS/Bytecode/expected/super-constructor-call.txt
+++ b/Tests/LibJS/Bytecode/expected/super-constructor-call.txt
@@ -1,5 +1,5 @@
-$221ada1a super-constructor-call.js:1:1
- Registers: 9
+$1f56e90a super-constructor-call.js:1:1
+ Registers: 11
Blocks: 1
Constants:
[0] = Undefined
@@ -8,25 +8,26 @@ $221ada1a super-constructor-call.js:1:1
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `Base`, is_immutable:true, is_global:false, is_strict:true
- [ 38] SetLexicalEnvironment environment:reg4
- [ 40] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0
- [ 68] DynamicInitializeLexicalBinding `Base`, src:reg6
- [ 78] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:1, is_catch_environment:false
- [ 90] CreateVariable `Derived`, is_immutable:true, is_global:false, is_strict:true
- [ a0] GetGlobal value_feedback:0, dst:reg5, `Base`
- [ b0] GetClassProtoParent dst:reg7, super_class:reg5
- [ c0] SetLexicalEnvironment environment:reg4
- [ c8] NewClass dst:reg8, super_class:reg5, proto_parent:reg7, class_environment:reg6, class_blueprint_index:1
- [ f0] DynamicInitializeLexicalBinding `Derived`, src:reg8
- [ 100] GetGlobal value_feedback:1, dst:reg6, `Derived`
- [ 110] CallConstruct value_feedback:2, call_feedback:0, dst:reg8, callee:reg6, Derived, arguments:[Int32(1)]
- [ 138] End value:reg8
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `Base`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] SetLexicalEnvironment environment:reg4
+ [ 50] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0
+ [ 78] DynamicInitializeLexicalBinding `Base`, src:reg6
+ [ 88] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ a0] CreateVariable `Derived`, is_immutable:true, is_global:false, is_strict:true
+ [ b0] GetGlobal value_feedback:0, dst:reg9, `Base`
+ [ c0] GetClassProtoParent dst:reg10, super_class:reg9
+ [ d0] SetLexicalEnvironment environment:reg4
+ [ d8] NewClass dst:reg6, super_class:reg9, proto_parent:reg10, class_environment:reg7, class_blueprint_index:1
+ [ 100] DynamicInitializeLexicalBinding `Derived`, src:reg6
+ [ 110] GetGlobal value_feedback:1, dst:reg6, `Derived`
+ [ 120] CallConstruct value_feedback:2, call_feedback:0, dst:reg5, callee:reg6, arguments:[Int32(1)]
+ [ 148] End value:reg5
-Derived$6ac2ec42 super-constructor-call.js:4:14
- Registers: 8
+Derived$6d86dd52 super-constructor-call.js:4:14
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
@@ -34,10 +35,9 @@ Derived$6ac2ec42 super-constructor-call.js:4:14
block0:
[ 0] Enter
[ 8] GetSuperConstructor dst:reg5
- [ 10] Mov dst:reg7, src:arg0
- [ 20] NewArray dst:reg6, elements:[reg7]
- [ 38] SuperCallWithArgumentArray value_feedback:0, call_feedback:0, dst:reg7, super_constructor:reg5, arguments:reg6, is_synthetic:false
- [ 50] End value:Undefined
+ [ 10] NewArray dst:reg6, elements:[arg0]
+ [ 28] SuperCallWithArgumentArray value_feedback:0, call_feedback:0, dst:reg5, super_constructor:reg5, arguments:reg6, is_synthetic:false
+ [ 40] End value:Undefined
Base$25c3a990
diff --git a/Tests/LibJS/Bytecode/expected/super-evaluation-order.txt b/Tests/LibJS/Bytecode/expected/super-evaluation-order.txt
index ab8feab6aa0..027580fd2b2 100644
--- a/Tests/LibJS/Bytecode/expected/super-evaluation-order.txt
+++ b/Tests/LibJS/Bytecode/expected/super-evaluation-order.txt
@@ -1,50 +1,48 @@
-$bf243d42 super-evaluation-order.js:1:1
- Registers: 9
+$bc604c32 super-evaluation-order.js:1:1
+ Registers: 11
Blocks: 1
Constants:
- [0] = String("read")
- [1] = String("write")
- [2] = String("update")
- [3] = Undefined
+ [0] = Undefined
+ [1] = String("read")
+ [2] = String("write")
+ [3] = String("update")
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `A`, is_immutable:true, is_global:false, is_strict:true
- [ 38] GetGlobal value_feedback:0, dst:reg6, `Object`
- [ 48] GetClassProtoParent dst:reg7, super_class:reg6
- [ 58] SetLexicalEnvironment environment:reg4
- [ 60] NewClass dst:reg8, super_class:reg6, proto_parent:reg7, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:String("read"), element_keys:String("write"), element_keys:String("update")]
- [ 98] DynamicInitializeLexicalBinding `A`, src:reg8
- [ a8] GetGlobal value_feedback:1, dst:reg6, `A`
- [ b8] CallConstruct value_feedback:2, call_feedback:0, dst:reg5, callee:reg6, A
- [ d8] GetById value_feedback:3, dst:reg6, base:reg5, `read`
- [ f0] Call value_feedback:4, call_feedback:1, dst:reg8, callee:reg6, this_value:reg5, <object>.read
- [ 110] GetGlobal value_feedback:5, dst:reg7, `A`
- [ 120] CallConstruct value_feedback:6, call_feedback:2, dst:reg5, callee:reg7, A
- [ 140] GetById value_feedback:7, dst:reg7, base:reg5, `write`
- [ 158] Call value_feedback:8, call_feedback:3, dst:reg6, callee:reg7, this_value:reg5, <object>.write
- [ 178] GetGlobal value_feedback:9, dst:reg5, `A`
- [ 188] CallConstruct value_feedback:10, call_feedback:4, dst:reg7, callee:reg5, A
- [ 1a8] GetById value_feedback:11, dst:reg5, base:reg7, `update`
- [ 1c0] Call value_feedback:12, call_feedback:5, dst:reg8, callee:reg5, this_value:reg7, <object>.update
- [ 1e0] End value:reg8
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `A`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] GetGlobal value_feedback:0, dst:reg9, `Object`
+ [ 58] GetClassProtoParent dst:reg10, super_class:reg9
+ [ 68] SetLexicalEnvironment environment:reg4
+ [ 70] NewClass dst:reg6, super_class:reg9, proto_parent:reg10, class_environment:reg7, class_blueprint_index:0, element_keys:[element_keys:String("read"), element_keys:String("write"), element_keys:String("update")]
+ [ a8] DynamicInitializeLexicalBinding `A`, src:reg6
+ [ b8] GetGlobal value_feedback:1, dst:reg6, `A`
+ [ c8] CallConstruct value_feedback:2, call_feedback:0, dst:reg6, callee:reg6
+ [ e8] GetById value_feedback:3, dst:reg7, base:reg6, `read`
+ [ 100] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6
+ [ 120] GetGlobal value_feedback:5, dst:reg6, `A`
+ [ 130] CallConstruct value_feedback:6, call_feedback:2, dst:reg6, callee:reg6
+ [ 150] GetById value_feedback:7, dst:reg7, base:reg6, `write`
+ [ 168] Call value_feedback:8, call_feedback:3, dst:reg5, callee:reg7, this_value:reg6
+ [ 188] GetGlobal value_feedback:9, dst:reg6, `A`
+ [ 198] CallConstruct value_feedback:10, call_feedback:4, dst:reg6, callee:reg6
+ [ 1b8] GetById value_feedback:11, dst:reg7, base:reg6, `update`
+ [ 1d0] Call value_feedback:12, call_feedback:5, dst:reg5, callee:reg7, this_value:reg6
+ [ 1f0] End value:reg5
-A$9ff96274 super-evaluation-order.js:1:1
+A$c128af34 super-evaluation-order.js:1:1
Registers: 8
Blocks: 1
block0:
[ 0] Enter
- [ 8] CreateVariable `args`, is_immutable:false, is_global:false, is_strict:false
- [ 18] CreateRestParams dst:arg0, rest_index:0
- [ 28] InitializeLexicalBinding `args`, src:arg0
- [ 40] GetSuperConstructor dst:reg5
- [ 48] GetBinding value_feedback:0, dst:reg6, `args`
- [ 60] SuperCallWithArgumentArray value_feedback:1, call_feedback:0, dst:reg7, super_constructor:reg5, arguments:reg6, is_synthetic:true
- [ 78] Return value:reg7
+ [ 8] CreateRestParams dst:reg5, rest_index:0
+ [ 18] GetSuperConstructor dst:reg6
+ [ 20] SuperCallWithArgumentArray value_feedback:0, call_feedback:0, dst:reg7, super_constructor:reg6, arguments:reg5, is_synthetic:true
+ [ 38] Return value:reg7
read$df25c2bd super-evaluation-order.js:3:9
@@ -61,7 +59,7 @@ block0:
[ 30] Return value:reg6
-write$03045a6a super-evaluation-order.js:6:20
+write$aad6a697 super-evaluation-order.js:6:9
Registers: 6
Blocks: 1
Constants:
@@ -77,7 +75,7 @@ block0:
[ 38] End value:Undefined
-update$044d6445 super-evaluation-order.js:9:16
+update$94baef3c super-evaluation-order.js:9:9
Registers: 8
Blocks: 1
Constants:
diff --git a/Tests/LibJS/Bytecode/expected/super-for-of-resolve-order.txt b/Tests/LibJS/Bytecode/expected/super-for-of-resolve-order.txt
index 42bad3cc829..c7cfe9182aa 100644
--- a/Tests/LibJS/Bytecode/expected/super-for-of-resolve-order.txt
+++ b/Tests/LibJS/Bytecode/expected/super-for-of-resolve-order.txt
@@ -1,5 +1,5 @@
-$84f4cb35 super-for-of-resolve-order.js:1:1
- Registers: 7
+$772115e5 super-for-of-resolve-order.js:1:1
+ Registers: 8
Blocks: 1
Constants:
[0] = Undefined
@@ -7,62 +7,48 @@ $84f4cb35 super-for-of-resolve-order.js:1:1
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
- [ 38] SetLexicalEnvironment environment:reg4
- [ 40] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0
- [ 68] DynamicInitializeLexicalBinding `C`, src:reg6
- [ 78] GetGlobal value_feedback:0, dst:reg5, `C`
- [ 88] CallConstruct value_feedback:1, call_feedback:0, dst:reg6, callee:reg5, C
- [ a8] End value:reg6
-
-
-C$a04f1576 super-for-of-resolve-order.js:3:28
- Registers: 13
- Blocks: 9
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `C`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] SetLexicalEnvironment environment:reg4
+ [ 50] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0
+ [ 78] DynamicInitializeLexicalBinding `C`, src:reg6
+ [ 88] GetGlobal value_feedback:0, dst:reg6, `C`
+ [ 98] CallConstruct value_feedback:1, call_feedback:0, dst:reg5, callee:reg6
+ [ b8] End value:reg5
+
+
+C$26d931cb super-for-of-resolve-order.js:3:14
+ Registers: 12
+ Blocks: 5
Constants:
- [0] = String("prop")
- [1] = Int32(1)
- [2] = Undefined
- [3] = Int32(2)
+ [0] = Int32(1)
+ [1] = Int32(2)
+ [2] = String("prop")
+ [3] = Undefined
block0:
[ 0] Enter
[ 8] NewPrimitiveArray dst:reg5, elements:[1, 2]
[ 28] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true
- [ 48] Jump target:block2
block1:
- [ 50] End value:Undefined
+ [ 48] IteratorNextUnpack dst_value:reg9, dst_done:reg10, iterator_object:reg6, iterator_next:reg7, iterator_done:reg8
+ [ 60] JumpTrue condition:reg10, target:block4
block2:
- [ 58] IteratorNextUnpack dst_value:reg10, dst_done:reg11, iterator_object:reg6, iterator_next:reg7, iterator_done:reg8
- [ 70] JumpIfLoop condition:reg11, true_target:block1, false_target:block4
+ [ 70] ResolveThisBinding
+ [ 78] ResolveSuperBase dst:reg11
+ [ 80] PutByIdWithThis base:reg11, this_value:this, `prop`, src:reg9, kind:Normal
+ [ a0] JumpLoop target:block1
block3:
- [ 80] Catch value_feedback:0, dst:reg9
- [ 88] Mov dst:reg5, src:Int32(1)
- [ 98] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg5, rhs:1, true_target:block5, false_target:block6
+ [ a8] Catch value_feedback:0, dst:reg11
+ [ b0] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:reg11
+ [ d0] Throw src:reg11
block4:
- [ b0] ResolveThisBinding
- [ b8] ResolveSuperBase dst:reg12
- [ c0] PutByIdWithThis base:reg12, this_value:this, `prop`, src:reg10, kind:Normal
- [ e0] JumpLoop target:block2
-
-block5:
- [ e8] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:reg9
- [ 108] Throw src:reg9
-
-block6:
- [ 110] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:Undefined
- [ 130] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg5, rhs:2, true_target:block7, false_target:block8
-
-block7:
- [ 148] Return value:reg9
-
-block8:
- [ 150] Throw src:reg9
+ [ d8] End value:Undefined
Exception handlers:
- [ b0 .. e8] => handler block3
+ [ 70 .. a8] => handler block3
diff --git a/Tests/LibJS/Bytecode/expected/super-length-access.txt b/Tests/LibJS/Bytecode/expected/super-length-access.txt
index 4b66310606c..6f8649a26fb 100644
--- a/Tests/LibJS/Bytecode/expected/super-length-access.txt
+++ b/Tests/LibJS/Bytecode/expected/super-length-access.txt
@@ -1,46 +1,44 @@
-$be23f63c super-length-access.js:3:1
- Registers: 9
+$bb60052c super-length-access.js:3:1
+ Registers: 11
Blocks: 1
Constants:
- [0] = String("length")
- [1] = String("m")
- [2] = Undefined
+ [0] = Undefined
+ [1] = String("length")
+ [2] = String("m")
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `A`, is_immutable:true, is_global:false, is_strict:true
- [ 38] SetLexicalEnvironment environment:reg4
- [ 40] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:String("length")]
- [ 70] DynamicInitializeLexicalBinding `A`, src:reg6
- [ 80] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:1, is_catch_environment:false
- [ 98] CreateVariable `B`, is_immutable:true, is_global:false, is_strict:true
- [ a8] GetGlobal value_feedback:0, dst:reg5, `A`
- [ b8] GetClassProtoParent dst:reg7, super_class:reg5
- [ c8] SetLexicalEnvironment environment:reg4
- [ d0] NewClass dst:reg8, super_class:reg5, proto_parent:reg7, class_environment:reg6, class_blueprint_index:1, element_keys:[element_keys:String("m")]
- [ 100] DynamicInitializeLexicalBinding `B`, src:reg8
- [ 110] GetGlobal value_feedback:1, dst:reg5, `B`
- [ 120] CallConstruct value_feedback:2, call_feedback:0, dst:reg6, callee:reg5, B
- [ 140] GetById value_feedback:3, dst:reg5, base:reg6, `m`
- [ 158] Call value_feedback:4, call_feedback:1, dst:reg8, callee:reg5, this_value:reg6, <object>.m
- [ 178] End value:reg8
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `A`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] SetLexicalEnvironment environment:reg4
+ [ 50] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0, element_keys:[element_keys:String("length")]
+ [ 80] DynamicInitializeLexicalBinding `A`, src:reg6
+ [ 90] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ a8] CreateVariable `B`, is_immutable:true, is_global:false, is_strict:true
+ [ b8] GetGlobal value_feedback:0, dst:reg9, `A`
+ [ c8] GetClassProtoParent dst:reg10, super_class:reg9
+ [ d8] SetLexicalEnvironment environment:reg4
+ [ e0] NewClass dst:reg6, super_class:reg9, proto_parent:reg10, class_environment:reg7, class_blueprint_index:1, element_keys:[element_keys:String("m")]
+ [ 110] DynamicInitializeLexicalBinding `B`, src:reg6
+ [ 120] GetGlobal value_feedback:1, dst:reg6, `B`
+ [ 130] CallConstruct value_feedback:2, call_feedback:0, dst:reg6, callee:reg6
+ [ 150] GetById value_feedback:3, dst:reg7, base:reg6, `m`
+ [ 168] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6
+ [ 188] End value:reg5
-B$73f1ca79 super-length-access.js:7:1
+B$52c27db9 super-length-access.js:7:1
Registers: 8
Blocks: 1
block0:
[ 0] Enter
- [ 8] CreateVariable `args`, is_immutable:false, is_global:false, is_strict:false
- [ 18] CreateRestParams dst:arg0, rest_index:0
- [ 28] InitializeLexicalBinding `args`, src:arg0
- [ 40] GetSuperConstructor dst:reg5
- [ 48] GetBinding value_feedback:0, dst:reg6, `args`
- [ 60] SuperCallWithArgumentArray value_feedback:1, call_feedback:0, dst:reg7, super_constructor:reg5, arguments:reg6, is_synthetic:true
- [ 78] Return value:reg7
+ [ 8] CreateRestParams dst:reg5, rest_index:0
+ [ 18] GetSuperConstructor dst:reg6
+ [ 20] SuperCallWithArgumentArray value_feedback:0, call_feedback:0, dst:reg7, super_constructor:reg6, arguments:reg5, is_synthetic:true
+ [ 38] Return value:reg7
A$70678274
diff --git a/Tests/LibJS/Bytecode/expected/super-method-call-order.txt b/Tests/LibJS/Bytecode/expected/super-method-call-order.txt
index c2d77360761..f808c838b2c 100644
--- a/Tests/LibJS/Bytecode/expected/super-method-call-order.txt
+++ b/Tests/LibJS/Bytecode/expected/super-method-call-order.txt
@@ -1,45 +1,47 @@
-$f3cbcd2f super-method-call-order.js:1:1
- Registers: 9
+$ffa84933 super-method-call-order.js:1:5
+ Registers: 8
Blocks: 1
+ Constants:
+ [0] = Undefined
block0:
[ 0] Enter
- [ 8] NewObject dst:reg5
- [ 18] NewFunction dst:reg6, shared_function_data_index:0 (m), home_object:reg5
- [ 30] InitObjectLiteralProperty object:reg5, `m`, src:reg6, shape_cache_index:0, property_slot:0
- [ 48] CacheObjectShape object:reg5
- [ 58] SetGlobal `proto`, src:reg5
- [ 68] NewObject dst:reg5
- [ 78] GetGlobal value_feedback:0, dst:reg6, `proto`
- [ 88] PutById base:reg5, `__proto__`, src:reg6, kind:Prototype
- [ a8] NewFunction dst:reg6, shared_function_data_index:1 (test), home_object:reg5
- [ c0] PutById base:reg5, `test`, src:reg6, kind:Own
- [ e0] NewFunction dst:reg6, shared_function_data_index:2 (get x), home_object:reg5
- [ f8] PutById base:reg5, `x`, src:reg6, kind:Getter
- [ 118] NewFunction dst:reg6, shared_function_data_index:3 (test2), home_object:reg5
- [ 130] PutById base:reg5, `test2`, src:reg6, kind:Own
- [ 150] SetGlobal `obj`, src:reg5
- [ 160] GetGlobal value_feedback:1, dst:reg6, `obj`
- [ 170] GetById value_feedback:2, dst:reg7, base:reg6, `test` (obj.test)
- [ 188] Call value_feedback:3, call_feedback:0, dst:reg5, callee:reg7, this_value:reg6, obj.test
- [ 1a8] GetGlobal value_feedback:4, dst:reg7, `obj`
- [ 1b8] GetById value_feedback:5, dst:reg6, base:reg7, `x` (obj.x)
- [ 1d0] GetGlobal value_feedback:6, dst:reg7, `obj`
- [ 1e0] GetById value_feedback:7, dst:reg8, base:reg7, `test2` (obj.test2)
- [ 1f8] Call value_feedback:8, call_feedback:1, dst:reg5, callee:reg8, this_value:reg7, obj.test2
- [ 218] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] NewObject dst:reg6
+ [ 28] NewFunction dst:reg7, shared_function_data_index:0 (m), home_object:reg6
+ [ 40] PutById base:reg6, `m`, src:reg7, kind:Own
+ [ 60] SetGlobal `proto`, src:reg6
+ [ 70] NewObject dst:reg6
+ [ 80] GetGlobal value_feedback:0, dst:reg7, `proto`
+ [ 90] PutById base:reg6, `__proto__`, src:reg7, kind:Prototype
+ [ b0] NewFunction dst:reg7, shared_function_data_index:1 (test), home_object:reg6
+ [ c8] PutById base:reg6, `test`, src:reg7, kind:Own
+ [ e8] NewFunction dst:reg7, shared_function_data_index:2 (get x), home_object:reg6
+ [ 100] PutById base:reg6, `x`, src:reg7, kind:Getter
+ [ 120] NewFunction dst:reg7, shared_function_data_index:3 (test2), home_object:reg6
+ [ 138] PutById base:reg6, `test2`, src:reg7, kind:Own
+ [ 158] SetGlobal `obj`, src:reg6
+ [ 168] GetGlobal value_feedback:1, dst:reg6, `obj`
+ [ 178] GetById value_feedback:2, dst:reg7, base:reg6, `test`
+ [ 190] Call value_feedback:3, call_feedback:0, dst:reg5, callee:reg7, this_value:reg6
+ [ 1b0] GetGlobal value_feedback:4, dst:reg6, `obj`
+ [ 1c0] GetById value_feedback:5, dst:reg5, base:reg6, `x`
+ [ 1d8] GetGlobal value_feedback:6, dst:reg6, `obj`
+ [ 1e8] GetById value_feedback:7, dst:reg7, base:reg6, `test2`
+ [ 200] Call value_feedback:8, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6
+ [ 220] End value:reg5
test$70dcf05f super-method-call-order.js:5:9
- Registers: 8
+ Registers: 7
Blocks: 1
block0:
[ 0] Enter
[ 8] ResolveThisBinding
- [ 10] ResolveSuperBase dst:reg6
- [ 18] GetByIdWithThis value_feedback:0, dst:reg7, base:reg6, `m`, this_value:this
- [ 30] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg7, this_value:this, <object>.m
+ [ 10] ResolveSuperBase dst:reg5
+ [ 18] GetByIdWithThis value_feedback:0, dst:reg6, base:reg5, `m`, this_value:this
+ [ 30] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:this
[ 50] Return value:reg5
@@ -55,20 +57,20 @@ block0:
get x$97875862 super-method-call-order.js:8:9
- Registers: 8
+ Registers: 7
Blocks: 1
block0:
[ 0] Enter
[ 8] ResolveThisBinding
- [ 10] ResolveSuperBase dst:reg6
- [ 18] GetByIdWithThis value_feedback:0, dst:reg7, base:reg6, `m`, this_value:this
- [ 30] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg7, this_value:this, <object>.m
+ [ 10] ResolveSuperBase dst:reg5
+ [ 18] GetByIdWithThis value_feedback:0, dst:reg6, base:reg5, `m`, this_value:this
+ [ 30] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:this
[ 50] Return value:reg5
test2$5d2fb73b super-method-call-order.js:11:9
- Registers: 8
+ Registers: 7
Blocks: 1
Constants:
[0] = String("m")
@@ -76,7 +78,7 @@ test2$5d2fb73b super-method-call-order.js:11:9
block0:
[ 0] Enter
[ 8] ResolveThisBinding
- [ 10] ResolveSuperBase dst:reg6
- [ 18] GetByIdWithThis value_feedback:0, dst:reg7, base:reg6, `m`, this_value:this
- [ 30] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg7, this_value:this, <object>['m']
+ [ 10] ResolveSuperBase dst:reg5
+ [ 18] GetByIdWithThis value_feedback:0, dst:reg6, base:reg5, `m`, this_value:this
+ [ 30] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:this
[ 50] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/super-optional-call-this.txt b/Tests/LibJS/Bytecode/expected/super-optional-call-this.txt
index 498dc089ca4..4e568a9e7ff 100644
--- a/Tests/LibJS/Bytecode/expected/super-optional-call-this.txt
+++ b/Tests/LibJS/Bytecode/expected/super-optional-call-this.txt
@@ -1,45 +1,43 @@
-$434a26da super-optional-call-this.js:1:1
- Registers: 9
+$408635ca super-optional-call-this.js:1:1
+ Registers: 11
Blocks: 1
Constants:
- [0] = String("method")
- [1] = Undefined
+ [0] = Undefined
+ [1] = String("method")
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `Base`, is_immutable:true, is_global:false, is_strict:true
- [ 38] SetLexicalEnvironment environment:reg4
- [ 40] NewClass dst:reg6, class_environment:reg5, class_blueprint_index:0, element_keys:[element_keys:String("method")]
- [ 70] DynamicInitializeLexicalBinding `Base`, src:reg6
- [ 80] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:1, is_catch_environment:false
- [ 98] CreateVariable `Foo`, is_immutable:true, is_global:false, is_strict:true
- [ a8] GetGlobal value_feedback:0, dst:reg5, `Base`
- [ b8] GetClassProtoParent dst:reg7, super_class:reg5
- [ c8] SetLexicalEnvironment environment:reg4
- [ d0] NewClass dst:reg8, super_class:reg5, proto_parent:reg7, class_environment:reg6, class_blueprint_index:1, element_keys:[element_keys:String("method")]
- [ 100] DynamicInitializeLexicalBinding `Foo`, src:reg8
- [ 110] GetGlobal value_feedback:1, dst:reg5, `Foo`
- [ 120] CallConstruct value_feedback:2, call_feedback:0, dst:reg6, callee:reg5, Foo
- [ 140] GetById value_feedback:3, dst:reg5, base:reg6, `method`
- [ 158] Call value_feedback:4, call_feedback:1, dst:reg8, callee:reg5, this_value:reg6, <object>.method
- [ 178] End value:reg8
-
-
-Foo$9e411946 super-optional-call-this.js:4:1
+ [ 10] Mov dst:reg5, src:Undefined
+ [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `Base`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] SetLexicalEnvironment environment:reg4
+ [ 50] NewClass dst:reg6, class_environment:reg7, class_blueprint_index:0, element_keys:[element_keys:String("method")]
+ [ 80] DynamicInitializeLexicalBinding `Base`, src:reg6
+ [ 90] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false
+ [ a8] CreateVariable `Foo`, is_immutable:true, is_global:false, is_strict:true
+ [ b8] GetGlobal value_feedback:0, dst:reg9, `Base`
+ [ c8] GetClassProtoParent dst:reg10, super_class:reg9
+ [ d8] SetLexicalEnvironment environment:reg4
+ [ e0] NewClass dst:reg6, super_class:reg9, proto_parent:reg10, class_environment:reg7, class_blueprint_index:1, element_keys:[element_keys:String("method")]
+ [ 110] DynamicInitializeLexicalBinding `Foo`, src:reg6
+ [ 120] GetGlobal value_feedback:1, dst:reg6, `Foo`
+ [ 130] CallConstruct value_feedback:2, call_feedback:0, dst:reg6, callee:reg6
+ [ 150] GetById value_feedback:3, dst:reg7, base:reg6, `method`
+ [ 168] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6
+ [ 188] End value:reg5
+
+
+Foo$7d11cc86 super-optional-call-this.js:4:1
Registers: 8
Blocks: 1
block0:
[ 0] Enter
- [ 8] CreateVariable `args`, is_immutable:false, is_global:false, is_strict:false
- [ 18] CreateRestParams dst:arg0, rest_index:0
- [ 28] InitializeLexicalBinding `args`, src:arg0
- [ 40] GetSuperConstructor dst:reg5
- [ 48] GetBinding value_feedback:0, dst:reg6, `args`
- [ 60] SuperCallWithArgumentArray value_feedback:1, call_feedback:0, dst:reg7, super_constructor:reg5, arguments:reg6, is_synthetic:true
- [ 78] Return value:reg7
+ [ 8] CreateRestParams dst:reg5, rest_index:0
+ [ 18] GetSuperConstructor dst:reg6
+ [ 20] SuperCallWithArgumentArray value_feedback:0, call_feedback:0, dst:reg7, super_constructor:reg6, arguments:reg5, is_synthetic:true
+ [ 38] Return value:reg7
Base$25c3a990
@@ -53,30 +51,28 @@ block0:
[ 8] End value:Undefined
-method$a721f13d super-optional-call-this.js:6:9
- Registers: 9
- Blocks: 3
+method$a45e002d super-optional-call-this.js:6:9
+ Registers: 7
+ Blocks: 4
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:reg5
- [ 10] ResolveThisBinding
- [ 18] ResolveSuperBase dst:reg7
- [ 20] GetByIdWithThis value_feedback:0, dst:reg8, base:reg7, `method`, this_value:this
- [ 38] Mov2 c0_dst:reg5, c0_src:this, c1_dst:reg6, c1_src:reg8
- [ 50] JumpNullish condition:reg6, true_target:block1, false_target:block2
+ [ 8] ResolveThisBinding
+ [ 10] ResolveSuperBase dst:reg5
+ [ 18] GetByIdWithThis value_feedback:0, dst:reg6, base:reg5, `method`, this_value:this
+ [ 30] JumpNullish condition:reg6, true_target:block2, false_target:block1
block1:
- [ 60] MovSrcUndefined dst:reg6
- [ 68] Return value:reg6
+ [ 40] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:this
+ [ 60] Jump target:block3
block2:
- [ 70] NewArray dst:reg7
- [ 80] CallWithArgumentArray value_feedback:1, call_feedback:0, dst:reg6, callee:reg6, this_value:reg5, arguments:reg7
- [ a0] MovSrcUndefined dst:reg5
- [ a8] Return value:reg6
+ [ 68] Mov dst:reg5, src:Undefined
+
+block3:
+ [ 78] Return value:reg5
method$ed84a6f2
diff --git a/Tests/LibJS/Bytecode/expected/switch-completion-value.txt b/Tests/LibJS/Bytecode/expected/switch-completion-value.txt
index 3e1369f67b3..3d2d2b2f380 100644
--- a/Tests/LibJS/Bytecode/expected/switch-completion-value.txt
+++ b/Tests/LibJS/Bytecode/expected/switch-completion-value.txt
@@ -1,5 +1,5 @@
-$ca340182 switch-completion-value.js:1:1
- Registers: 11
+$3576718a switch-completion-value.js:1:1
+ Registers: 10
Blocks: 1
Constants:
[0] = Undefined
@@ -9,49 +9,57 @@ $ca340182 switch-completion-value.js:1:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `eval`
- [ 40] CallDirectEval value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, eval, arguments:[String("switch(1) { case 1: 'hello'; let x = 1; }")]
- [ 68] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 90] GetGlobal value_feedback:5, dst:reg6, `console`
- [ a0] GetById value_feedback:6, dst:reg8, base:reg6, `log` (console.log)
- [ b8] GetGlobal value_feedback:7, dst:reg10, `eval`
- [ c8] CallDirectEval value_feedback:8, call_feedback:2, dst:reg9, callee:reg10, this_value:Undefined, eval, arguments:[String("switch(1) { case 1: 'first'; 'second'; }")]
- [ f0] Call value_feedback:9, call_feedback:3, dst:reg7, callee:reg8, this_value:reg6, console.log, arguments:[reg9]
- [ 118] GetGlobal value_feedback:10, dst:reg8, `console`
- [ 128] GetById value_feedback:11, dst:reg6, base:reg8, `log` (console.log)
- [ 140] GetGlobal value_feedback:12, dst:reg10, `eval`
- [ 150] CallDirectEval value_feedback:13, call_feedback:4, dst:reg9, callee:reg10, this_value:Undefined, eval, arguments:[String("switch(1) { case 1: 'matched'; break; default: 'default'; }")]
- [ 178] Call value_feedback:14, call_feedback:5, dst:reg5, callee:reg6, this_value:reg8, console.log, arguments:[reg9]
- [ 1a0] End value:reg5
-
-
-eval$6559f0fb line 1, column 1
- Registers: 7
- Blocks: 3
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] DynamicGetBinding value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] DynamicGetCalleeAndThisFromEnvironment value_feedback:2, callee:reg8, this_value:reg9, `eval`
+ [ 58] CallDirectEval value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:reg9, arguments:[String("switch(1) { case 1: 'hello'; let x = 1; }")]
+ [ 80] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ a8] DynamicGetBinding value_feedback:5, dst:reg6, `console`
+ [ b8] GetById value_feedback:6, dst:reg7, base:reg6, `log`
+ [ d0] DynamicGetCalleeAndThisFromEnvironment value_feedback:7, callee:reg8, this_value:reg9, `eval`
+ [ e8] CallDirectEval value_feedback:8, call_feedback:2, dst:reg8, callee:reg8, this_value:reg9, arguments:[String("switch(1) { case 1: 'first'; 'second'; }")]
+ [ 110] Call value_feedback:9, call_feedback:3, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 138] DynamicGetBinding value_feedback:10, dst:reg6, `console`
+ [ 148] GetById value_feedback:11, dst:reg7, base:reg6, `log`
+ [ 160] DynamicGetCalleeAndThisFromEnvironment value_feedback:12, callee:reg8, this_value:reg9, `eval`
+ [ 178] CallDirectEval value_feedback:13, call_feedback:4, dst:reg8, callee:reg8, this_value:reg9, arguments:[String("switch(1) { case 1: 'matched'; break; default: 'default'; }")]
+ [ 1a0] Call value_feedback:14, call_feedback:5, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 1c8] End value:reg5
+
+
+eval$01462e32 line 1, column 8
+ Registers: 8
+ Blocks: 4
Locals: x~0
Constants:
[0] = Undefined
[1] = Int32(1)
- [2] = String("hello")
+ [2] = <Empty>
+ [3] = String("hello")
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:reg5
- [ 10] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:Int32(1), rhs:1, true_target:block2, false_target:block1
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg6, src:Int32(1)
+ [ 28] Mov dst:reg5, src:Undefined
+ [ 38] Mov dst:x~0, src:<Empty>
+ [ 48] JumpStrictlyEquals arith_feedback:0, lhs:Int32(1), rhs:reg6, true_target:block2, false_target:block1
block1:
- [ 28] End value:reg5
+ [ 60] Jump target:block3
block2:
- [ 30] Mov2 c0_dst:reg5, c0_src:String("hello"), c1_dst:x~0, c1_src:Int32(1)
- [ 48] End value:reg5
+ [ 68] Mov dst:reg5, src:String("hello")
+ [ 78] Mov dst:x~0, src:Int32(1)
+
+block3:
+ [ 88] End value:reg5
-eval$6559f0fb line 1, column 1
- Registers: 7
- Blocks: 3
+eval$fe823d22 line 1, column 8
+ Registers: 8
+ Blocks: 4
Constants:
[0] = Undefined
[1] = Int32(1)
@@ -60,20 +68,25 @@ eval$6559f0fb line 1, column 1
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:reg5
- [ 10] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:Int32(1), rhs:1, true_target:block2, false_target:block1
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg6, src:Int32(1)
+ [ 28] Mov dst:reg5, src:Undefined
+ [ 38] JumpStrictlyEquals arith_feedback:0, lhs:Int32(1), rhs:reg6, true_target:block2, false_target:block1
block1:
- [ 28] End value:reg5
+ [ 50] Jump target:block3
block2:
- [ 30] Mov2 c0_dst:reg5, c0_src:String("first"), c1_dst:reg5, c1_src:String("second")
- [ 48] End value:reg5
+ [ 58] Mov dst:reg5, src:String("first")
+ [ 68] Mov dst:reg5, src:String("second")
+block3:
+ [ 78] End value:reg5
-eval$6da5c42b line 1, column 1
- Registers: 7
- Blocks: 4
+
+eval$7fe435aa line 1, column 8
+ Registers: 8
+ Blocks: 5
Constants:
[0] = Undefined
[1] = Int32(1)
@@ -82,19 +95,23 @@ eval$6da5c42b line 1, column 1
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:reg5
- [ 10] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:Int32(1), rhs:1, true_target:block2, false_target:block1
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg6, src:Int32(1)
+ [ 28] Mov dst:reg5, src:Undefined
+ [ 38] JumpStrictlyEquals arith_feedback:0, lhs:Int32(1), rhs:reg6, true_target:block2, false_target:block1
block1:
- [ 28] Jump target:block3
+ [ 50] Jump target:block3
block2:
- [ 30] Mov dst:reg5, src:String("matched")
- [ 40] End value:reg5
+ [ 58] Mov dst:reg5, src:String("matched")
+ [ 68] Jump target:block4
block3:
- [ 48] Mov dst:reg5, src:String("default")
- [ 58] End value:reg5
+ [ 70] Mov dst:reg5, src:String("default")
+
+block4:
+ [ 80] End value:reg5
"hello"
diff --git a/Tests/LibJS/Bytecode/expected/switch-local-only-let.txt b/Tests/LibJS/Bytecode/expected/switch-local-only-let.txt
index 98fd02de0bd..80d19d1bfa8 100644
--- a/Tests/LibJS/Bytecode/expected/switch-local-only-let.txt
+++ b/Tests/LibJS/Bytecode/expected/switch-local-only-let.txt
@@ -1,5 +1,5 @@
-$bcbab198 switch-local-only-let.js:15:1
- Registers: 11
+$b9f6c088 switch-local-only-let.js:15:1
+ Registers: 9
Blocks: 1
Constants:
[0] = Undefined
@@ -9,59 +9,60 @@ $bcbab198 switch-local-only-let.js:15:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `switchLocalOnly`
- [ 40] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, switchLocalOnly, arguments:[Int32(1)]
- [ 68] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 90] GetGlobal value_feedback:5, dst:reg6, `console`
- [ a0] GetById value_feedback:6, dst:reg8, base:reg6, `log` (console.log)
- [ b8] GetGlobal value_feedback:7, dst:reg10, `switchLocalOnly`
- [ c8] Call value_feedback:8, call_feedback:2, dst:reg9, callee:reg10, this_value:Undefined, switchLocalOnly, arguments:[Int32(2)]
- [ f0] Call value_feedback:9, call_feedback:3, dst:reg7, callee:reg8, this_value:reg6, console.log, arguments:[reg9]
- [ 118] GetGlobal value_feedback:10, dst:reg8, `console`
- [ 128] GetById value_feedback:11, dst:reg6, base:reg8, `log` (console.log)
- [ 140] GetGlobal value_feedback:12, dst:reg10, `switchLocalOnly`
- [ 150] Call value_feedback:13, call_feedback:4, dst:reg9, callee:reg10, this_value:Undefined, switchLocalOnly, arguments:[Int32(3)]
- [ 178] Call value_feedback:14, call_feedback:5, dst:reg5, callee:reg6, this_value:reg8, console.log, arguments:[reg9]
- [ 1a0] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `switchLocalOnly`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined, arguments:[Int32(1)]
+ [ 78] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ a0] GetGlobal value_feedback:5, dst:reg6, `console`
+ [ b0] GetById value_feedback:6, dst:reg7, base:reg6, `log`
+ [ c8] GetGlobal value_feedback:7, dst:reg8, `switchLocalOnly`
+ [ d8] Call value_feedback:8, call_feedback:2, dst:reg8, callee:reg8, this_value:Undefined, arguments:[Int32(2)]
+ [ 100] Call value_feedback:9, call_feedback:3, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 128] GetGlobal value_feedback:10, dst:reg6, `console`
+ [ 138] GetById value_feedback:11, dst:reg7, base:reg6, `log`
+ [ 150] GetGlobal value_feedback:12, dst:reg8, `switchLocalOnly`
+ [ 160] Call value_feedback:13, call_feedback:4, dst:reg8, callee:reg8, this_value:Undefined, arguments:[Int32(3)]
+ [ 188] Call value_feedback:14, call_feedback:5, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 1b0] End value:reg5
-switchLocalOnly$6a4e5c3f switch-local-only-let.js:4:5
- Registers: 6
- Blocks: 7
+switchLocalOnly$326c4edf switch-local-only-let.js:4:13
+ Registers: 7
+ Blocks: 6
Locals: a~0, b~1
Constants:
- [0] = Int32(1)
- [1] = Int32(2)
- [2] = Int32(10)
- [3] = Int32(20)
- [4] = Int32(0)
- [5] = Undefined
+ [0] = <Empty>
+ [1] = Int32(1)
+ [2] = Int32(2)
+ [3] = Int32(10)
+ [4] = Int32(20)
+ [5] = Int32(0)
block0:
[ 0] Enter
- [ 8] JumpStrictlyEquals arith_feedback:0, lhs:Int32(1), rhs:arg0, true_target:block3, false_target:block1
+ [ 8] Mov dst:reg5, src:arg0
+ [ 18] Mov dst:a~0, src:<Empty>
+ [ 28] Mov dst:b~1, src:<Empty>
+ [ 38] JumpStrictlyEquals arith_feedback:0, lhs:Int32(1), rhs:reg5, true_target:block3, false_target:block1
block1:
- [ 20] JumpStrictlyEquals arith_feedback:1, lhs:Int32(2), rhs:arg0, true_target:block4, false_target:block2
+ [ 50] JumpStrictlyEquals arith_feedback:1, lhs:Int32(2), rhs:reg5, true_target:block4, false_target:block2
block2:
- [ 38] Return value:Int32(0)
+ [ 68] Jump target:block5
block3:
- [ 40] Mov dst:a~0, src:Int32(10)
- [ 50] Return value:a~0
+ [ 70] Mov dst:a~0, src:Int32(10)
+ [ 80] Return value:a~0
block4:
- [ 58] Mov dst:b~1, src:Int32(20)
- [ 68] Return value:b~1
+ [ 88] Mov dst:b~1, src:Int32(20)
+ [ 98] Return value:b~1
block5:
- [ 70] Return value:Int32(0)
-
-block6:
- [ 78] End value:Undefined
+ [ a0] Return value:Int32(0)
10
diff --git a/Tests/LibJS/Bytecode/expected/switch-scoping.txt b/Tests/LibJS/Bytecode/expected/switch-scoping.txt
index e0edcb0e6d7..9c15fcff9a9 100644
--- a/Tests/LibJS/Bytecode/expected/switch-scoping.txt
+++ b/Tests/LibJS/Bytecode/expected/switch-scoping.txt
@@ -1,5 +1,5 @@
-$27fd21a0 switch-scoping.js:15:1
- Registers: 11
+$25393090 switch-scoping.js:15:1
+ Registers: 9
Blocks: 1
Constants:
[0] = Undefined
@@ -8,21 +8,22 @@ $27fd21a0 switch-scoping.js:15:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `switchWithBlockDecl`
- [ 40] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, switchWithBlockDecl, arguments:[Int32(1)]
- [ 68] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 90] GetGlobal value_feedback:5, dst:reg6, `console`
- [ a0] GetById value_feedback:6, dst:reg8, base:reg6, `log` (console.log)
- [ b8] GetGlobal value_feedback:7, dst:reg10, `switchWithBlockDecl`
- [ c8] Call value_feedback:8, call_feedback:2, dst:reg9, callee:reg10, this_value:Undefined, switchWithBlockDecl, arguments:[Int32(2)]
- [ f0] Call value_feedback:9, call_feedback:3, dst:reg7, callee:reg8, this_value:reg6, console.log, arguments:[reg9]
- [ 118] End value:reg7
-
-
-switchWithBlockDecl$ba88cf0a switch-scoping.js:2:5
- Registers: 7
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `switchWithBlockDecl`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined, arguments:[Int32(1)]
+ [ 78] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ a0] GetGlobal value_feedback:5, dst:reg6, `console`
+ [ b0] GetById value_feedback:6, dst:reg7, base:reg6, `log`
+ [ c8] GetGlobal value_feedback:7, dst:reg8, `switchWithBlockDecl`
+ [ d8] Call value_feedback:8, call_feedback:2, dst:reg8, callee:reg8, this_value:Undefined, arguments:[Int32(2)]
+ [ 100] Call value_feedback:9, call_feedback:3, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 128] End value:reg5
+
+
+switchWithBlockDecl$c207ea76 switch-scoping.js:2:9
+ Registers: 8
Blocks: 6
Locals: result~0
Constants:
@@ -35,33 +36,32 @@ switchWithBlockDecl$ba88cf0a switch-scoping.js:2:5
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] MovSrcUndefined dst:result~0
- [ 18] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:2, is_catch_environment:false
- [ 30] CreateMutableBinding environment:reg5, `a`, can_be_deleted:false
- [ 40] CreateMutableBinding environment:reg5, `b`, can_be_deleted:false
- [ 50] JumpStrictlyEquals arith_feedback:0, lhs:Int32(1), rhs:arg0, true_target:block3, false_target:block1
+ [ 10] Mov dst:result~0, src:Undefined
+ [ 20] Mov dst:reg5, src:arg0
+ [ 30] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:2, is_catch_environment:false
+ [ 48] CreateVariable `a`, is_immutable:false, is_global:false, is_strict:false
+ [ 58] CreateVariable `b`, is_immutable:false, is_global:false, is_strict:false
+ [ 68] JumpStrictlyEquals arith_feedback:0, lhs:Int32(1), rhs:reg5, true_target:block3, false_target:block1
block1:
- [ 68] JumpStrictlyEquals arith_feedback:1, lhs:Int32(2), rhs:arg0, true_target:block4, false_target:block2
+ [ 80] JumpStrictlyEquals arith_feedback:1, lhs:Int32(2), rhs:reg5, true_target:block4, false_target:block2
block2:
- [ 80] Jump target:block5
+ [ 98] Jump target:block5
block3:
- [ 88] InitializeLexicalBinding `a`, src:String("one")
- [ a0] NewFunction dst:reg6, shared_function_data_index:0 (result)
- [ b8] Mov dst:result~0, src:reg6
- [ c8] Jump target:block5
+ [ a0] InitializeLexicalBinding `a`, src:String("one")
+ [ b8] NewFunction dst:result~0, shared_function_data_index:0 (result)
+ [ d0] Jump target:block5
block4:
- [ d0] InitializeLexicalBinding `b`, src:String("two")
- [ e8] NewFunction dst:reg6, shared_function_data_index:1 (result)
- [ 100] Mov dst:result~0, src:reg6
+ [ d8] InitializeLexicalBinding `b`, src:String("two")
+ [ f0] NewFunction dst:result~0, shared_function_data_index:1 (result)
block5:
- [ 110] SetLexicalEnvironment environment:reg4
- [ 118] Call value_feedback:0, call_feedback:0, dst:reg5, callee:result~0, this_value:Undefined, result
- [ 138] Return value:reg5
+ [ 108] SetLexicalEnvironment environment:reg4
+ [ 110] Call value_feedback:0, call_feedback:0, dst:reg5, callee:result~0, this_value:Undefined
+ [ 130] Return value:reg5
result$b74edc04 switch-scoping.js:6:22
diff --git a/Tests/LibJS/Bytecode/expected/switch-with-block-scope-return.txt b/Tests/LibJS/Bytecode/expected/switch-with-block-scope-return.txt
index 04f5f084c85..b89bbc88d4e 100644
--- a/Tests/LibJS/Bytecode/expected/switch-with-block-scope-return.txt
+++ b/Tests/LibJS/Bytecode/expected/switch-with-block-scope-return.txt
@@ -1,4 +1,4 @@
-$469b0790 switch-with-block-scope-return.js:12:1
+$43d71680 switch-with-block-scope-return.js:12:1
Registers: 7
Blocks: 1
Constants:
@@ -7,14 +7,15 @@ $469b0790 switch-with-block-scope-return.js:12:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f, arguments:[Int32(1)]
- [ 40] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[Int32(1)]
+ [ 50] End value:reg5
-f$25d82f37 switch-with-block-scope-return.js:2:5
+f$3acd362f switch-with-block-scope-return.js:2:13
Registers: 8
- Blocks: 7
+ Blocks: 6
Constants:
[0] = Int32(1)
[1] = Int32(2)
@@ -26,31 +27,28 @@ f$25d82f37 switch-with-block-scope-return.js:2:5
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateImmutableBinding environment:reg5, `y`, strict_binding:true
- [ 38] JumpStrictlyEquals arith_feedback:0, lhs:Int32(1), rhs:arg0, true_target:block3, false_target:block1
+ [ 10] Mov dst:reg5, src:arg0
+ [ 20] CreateLexicalEnvironment dst:reg6, parent:reg4, capacity:1, is_catch_environment:false
+ [ 38] CreateVariable `y`, is_immutable:true, is_global:false, is_strict:true
+ [ 48] JumpStrictlyEquals arith_feedback:0, lhs:Int32(1), rhs:reg5, true_target:block3, false_target:block1
block1:
- [ 50] JumpStrictlyEquals arith_feedback:1, lhs:Int32(2), rhs:arg0, true_target:block4, false_target:block2
+ [ 60] JumpStrictlyEquals arith_feedback:1, lhs:Int32(2), rhs:reg5, true_target:block4, false_target:block2
block2:
- [ 68] Jump target:block5
+ [ 78] Jump target:block5
block3:
- [ 70] SetLexicalEnvironment environment:reg4
- [ 78] Return value:String("one")
+ [ 80] SetLexicalEnvironment environment:reg4
+ [ 88] Return value:String("one")
block4:
- [ 80] InitializeLexicalBinding `y`, src:String("two")
- [ 98] NewFunction dst:reg7, shared_function_data_index:0
- [ b0] Call value_feedback:0, call_feedback:0, dst:reg6, callee:reg7, this_value:Undefined
- [ d0] SetLexicalEnvironment environment:reg4
- [ d8] Return value:reg6
-
-block5:
+ [ 90] InitializeLexicalBinding `y`, src:String("two")
+ [ a8] NewFunction dst:reg7, shared_function_data_index:0
+ [ c0] Call value_feedback:0, call_feedback:0, dst:reg7, callee:reg7, this_value:Undefined
[ e0] SetLexicalEnvironment environment:reg4
- [ e8] Return value:String("other")
+ [ e8] Return value:reg7
-block6:
+block5:
[ f0] SetLexicalEnvironment environment:reg4
- [ f8] End value:Undefined
+ [ f8] Return value:String("other")
diff --git a/Tests/LibJS/Bytecode/expected/tagged-template-base-identifier.txt b/Tests/LibJS/Bytecode/expected/tagged-template-base-identifier.txt
index 7c233f82169..a304db33801 100644
--- a/Tests/LibJS/Bytecode/expected/tagged-template-base-identifier.txt
+++ b/Tests/LibJS/Bytecode/expected/tagged-template-base-identifier.txt
@@ -1,21 +1,23 @@
-$7ca8f805 tagged-template-base-identifier.js:1:1
+$1a7f12f1 tagged-template-base-identifier.js:1:5
Registers: 9
Blocks: 1
Constants:
- [0] = String("")
+ [0] = Undefined
+ [1] = String("")
block0:
[ 0] Enter
- [ 8] NewObject dst:reg5
- [ 18] NewFunction dst:reg6, shared_function_data_index:0 (f)
- [ 30] InitObjectLiteralProperty object:reg5, `f`, src:reg6, shape_cache_index:0, property_slot:0
- [ 48] CacheObjectShape object:reg5
- [ 58] SetGlobal `obj`, src:reg5
- [ 68] GetGlobal value_feedback:0, dst:reg5, `obj`
- [ 78] GetById value_feedback:1, dst:reg6, base:reg5, `f` (obj.f)
- [ 90] GetTemplateObject dst:reg7, strings:[String(""), String("")]
- [ b0] Call value_feedback:2, call_feedback:0, dst:reg8, callee:reg6, this_value:reg5, arguments:[reg7]
- [ d8] End value:reg8
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] NewObject dst:reg6
+ [ 28] NewFunction dst:reg7, shared_function_data_index:0 (f)
+ [ 40] InitObjectLiteralProperty object:reg6, `f`, src:reg7, shape_cache_index:0, property_slot:0
+ [ 58] CacheObjectShape object:reg6
+ [ 68] SetGlobal `obj`, src:reg6
+ [ 78] GetGlobal value_feedback:0, dst:reg6, `obj`
+ [ 88] GetById value_feedback:1, dst:reg7, base:reg6, `f`
+ [ a0] GetTemplateObject dst:reg8, strings:[String(""), String("")]
+ [ c0] Call value_feedback:2, call_feedback:0, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ e8] End value:reg5
f$705b4581 tagged-template-base-identifier.js:3:9
diff --git a/Tests/LibJS/Bytecode/expected/tagged-template-if-register-order.txt b/Tests/LibJS/Bytecode/expected/tagged-template-if-register-order.txt
index cb064e3c44a..96556659063 100644
--- a/Tests/LibJS/Bytecode/expected/tagged-template-if-register-order.txt
+++ b/Tests/LibJS/Bytecode/expected/tagged-template-if-register-order.txt
@@ -1,42 +1,44 @@
-$54bb0ec1 tagged-template-if-register-order.js:2:1
- Registers: 11
+$ca340182 tagged-template-if-register-order.js:1:1
+ Registers: 9
Blocks: 6
Constants:
- [0] = String("use strict")
- [1] = String("hello")
- [2] = Null
- [3] = Undefined
+ [0] = Undefined
+ [1] = String("use strict")
+ [2] = String("hello")
+ [3] = Null
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg5, `String`
- [ 18] GetById value_feedback:1, dst:reg6, base:reg5, `raw` (String.raw)
- [ 30] GetTemplateObject dst:reg7, strings:[String("hello"), String("hello")]
- [ 50] Call value_feedback:2, call_feedback:0, dst:reg8, callee:reg6, this_value:reg5, arguments:[reg7]
- [ 78] DynamicInitializeLexicalBinding `x`, src:reg8
- [ 88] DynamicInitializeLexicalBinding `y`, src:Null
- [ 98] GetGlobal value_feedback:3, dst:reg8, `x`
- [ a8] StrictlyEquals arith_feedback:0, dst:reg6, lhs:reg8, rhs:String("hello")
- [ b8] MovSrcUndefined dst:reg8
- [ c0] JumpFalse condition:reg6, target:block2
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:String("use strict")
+ [ 28] GetGlobal value_feedback:0, dst:reg6, `String`
+ [ 38] GetById value_feedback:1, dst:reg7, base:reg6, `raw`
+ [ 50] GetTemplateObject dst:reg8, strings:[String("hello"), String("hello")]
+ [ 70] Call value_feedback:2, call_feedback:0, dst:reg6, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 98] DynamicInitializeLexicalBinding `x`, src:reg6
+ [ a8] DynamicInitializeLexicalBinding `y`, src:Null
+ [ b8] GetGlobal value_feedback:3, dst:reg6, `x`
+ [ c8] StrictlyEquals arith_feedback:0, dst:reg6, lhs:reg6, rhs:String("hello")
+ [ d8] Mov dst:reg5, src:Undefined
+ [ e8] JumpFalse condition:reg6, target:block5
block1:
- [ d0] ResolveGlobalBinding dst:reg7, `y`
- [ e0] GetGlobal value_feedback:4, dst:reg9, `x`
- [ f0] GetById value_feedback:5, dst:reg10, base:reg9, `toUpperCase` (x.toUpperCase)
- [ 108] Call value_feedback:6, call_feedback:1, dst:reg5, callee:reg10, this_value:reg9, x.toUpperCase
- [ 128] JumpIf condition:reg7, true_target:block3, false_target:block4
+ [ f8] ResolveGlobalBinding dst:reg6, `y`
+ [ 108] GetGlobal value_feedback:4, dst:reg7, `x`
+ [ 118] GetById value_feedback:5, dst:reg8, base:reg7, `toUpperCase`
+ [ 130] Call value_feedback:6, call_feedback:1, dst:reg7, callee:reg8, this_value:reg7
+ [ 150] JumpIf condition:reg6, true_target:block2, false_target:block3
block2:
- [ 138] End value:reg8
+ [ 160] SetGlobal `y`, src:reg7
+ [ 170] Jump target:block4
block3:
- [ 140] SetGlobal `y`, src:reg5
- [ 150] Jump target:block5
+ [ 178] SetResolvedBinding environment:Null, `y`, src:reg7
+ [ 188] Jump target:block4
block4:
- [ 158] SetResolvedBinding environment:Null, `y`, src:reg5
+ [ 190] Mov dst:reg5, src:reg7
block5:
- [ 168] Mov dst:reg8, src:reg5
- [ 178] End value:reg8
+ [ 1a0] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/tdz-reset-in-loop.txt b/Tests/LibJS/Bytecode/expected/tdz-reset-in-loop.txt
new file mode 100644
index 00000000000..c9529bd49d9
--- /dev/null
+++ b/Tests/LibJS/Bytecode/expected/tdz-reset-in-loop.txt
@@ -0,0 +1,101 @@
+$29e4bdb2 tdz-reset-in-loop.js:22:1
+ Registers: 8
+ Blocks: 1
+ Constants:
+ [0] = Undefined
+
+block0:
+ [ 0] Enter
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `checked`
+ [ 28] NewArray dst:reg7
+ [ 38] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 60] GetGlobal value_feedback:2, dst:reg6, `nested`
+ [ 70] NewArray dst:reg7
+ [ 80] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ a8] End value:reg5
+
+
+checked$6c1072e2 tdz-reset-in-loop.js:5:10
+ Registers: 8
+ Blocks: 4
+ Locals: i~0, value~1, plain~2
+ Constants:
+ [0] = Int32(0)
+ [1] = <Empty>
+ [2] = Int32(1)
+ [3] = Undefined
+
+block0:
+ [ 0] Enter
+ [ 8] Mov dst:i~0, src:Int32(0)
+ [ 18] Jump target:block2
+
+block1:
+ [ 20] Mov dst:value~1, src:<Empty>
+ [ 30] GetByValue value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0, property:i~0
+ [ 50] NewFunction dst:reg6, shared_function_data_index:0
+ [ 68] ThrowIfTDZ src:value~1
+ [ 70] Typeof dst:reg7, src:value~1
+ [ 80] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg5, this_value:arg0, arguments:[reg6, reg7]
+ [ a8] Mov dst:value~1, src:i~0
+ [ b8] AddRhsInt32 arith_feedback:0, dst:plain~2, lhs:value~1, rhs:1
+ [ c8] GetByValue value_feedback:2, keyed_feedback:1, dst:reg5, base:arg0, property:i~0
+ [ e8] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg5, this_value:arg0, arguments:[plain~2]
+ [ 110] Increment arith_feedback:1, dst:i~0
+
+block2:
+ [ 118] GetLength value_feedback:4, keyed_feedback:2, dst:reg5, base:arg0
+ [ 130] JumpLessThanLoop arith_feedback:2, lhs:i~0, rhs:reg5, true_target:block1, false_target:block3
+
+block3:
+ [ 148] End value:Undefined
+
+
+nested$e1bbca88 tdz-reset-in-loop.js:14:5
+ Registers: 12
+ Blocks: 8
+ Locals: value~0, item~1
+ Constants:
+ [0] = <Empty>
+ [1] = Undefined
+
+block0:
+ [ 0] Enter
+
+block1:
+ [ 8] GetLength value_feedback:0, keyed_feedback:0, dst:reg5, base:arg0
+ [ 20] JumpFalse condition:reg5, target:block7
+
+block2:
+ [ 30] Mov dst:value~0, src:<Empty>
+ [ 40] Mov dst:item~1, src:<Empty>
+ [ 50] Mov dst:reg5, src:arg0
+ [ 60] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true
+
+block3:
+ [ 80] IteratorNextUnpack dst_value:reg9, dst_done:reg10, iterator_object:reg6, iterator_next:reg7, iterator_done:reg8
+ [ 98] JumpTrue condition:reg10, target:block6
+
+block4:
+ [ a8] Mov dst:item~1, src:reg9
+ [ b8] ThrowIfTDZ src:value~0
+ [ c0] Typeof dst:reg11, src:value~0
+ [ d0] Call value_feedback:1, call_feedback:0, dst:reg11, callee:item~1, this_value:Undefined, arguments:[reg11]
+ [ f8] JumpLoop target:block3
+
+block5:
+ [ 100] Catch value_feedback:2, dst:reg11
+ [ 108] IteratorClose iterator_object:reg6, iterator_next:reg7, iterator_done:reg8, completion_value:reg11
+ [ 128] Throw src:reg11
+
+block6:
+ [ 130] GetById value_feedback:3, dst:reg5, base:arg0, `pop`
+ [ 148] Call value_feedback:4, call_feedback:1, dst:value~0, callee:reg5, this_value:arg0
+ [ 168] JumpLoop target:block1
+
+block7:
+ [ 170] End value:Undefined
+
+Exception handlers:
+ [ a8 .. 100] => handler block5
diff --git a/Tests/LibJS/Bytecode/expected/this-base-identifier.txt b/Tests/LibJS/Bytecode/expected/this-base-identifier.txt
index 0d8f525b512..94940395b05 100644
--- a/Tests/LibJS/Bytecode/expected/this-base-identifier.txt
+++ b/Tests/LibJS/Bytecode/expected/this-base-identifier.txt
@@ -1,32 +1,33 @@
-$474fd25c this-base-identifier.js:16:1
- Registers: 10
- Blocks: 3
+$448be14c this-base-identifier.js:16:1
+ Registers: 7
+ Blocks: 4
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `get_from_this`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, get_from_this
- [ 38] GetGlobal value_feedback:2, dst:reg7, `set_on_this`
- [ 48] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, set_on_this
- [ 68] MovSrcUndefined dst:reg5
- [ 70] Jump target:block2
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `get_from_this`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] GetGlobal value_feedback:2, dst:reg6, `set_on_this`
+ [ 58] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined
+ [ 78] Mov dst:reg5, src:Undefined
block1:
- [ 78] Catch value_feedback:4, dst:reg7
- [ 80] Mov2 c0_dst:reg8, c0_src:Undefined, c1_dst:reg5, c1_src:reg8
- [ 98] End value:reg5
+ [ 88] GetGlobal value_feedback:4, dst:reg6, `chained_this_access`
+ [ 98] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined
+ [ b8] Jump target:block3
block2:
- [ a0] MovSrcUndefined dst:reg7
- [ a8] GetGlobal value_feedback:5, dst:reg9, `chained_this_access`
- [ b8] Call value_feedback:6, call_feedback:2, dst:reg8, callee:reg9, this_value:Undefined, chained_this_access
- [ d8] Mov2 c0_dst:reg7, c0_src:reg8, c1_dst:reg5, c1_src:reg7
- [ f0] End value:reg5
+ [ c0] Catch value_feedback:6, dst:reg6
+ [ c8] Mov dst:reg5, src:Undefined
+ [ d8] Jump target:block3
+
+block3:
+ [ e0] End value:reg5
Exception handlers:
- [ a0 .. f8] => handler block1
+ [ 88 .. c0] => handler block2
get_from_this$7b4d6173 this-base-identifier.js:5:5
@@ -35,7 +36,7 @@ get_from_this$7b4d6173 this-base-identifier.js:5:5
block0:
[ 0] Enter
- [ 8] GetById value_feedback:0, dst:reg5, base:this, `foo` (this.foo)
+ [ 8] GetById value_feedback:0, dst:reg5, base:this, `foo`
[ 20] Return value:reg5
@@ -48,16 +49,16 @@ set_on_this$1818839f this-base-identifier.js:9:14
block0:
[ 0] Enter
- [ 8] PutById base:this, `bar`, src:Int32(1), kind:Normal (this.bar)
+ [ 8] PutById base:this, `bar`, src:Int32(1), kind:Normal
[ 28] End value:Undefined
chained_this_access$cbe84523 this-base-identifier.js:13:5
- Registers: 7
+ Registers: 6
Blocks: 1
block0:
[ 0] Enter
- [ 8] GetById value_feedback:0, dst:reg5, base:this, `a` (this.a)
- [ 20] GetById value_feedback:1, dst:reg6, base:reg5, `b` (this.a.b)
- [ 38] Return value:reg6
+ [ 8] GetById value_feedback:0, dst:reg5, base:this, `a`
+ [ 20] GetById value_feedback:1, dst:reg5, base:reg5, `b`
+ [ 38] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/try-catch-completion-ordering.txt b/Tests/LibJS/Bytecode/expected/try-catch-completion-ordering.txt
index 5c88161f7e5..3fc0d1644d7 100644
--- a/Tests/LibJS/Bytecode/expected/try-catch-completion-ordering.txt
+++ b/Tests/LibJS/Bytecode/expected/try-catch-completion-ordering.txt
@@ -1,26 +1,31 @@
-$e7eb680d try-catch-completion-ordering.js:1:1
- Registers: 8
- Blocks: 3
+$0392d2ad try-catch-completion-ordering.js:1:1
+ Registers: 7
+ Blocks: 4
Locals: e~0
Constants:
[0] = Undefined
- [1] = Int32(42)
- [2] = Null
+ [1] = Null
+ [2] = <Empty>
+ [3] = Int32(42)
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:reg5
- [ 10] Jump target:block2
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:Undefined
block1:
- [ 18] Catch value_feedback:0, dst:reg6
- [ 20] Mov3 c0_dst:e~0, c0_src:reg6, c1_dst:reg7, c1_src:Undefined, c2_dst:reg7, c2_src:Int32(42)
- [ 40] Mov dst:reg5, src:reg7
- [ 50] End value:reg5
+ [ 28] Throw src:Null
block2:
- [ 58] MovSrcUndefined dst:reg6
- [ 60] Throw src:Null
+ [ 30] Catch value_feedback:0, dst:reg6
+ [ 38] Mov dst:reg5, src:Undefined
+ [ 48] Mov dst:e~0, src:<Empty>
+ [ 58] Mov dst:e~0, src:reg6
+ [ 68] Mov dst:reg5, src:Int32(42)
+ [ 78] Jump target:block3
+
+block3:
+ [ 80] End value:reg5
Exception handlers:
- [ 58 .. 68] => handler block1
+ [ 28 .. 30] => handler block2
diff --git a/Tests/LibJS/Bytecode/expected/try-catch-finally-register.txt b/Tests/LibJS/Bytecode/expected/try-catch-finally-register.txt
index 23d567dc7d1..9f269f5dde2 100644
--- a/Tests/LibJS/Bytecode/expected/try-catch-finally-register.txt
+++ b/Tests/LibJS/Bytecode/expected/try-catch-finally-register.txt
@@ -1,50 +1,51 @@
-$2a66ad4a try-catch-finally-register.js:1:1
- Registers: 10
- Blocks: 9
+$2fee8f6a try-catch-finally-register.js:1:1
+ Registers: 9
+ Blocks: 7
Locals: e~0
Constants:
[0] = Undefined
[1] = Int32(1)
- [2] = Int32(2)
- [3] = Int32(0)
- [4] = Int32(3)
+ [2] = Int32(0)
+ [3] = <Empty>
+ [4] = Int32(2)
+ [5] = Int32(3)
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:reg5
- [ 10] Jump target:block4
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:Undefined
block1:
- [ 18] Catch value_feedback:0, dst:reg7
- [ 20] Mov dst:reg6, src:Int32(1)
+ [ 28] Mov dst:reg5, src:Int32(1)
+ [ 38] Mov dst:reg6, src:Int32(0)
+ [ 48] Jump target:block4
block2:
- [ 30] Mov2 c0_dst:reg9, c0_src:Undefined, c1_dst:reg9, c1_src:Int32(3)
- [ 48] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg6, rhs:0, true_target:block5, false_target:block6
+ [ 50] Catch value_feedback:0, dst:reg8
+ [ 58] Mov dst:reg5, src:Undefined
+ [ 68] Mov dst:e~0, src:<Empty>
+ [ 78] Mov dst:e~0, src:reg8
+ [ 88] Mov dst:reg5, src:Int32(2)
+ [ 98] Mov dst:reg6, src:Int32(0)
+ [ a8] Jump target:block4
block3:
- [ 60] Catch value_feedback:1, dst:reg8
- [ 68] Mov3 c0_dst:e~0, c0_src:reg8, c1_dst:reg9, c1_src:Undefined, c2_dst:reg9, c2_src:Int32(2)
- [ 88] Mov2 c0_dst:reg5, c0_src:reg9, c1_dst:reg6, c1_src:Int32(0)
- [ a0] JumpLoop target:block2
+ [ b0] Catch value_feedback:1, dst:reg7
+ [ b8] Mov dst:reg6, src:Int32(1)
block4:
- [ a8] Mov3 c0_dst:reg8, c0_src:Undefined, c1_dst:reg8, c1_src:Int32(1), c2_dst:reg5, c2_src:reg8
- [ c8] Mov dst:reg6, src:Int32(0)
- [ d8] JumpLoop target:block2
+ [ c8] Mov dst:reg8, src:reg5
+ [ d8] Mov dst:reg5, src:Undefined
+ [ e8] Mov dst:reg5, src:Int32(3)
+ [ f8] Mov dst:reg5, src:reg8
+ [ 108] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg6, rhs:0, true_target:block6, false_target:block5
block5:
- [ e0] End value:reg5
+ [ 120] Throw src:reg7
block6:
- [ e8] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg6, rhs:2, true_target:block7, false_target:block8
-
-block7:
- [ 100] Return value:reg7
-
-block8:
- [ 108] Throw src:reg7
+ [ 128] End value:reg5
Exception handlers:
- [ 60 .. a8] => handler block1
- [ a8 .. e0] => handler block3
+ [ 28 .. 50] => handler block2
+ [ 50 .. b0] => handler block3
diff --git a/Tests/LibJS/Bytecode/expected/try-catch-scoping.txt b/Tests/LibJS/Bytecode/expected/try-catch-scoping.txt
index 6564c064c60..98c6fd20e08 100644
--- a/Tests/LibJS/Bytecode/expected/try-catch-scoping.txt
+++ b/Tests/LibJS/Bytecode/expected/try-catch-scoping.txt
@@ -1,108 +1,107 @@
-$bd6168df try-catch-scoping.js:11:1
- Registers: 8
+$996e2b0f try-catch-scoping.js:11:1
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `tryCatchWithBlocks`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, tryCatchWithBlocks
- [ 38] GetGlobal value_feedback:2, dst:reg7, `tryCatchFinallyWithBlocks`
- [ 48] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, tryCatchFinallyWithBlocks
- [ 68] End value:reg6
-
-
-tryCatchWithBlocks$862d6678 try-catch-scoping.js:2:5
- Registers: 11
- Blocks: 3
- Locals: y~0, z~1, e~2, x~3
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `tryCatchWithBlocks`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] GetGlobal value_feedback:2, dst:reg6, `tryCatchFinallyWithBlocks`
+ [ 58] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined
+ [ 78] End value:reg5
+
+
+tryCatchWithBlocks$475f75cc try-catch-scoping.js:2:9
+ Registers: 9
+ Blocks: 4
+ Locals: x~0, y~1, e~2, z~3
Constants:
[0] = Int32(1)
- [1] = Int32(3)
- [2] = Int32(2)
- [3] = Undefined
+ [1] = Int32(2)
+ [2] = <Empty>
+ [3] = Int32(3)
+ [4] = Undefined
block0:
[ 0] Enter
- [ 8] Mov dst:x~3, src:Int32(1)
- [ 18] Jump target:block2
+ [ 8] Mov dst:x~0, src:Int32(1)
block1:
- [ 20] Catch value_feedback:0, dst:reg5
- [ 28] Mov2 c0_dst:e~2, c0_src:reg5, c1_dst:z~1, c1_src:Int32(3)
- [ 40] GetGlobal value_feedback:1, dst:reg7, `console`
- [ 50] GetById value_feedback:2, dst:reg8, base:reg7, `log` (console.log)
- [ 68] Add arith_feedback:0, dst:reg9, lhs:x~3, rhs:e~2
- [ 78] Add arith_feedback:1, dst:reg10, lhs:reg9, rhs:z~1
- [ 88] Call value_feedback:3, call_feedback:0, dst:reg6, callee:reg8, this_value:reg7, console.log, arguments:[reg10]
- [ b0] End value:Undefined
+ [ 18] Mov dst:y~1, src:Int32(2)
+ [ 28] Throw src:y~1
block2:
- [ b8] Mov dst:y~0, src:Int32(2)
- [ c8] Throw src:y~0
+ [ 30] Catch value_feedback:0, dst:reg5
+ [ 38] Mov dst:e~2, src:<Empty>
+ [ 48] Mov dst:e~2, src:reg5
+ [ 58] Mov dst:z~3, src:Int32(3)
+ [ 68] GetGlobal value_feedback:1, dst:reg6, `console`
+ [ 78] GetById value_feedback:2, dst:reg7, base:reg6, `log`
+ [ 90] Add arith_feedback:0, dst:reg8, lhs:x~0, rhs:e~2
+ [ a0] Add arith_feedback:1, dst:reg8, lhs:reg8, rhs:z~3
+ [ b0] Call value_feedback:3, call_feedback:0, dst:reg6, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ d8] Jump target:block3
+
+block3:
+ [ e0] End value:Undefined
Exception handlers:
- [ b8 .. d0] => handler block1
+ [ 18 .. 30] => handler block2
-tryCatchFinallyWithBlocks$a5f0648a try-catch-scoping.js:14:5
- Registers: 12
- Blocks: 9
- Locals: y~0, e~1, z~2, x~3
+tryCatchFinallyWithBlocks$adde6df6 try-catch-scoping.js:14:9
+ Registers: 10
+ Blocks: 7
+ Locals: x~0, y~1, e~2, z~3
Constants:
[0] = Int32(1)
- [1] = Int32(0)
- [2] = Int32(2)
- [3] = Int32(3)
- [4] = Undefined
+ [1] = Int32(2)
+ [2] = <Empty>
+ [3] = Int32(0)
+ [4] = Int32(3)
+ [5] = Undefined
block0:
[ 0] Enter
- [ 8] Mov dst:x~3, src:Int32(1)
- [ 18] Jump target:block4
+ [ 8] Mov dst:x~0, src:Int32(1)
block1:
- [ 20] Catch value_feedback:0, dst:reg6
- [ 28] Mov dst:reg5, src:Int32(1)
+ [ 18] Mov dst:y~1, src:Int32(2)
+ [ 28] Throw src:y~1
block2:
- [ 38] Mov dst:z~2, src:Int32(3)
- [ 48] GetGlobal value_feedback:5, dst:reg8, `console`
- [ 58] GetById value_feedback:6, dst:reg10, base:reg8, `log` (console.log)
- [ 70] Mov dst:reg9, src:z~2
- [ 80] Call value_feedback:7, call_feedback:1, dst:reg7, callee:reg10, this_value:reg8, console.log, arguments:[reg9]
- [ a8] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg5, rhs:0, true_target:block5, false_target:block6
+ [ 30] Catch value_feedback:0, dst:reg7
+ [ 38] Mov dst:e~2, src:<Empty>
+ [ 48] Mov dst:e~2, src:reg7
+ [ 58] GetGlobal value_feedback:1, dst:reg8, `console`
+ [ 68] GetById value_feedback:2, dst:reg9, base:reg8, `log`
+ [ 80] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:reg8, arguments:[e~2]
+ [ a8] Mov dst:reg5, src:Int32(0)
+ [ b8] Jump target:block4
block3:
- [ c0] Catch value_feedback:1, dst:reg7
- [ c8] Mov dst:e~1, src:reg7
- [ d8] GetGlobal value_feedback:2, dst:reg9, `console`
- [ e8] GetById value_feedback:3, dst:reg10, base:reg9, `log` (console.log)
- [ 100] Mov dst:reg11, src:e~1
- [ 110] Call value_feedback:4, call_feedback:0, dst:reg8, callee:reg10, this_value:reg9, console.log, arguments:[reg11]
- [ 138] Mov dst:reg5, src:Int32(0)
- [ 148] JumpLoop target:block2
+ [ c0] Catch value_feedback:4, dst:reg6
+ [ c8] Mov dst:reg5, src:Int32(1)
block4:
- [ 150] Mov dst:y~0, src:Int32(2)
- [ 160] Throw src:y~0
+ [ d8] Mov dst:z~3, src:Int32(3)
+ [ e8] GetGlobal value_feedback:5, dst:reg7, `console`
+ [ f8] GetById value_feedback:6, dst:reg8, base:reg7, `log`
+ [ 110] Call value_feedback:7, call_feedback:1, dst:reg7, callee:reg8, this_value:reg7, arguments:[z~3]
+ [ 138] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg5, rhs:0, true_target:block6, false_target:block5
block5:
- [ 168] End value:Undefined
+ [ 150] Throw src:reg6
block6:
- [ 170] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg5, rhs:2, true_target:block7, false_target:block8
-
-block7:
- [ 188] Return value:reg6
-
-block8:
- [ 190] Throw src:reg6
+ [ 158] End value:Undefined
Exception handlers:
- [ c0 .. 150] => handler block1
- [ 150 .. 168] => handler block3
+ [ 18 .. 30] => handler block2
+ [ 30 .. c0] => handler block3
6
diff --git a/Tests/LibJS/Bytecode/expected/try-catch-terminated.txt b/Tests/LibJS/Bytecode/expected/try-catch-terminated.txt
index 73d575e1bb0..9129188323d 100644
--- a/Tests/LibJS/Bytecode/expected/try-catch-terminated.txt
+++ b/Tests/LibJS/Bytecode/expected/try-catch-terminated.txt
@@ -1,4 +1,4 @@
-$c7fd0018 try-catch-terminated.js:12:1
+$c5390f08 try-catch-terminated.js:12:1
Registers: 7
Blocks: 1
Constants:
@@ -6,29 +6,31 @@ $c7fd0018 try-catch-terminated.js:12:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `try_return`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, try_return
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `try_return`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-try_return$f1d3ca4f try-catch-terminated.js:5:5
+try_return$6825fe97 try-catch-terminated.js:5:5
Registers: 6
Blocks: 3
Locals: e~0
Constants:
[0] = Int32(1)
+ [1] = <Empty>
block0:
[ 0] Enter
- [ 8] Jump target:block2
block1:
- [ 10] Catch value_feedback:0, dst:reg5
- [ 18] Mov dst:e~0, src:reg5
- [ 28] Return value:e~0
+ [ 8] Throw src:Int32(1)
block2:
- [ 30] Throw src:Int32(1)
+ [ 10] Catch value_feedback:0, dst:reg5
+ [ 18] Mov dst:e~0, src:<Empty>
+ [ 28] Mov dst:e~0, src:reg5
+ [ 38] Return value:e~0
Exception handlers:
- [ 30 .. 38] => handler block1
+ [ 8 .. 10] => handler block2
diff --git a/Tests/LibJS/Bytecode/expected/try-finally-continue.txt b/Tests/LibJS/Bytecode/expected/try-finally-continue.txt
index f67a04345a7..ff375aecb40 100644
--- a/Tests/LibJS/Bytecode/expected/try-finally-continue.txt
+++ b/Tests/LibJS/Bytecode/expected/try-finally-continue.txt
@@ -1,165 +1,141 @@
-$78986e0e try-finally-continue.js:13:1
- Registers: 11
+$80e4413e try-finally-continue.js:13:1
+ Registers: 9
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `console`
- [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `log` (console.log)
- [ 30] GetGlobal value_feedback:2, dst:reg9, `continueThroughFinally`
- [ 40] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg9, this_value:Undefined, continueThroughFinally
- [ 60] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, console.log, arguments:[reg8]
- [ 88] GetGlobal value_feedback:5, dst:reg6, `console`
- [ 98] GetById value_feedback:6, dst:reg8, base:reg6, `log` (console.log)
- [ b0] GetGlobal value_feedback:7, dst:reg10, `breakThroughFinally`
- [ c0] Call value_feedback:8, call_feedback:2, dst:reg9, callee:reg10, this_value:Undefined, breakThroughFinally
- [ e0] Call value_feedback:9, call_feedback:3, dst:reg7, callee:reg8, this_value:reg6, console.log, arguments:[reg9]
- [ 108] End value:reg7
-
-
-continueThroughFinally$9f101dc6 try-finally-continue.js:2:5
- Registers: 9
- Blocks: 15
- Locals: i~0, result~1
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `console`
+ [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 40] GetGlobal value_feedback:2, dst:reg8, `continueThroughFinally`
+ [ 50] Call value_feedback:3, call_feedback:0, dst:reg8, callee:reg8, this_value:Undefined
+ [ 70] Call value_feedback:4, call_feedback:1, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 98] GetGlobal value_feedback:5, dst:reg6, `console`
+ [ a8] GetById value_feedback:6, dst:reg7, base:reg6, `log`
+ [ c0] GetGlobal value_feedback:7, dst:reg8, `breakThroughFinally`
+ [ d0] Call value_feedback:8, call_feedback:2, dst:reg8, callee:reg8, this_value:Undefined
+ [ f0] Call value_feedback:9, call_feedback:3, dst:reg5, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ 118] End value:reg5
+
+
+continueThroughFinally$3ce638b2 try-finally-continue.js:2:9
+ Registers: 8
+ Blocks: 12
+ Locals: result~0, i~1
Constants:
[0] = Int32(0)
- [1] = Int32(3)
- [2] = Int32(1)
+ [1] = Int32(1)
+ [2] = Int32(2)
[3] = Int32(10)
- [4] = Int32(2)
- [5] = Undefined
+ [4] = Int32(3)
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:result~1, c0_src:Int32(0), c1_dst:i~0, c1_src:Int32(0)
- [ 20] Jump target:block3
+ [ 8] Mov dst:result~0, src:Int32(0)
+ [ 18] Mov dst:i~1, src:Int32(0)
+ [ 28] Jump target:block10
block1:
- [ 28] Jump target:block7
+ [ 30] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:i~1, rhs:1, true_target:block2, false_target:block3
block2:
- [ 30] PostfixIncrement arith_feedback:1, dst:reg5, src:i~0
+ [ 48] Mov dst:reg5, src:Int32(2)
+ [ 58] Jump target:block5
block3:
- [ 40] JumpLessThanLoopRhsInt32 arith_feedback:0, lhs:i~0, rhs:3, true_target:block1, false_target:block4
+ [ 60] Add arith_feedback:1, dst:result~0, lhs:result~0, rhs:i~1
+ [ 70] Mov dst:reg5, src:Int32(0)
+ [ 80] Jump target:block5
block4:
- [ 58] Return value:result~1
+ [ 88] Catch value_feedback:0, dst:reg6
+ [ 90] Mov dst:reg5, src:Int32(1)
block5:
- [ 60] Catch value_feedback:0, dst:reg6
- [ 68] Mov dst:reg5, src:Int32(1)
+ [ a0] AddRhsInt32 arith_feedback:2, dst:result~0, lhs:result~0, rhs:10
+ [ b0] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg5, rhs:0, true_target:block9, false_target:block6
block6:
- [ 78] Mov dst:reg8, src:result~1
- [ 88] AddRhsInt32 arith_feedback:4, dst:reg7, lhs:reg8, rhs:10
- [ 98] Mov dst:result~1, src:reg7
- [ a8] JumpStrictlyEqualsRhsInt32 arith_feedback:5, lhs:reg5, rhs:0, true_target:block10, false_target:block11
+ [ c8] JumpStrictlyEqualsRhsInt32 arith_feedback:4, lhs:reg5, rhs:2, true_target:block7, false_target:block8
block7:
- [ c0] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:i~0, rhs:1, true_target:block8, false_target:block9
+ [ e0] Jump target:block9
block8:
- [ d8] Mov dst:reg5, src:Int32(3)
- [ e8] JumpLoop target:block6
+ [ e8] Throw src:reg6
block9:
- [ f0] Mov dst:reg7, src:result~1
- [ 100] Add arith_feedback:3, dst:reg8, lhs:reg7, rhs:i~0
- [ 110] Mov2 c0_dst:result~1, c0_src:reg8, c1_dst:reg5, c1_src:Int32(0)
- [ 128] JumpLoop target:block6
+ [ f0] Increment arith_feedback:5, dst:i~1
block10:
- [ 130] JumpLoop target:block2
+ [ f8] JumpLessThanLoopRhsInt32 arith_feedback:6, lhs:i~1, rhs:3, true_target:block1, false_target:block11
block11:
- [ 138] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:6, lhs:reg5, rhs:3, true_target:block2, false_target:block12
-
-block12:
- [ 150] JumpStrictlyEqualsRhsInt32 arith_feedback:7, lhs:reg5, rhs:2, true_target:block13, false_target:block14
-
-block13:
- [ 168] Return value:reg6
-
-block14:
- [ 170] Throw src:reg6
+ [ 110] Return value:result~0
Exception handlers:
- [ c0 .. 130] => handler block5
+ [ 30 .. 88] => handler block4
-breakThroughFinally$39a8852a try-finally-continue.js:16:5
- Registers: 9
- Blocks: 15
- Locals: i~0, result~1
+breakThroughFinally$e163e2ce try-finally-continue.js:16:9
+ Registers: 8
+ Blocks: 12
+ Locals: result~0, i~1
Constants:
[0] = Int32(0)
- [1] = Int32(10)
+ [1] = Int32(2)
[2] = Int32(1)
- [3] = Int32(2)
- [4] = Int32(3)
- [5] = Int32(100)
- [6] = Undefined
+ [3] = Int32(100)
+ [4] = Int32(10)
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:result~1, c0_src:Int32(0), c1_dst:i~0, c1_src:Int32(0)
- [ 20] Jump target:block3
+ [ 8] Mov dst:result~0, src:Int32(0)
+ [ 18] Mov dst:i~1, src:Int32(0)
+ [ 28] Jump target:block10
block1:
- [ 28] Jump target:block7
+ [ 30] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:i~1, rhs:2, true_target:block2, false_target:block3
block2:
- [ 30] PostfixIncrement arith_feedback:1, dst:reg5, src:i~0
+ [ 48] Mov dst:reg5, src:Int32(2)
+ [ 58] Jump target:block5
block3:
- [ 40] JumpLessThanLoopRhsInt32 arith_feedback:0, lhs:i~0, rhs:10, true_target:block1, false_target:block4
+ [ 60] Add arith_feedback:1, dst:result~0, lhs:result~0, rhs:i~1
+ [ 70] Mov dst:reg5, src:Int32(0)
+ [ 80] Jump target:block5
block4:
- [ 58] Return value:result~1
+ [ 88] Catch value_feedback:0, dst:reg6
+ [ 90] Mov dst:reg5, src:Int32(1)
block5:
- [ 60] Catch value_feedback:0, dst:reg6
- [ 68] Mov dst:reg5, src:Int32(1)
+ [ a0] AddRhsInt32 arith_feedback:2, dst:result~0, lhs:result~0, rhs:100
+ [ b0] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg5, rhs:0, true_target:block9, false_target:block6
block6:
- [ 78] Mov dst:reg8, src:result~1
- [ 88] AddRhsInt32 arith_feedback:4, dst:reg7, lhs:reg8, rhs:100
- [ 98] Mov dst:result~1, src:reg7
- [ a8] JumpStrictlyEqualsRhsInt32 arith_feedback:5, lhs:reg5, rhs:0, true_target:block10, false_target:block11
+ [ c8] JumpStrictlyEqualsRhsInt32 arith_feedback:4, lhs:reg5, rhs:2, true_target:block7, false_target:block8
block7:
- [ c0] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:i~0, rhs:2, true_target:block8, false_target:block9
+ [ e0] Jump target:block11
block8:
- [ d8] Mov dst:reg5, src:Int32(3)
- [ e8] JumpLoop target:block6
+ [ e8] Throw src:reg6
block9:
- [ f0] Mov dst:reg7, src:result~1
- [ 100] Add arith_feedback:3, dst:reg8, lhs:reg7, rhs:i~0
- [ 110] Mov2 c0_dst:result~1, c0_src:reg8, c1_dst:reg5, c1_src:Int32(0)
- [ 128] JumpLoop target:block6
+ [ f0] Increment arith_feedback:5, dst:i~1
block10:
- [ 130] JumpLoop target:block2
+ [ f8] JumpLessThanLoopRhsInt32 arith_feedback:6, lhs:i~1, rhs:10, true_target:block1, false_target:block11
block11:
- [ 138] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:6, lhs:reg5, rhs:3, true_target:block4, false_target:block12
-
-block12:
- [ 150] JumpStrictlyEqualsRhsInt32 arith_feedback:7, lhs:reg5, rhs:2, true_target:block13, false_target:block14
-
-block13:
- [ 168] Return value:reg6
-
-block14:
- [ 170] Throw src:reg6
+ [ 110] Return value:result~0
Exception handlers:
- [ c0 .. 130] => handler block5
+ [ 30 .. 88] => handler block4
32
diff --git a/Tests/LibJS/Bytecode/expected/try-finally.txt b/Tests/LibJS/Bytecode/expected/try-finally.txt
index 6ec492c4bf9..3138114bd2c 100644
--- a/Tests/LibJS/Bytecode/expected/try-finally.txt
+++ b/Tests/LibJS/Bytecode/expected/try-finally.txt
@@ -1,22 +1,23 @@
-$3ce5efbc try-finally.js:8:1
- Registers: 8
+$3a21feac try-finally.js:8:1
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `basicTryFinally`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, basicTryFinally
- [ 38] GetGlobal value_feedback:2, dst:reg7, `breakThroughFinally`
- [ 48] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, breakThroughFinally
- [ 68] GetGlobal value_feedback:4, dst:reg7, `nestedTryFinallyWithBreak`
- [ 78] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg7, this_value:Undefined, nestedTryFinallyWithBreak
- [ 98] End value:reg5
-
-
-basicTryFinally$ac313afe try-finally.js:2:5
- Registers: 10
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `basicTryFinally`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] GetGlobal value_feedback:2, dst:reg6, `breakThroughFinally`
+ [ 58] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined
+ [ 78] GetGlobal value_feedback:4, dst:reg6, `nestedTryFinallyWithBreak`
+ [ 88] Call value_feedback:5, call_feedback:2, dst:reg5, callee:reg6, this_value:Undefined
+ [ a8] End value:reg5
+
+
+basicTryFinally$8dff5ef2 try-finally.js:2:9
+ Registers: 9
Blocks: 8
Constants:
[0] = Int32(1)
@@ -27,203 +28,171 @@ basicTryFinally$ac313afe try-finally.js:2:5
block0:
[ 0] Enter
- [ 8] Jump target:block3
block1:
- [ 10] Catch value_feedback:0, dst:reg6
- [ 18] Mov dst:reg5, src:Int32(1)
+ [ 8] Mov dst:reg6, src:Int32(1)
+ [ 18] Mov dst:reg5, src:Int32(2)
+ [ 28] Jump target:block3
block2:
- [ 28] GetGlobal value_feedback:1, dst:reg8, `console`
- [ 38] GetById value_feedback:2, dst:reg9, base:reg8, `log` (console.log)
- [ 50] Call value_feedback:3, call_feedback:0, dst:reg7, callee:reg9, this_value:reg8, console.log, arguments:[String("finally")]
- [ 78] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg5, rhs:0, true_target:block4, false_target:block5
+ [ 30] Catch value_feedback:0, dst:reg6
+ [ 38] Mov dst:reg5, src:Int32(1)
block3:
- [ 90] Mov2 c0_dst:reg6, c0_src:Int32(1), c1_dst:reg5, c1_src:Int32(2)
- [ a8] JumpLoop target:block2
+ [ 48] GetGlobal value_feedback:1, dst:reg7, `console`
+ [ 58] GetById value_feedback:2, dst:reg8, base:reg7, `log`
+ [ 70] Call value_feedback:3, call_feedback:0, dst:reg7, callee:reg8, this_value:reg7, arguments:[String("finally")]
+ [ 98] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg5, rhs:0, true_target:block7, false_target:block4
block4:
- [ b0] End value:Undefined
+ [ b0] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg5, rhs:2, true_target:block5, false_target:block6
block5:
- [ b8] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg5, rhs:2, true_target:block6, false_target:block7
+ [ c8] Return value:reg6
block6:
- [ d0] Return value:reg6
+ [ d0] Throw src:reg6
block7:
- [ d8] Throw src:reg6
+ [ d8] End value:Undefined
Exception handlers:
- [ 90 .. b0] => handler block1
+ [ 8 .. 30] => handler block2
-breakThroughFinally$27179709 try-finally.js:11:5
- Registers: 11
- Blocks: 15
+breakThroughFinally$b9227aa6 try-finally.js:11:10
+ Registers: 9
+ Blocks: 12
Locals: i~0
Constants:
[0] = Int32(0)
- [1] = Int32(10)
- [2] = Int32(1)
- [3] = Int32(5)
- [4] = Int32(3)
- [5] = Int32(2)
- [6] = Undefined
+ [1] = Int32(5)
+ [2] = Int32(2)
+ [3] = Int32(1)
+ [4] = Int32(10)
+ [5] = Undefined
block0:
[ 0] Enter
[ 8] Mov dst:i~0, src:Int32(0)
- [ 18] Jump target:block3
+ [ 18] Jump target:block10
block1:
- [ 20] Jump target:block7
+ [ 20] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:i~0, rhs:5, true_target:block2, false_target:block3
block2:
- [ 28] PostfixIncrement arith_feedback:1, dst:reg5, src:i~0
+ [ 38] Mov dst:reg5, src:Int32(2)
+ [ 48] Jump target:block5
block3:
- [ 38] JumpLessThanLoopRhsInt32 arith_feedback:0, lhs:i~0, rhs:10, true_target:block1, false_target:block4
+ [ 50] Mov dst:reg5, src:Int32(0)
+ [ 60] Jump target:block5
block4:
- [ 50] End value:Undefined
+ [ 68] Catch value_feedback:0, dst:reg6
+ [ 70] Mov dst:reg5, src:Int32(1)
block5:
- [ 58] Catch value_feedback:0, dst:reg6
- [ 60] Mov dst:reg5, src:Int32(1)
+ [ 80] GetGlobal value_feedback:1, dst:reg7, `console`
+ [ 90] GetById value_feedback:2, dst:reg8, base:reg7, `log`
+ [ a8] Call value_feedback:3, call_feedback:0, dst:reg7, callee:reg8, this_value:reg7, arguments:[i~0]
+ [ d0] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg5, rhs:0, true_target:block9, false_target:block6
block6:
- [ 70] GetGlobal value_feedback:1, dst:reg8, `console`
- [ 80] GetById value_feedback:2, dst:reg9, base:reg8, `log` (console.log)
- [ 98] Mov dst:reg10, src:i~0
- [ a8] Call value_feedback:3, call_feedback:0, dst:reg7, callee:reg9, this_value:reg8, console.log, arguments:[reg10]
- [ d0] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg5, rhs:0, true_target:block10, false_target:block11
+ [ e8] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:reg5, rhs:2, true_target:block7, false_target:block8
block7:
- [ e8] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:i~0, rhs:5, true_target:block8, false_target:block9
+ [ 100] Jump target:block11
block8:
- [ 100] Mov dst:reg5, src:Int32(3)
- [ 110] JumpLoop target:block6
+ [ 108] Throw src:reg6
block9:
- [ 118] Mov dst:reg5, src:Int32(0)
- [ 128] JumpLoop target:block6
+ [ 110] Increment arith_feedback:3, dst:i~0
block10:
- [ 130] JumpLoop target:block2
+ [ 118] JumpLessThanLoopRhsInt32 arith_feedback:4, lhs:i~0, rhs:10, true_target:block1, false_target:block11
block11:
- [ 138] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:4, lhs:reg5, rhs:3, true_target:block4, false_target:block12
-
-block12:
- [ 150] JumpStrictlyEqualsRhsInt32 arith_feedback:5, lhs:reg5, rhs:2, true_target:block13, false_target:block14
-
-block13:
- [ 168] Return value:reg6
-
-block14:
- [ 170] Throw src:reg6
+ [ 130] End value:Undefined
Exception handlers:
- [ e8 .. 130] => handler block5
+ [ 20 .. 68] => handler block4
-nestedTryFinallyWithBreak$9e2f6d8b try-finally.js:22:12
- Registers: 12
- Blocks: 21
+nestedTryFinallyWithBreak$0a2b5c13 try-finally.js:22:21
+ Registers: 11
+ Blocks: 15
Locals: i~0
Constants:
[0] = Int32(0)
- [1] = Int32(1)
- [2] = Int32(3)
+ [1] = Int32(2)
+ [2] = Int32(1)
[3] = String("inner")
- [4] = Int32(2)
+ [4] = String("outer")
[5] = Undefined
- [6] = String("outer")
block0:
[ 0] Enter
[ 8] Mov dst:i~0, src:Int32(0)
block1:
- [ 18] Jump target:block6
+ [ 18] Mov dst:reg7, src:Int32(2)
+ [ 28] Jump target:block3
block2:
- [ 20] PostfixIncrement arith_feedback:0, dst:reg5, src:i~0
- [ 30] JumpLoop target:block1
+ [ 30] Catch value_feedback:0, dst:reg8
+ [ 38] Mov dst:reg7, src:Int32(1)
block3:
- [ 38] End value:Undefined
+ [ 48] GetGlobal value_feedback:1, dst:reg9, `console`
+ [ 58] GetById value_feedback:2, dst:reg10, base:reg9, `log`
+ [ 70] Call value_feedback:3, call_feedback:0, dst:reg9, callee:reg10, this_value:reg9, arguments:[String("inner")]
+ [ 98] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg7, rhs:0, true_target:block7, false_target:block4
block4:
- [ 40] Catch value_feedback:0, dst:reg6
- [ 48] Mov dst:reg5, src:Int32(1)
+ [ b0] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg7, rhs:2, true_target:block5, false_target:block6
block5:
- [ 58] GetGlobal value_feedback:5, dst:reg8, `console`
- [ 68] GetById value_feedback:6, dst:reg9, base:reg8, `log` (console.log)
- [ 80] Call value_feedback:7, call_feedback:1, dst:reg7, callee:reg9, this_value:reg8, console.log, arguments:[String("outer")]
- [ a8] JumpStrictlyEqualsRhsInt32 arith_feedback:4, lhs:reg5, rhs:0, true_target:block16, false_target:block17
+ [ c8] Mov dst:reg5, src:Int32(2)
+ [ d8] Jump target:block9
block6:
- [ c0] Jump target:block9
+ [ e0] Throw src:reg8
block7:
- [ c8] Catch value_feedback:1, dst:reg8
- [ d0] Mov dst:reg7, src:Int32(1)
+ [ e8] Mov dst:reg5, src:Int32(0)
+ [ f8] Jump target:block9
block8:
- [ e0] GetGlobal value_feedback:2, dst:reg10, `console`
- [ f0] GetById value_feedback:3, dst:reg11, base:reg10, `log` (console.log)
- [ 108] Call value_feedback:4, call_feedback:0, dst:reg9, callee:reg11, this_value:reg10, console.log, arguments:[String("inner")]
- [ 130] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg7, rhs:0, true_target:block11, false_target:block12
+ [ 100] Catch value_feedback:4, dst:reg6
+ [ 108] Mov dst:reg5, src:Int32(1)
block9:
- [ 148] Mov dst:reg7, src:Int32(3)
- [ 158] JumpLoop target:block8
+ [ 118] GetGlobal value_feedback:5, dst:reg7, `console`
+ [ 128] GetById value_feedback:6, dst:reg8, base:reg7, `log`
+ [ 140] Call value_feedback:7, call_feedback:1, dst:reg7, callee:reg8, this_value:reg7, arguments:[String("outer")]
+ [ 168] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:reg5, rhs:0, true_target:block13, false_target:block10
block10:
- [ 160] Mov dst:reg5, src:Int32(3)
- [ 170] JumpLoop target:block5
+ [ 180] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg5, rhs:2, true_target:block11, false_target:block12
block11:
- [ 178] Mov dst:reg5, src:Int32(0)
- [ 188] JumpLoop target:block5
+ [ 198] Jump target:block14
block12:
- [ 190] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:2, lhs:reg7, rhs:3, true_target:block10, false_target:block13
+ [ 1a0] Throw src:reg6
block13:
- [ 1a8] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg7, rhs:2, true_target:block14, false_target:block15
+ [ 1a8] Increment arith_feedback:4, dst:i~0
+ [ 1b0] JumpLoop target:block1
block14:
- [ 1c0] Mov2 c0_dst:reg5, c0_src:reg7, c1_dst:reg6, c1_src:reg8
- [ 1d8] JumpLoop target:block5
-
-block15:
- [ 1e0] Throw src:reg8
-
-block16:
- [ 1e8] JumpLoop target:block2
-
-block17:
- [ 1f0] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:5, lhs:reg5, rhs:3, true_target:block3, false_target:block18
-
-block18:
- [ 208] JumpStrictlyEqualsRhsInt32 arith_feedback:6, lhs:reg5, rhs:2, true_target:block19, false_target:block20
-
-block19:
- [ 220] Return value:reg6
-
-block20:
- [ 228] Throw src:reg6
+ [ 1b8] End value:Undefined
Exception handlers:
- [ c0 .. 148] => handler block4
- [ 148 .. 178] => handler block7
- [ 178 .. 1e8] => handler block4
+ [ 18 .. 30] => handler block2
+ [ 30 .. 100] => handler block8
"finally"
diff --git a/Tests/LibJS/Bytecode/expected/update-member-expression.txt b/Tests/LibJS/Bytecode/expected/update-member-expression.txt
index 87d697fb47d..65eaf723318 100644
--- a/Tests/LibJS/Bytecode/expected/update-member-expression.txt
+++ b/Tests/LibJS/Bytecode/expected/update-member-expression.txt
@@ -1,45 +1,44 @@
-$a9ab6c09 update-member-expression.js:13:1
- Registers: 9
+$a6e77af9 update-member-expression.js:13:1
+ Registers: 8
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `postfix_increment`
- [ 18] NewObject dst:reg7
- [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, postfix_increment, arguments:[reg7]
- [ 50] GetGlobal value_feedback:2, dst:reg7, `prefix_decrement`
- [ 60] NewObject dst:reg8
- [ 70] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, prefix_decrement, arguments:[reg8]
- [ 98] End value:reg6
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `postfix_increment`
+ [ 28] NewObject dst:reg7
+ [ 38] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 60] GetGlobal value_feedback:2, dst:reg6, `prefix_decrement`
+ [ 70] NewObject dst:reg7
+ [ 80] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ a8] End value:reg5
-postfix_increment$c28f93c4 update-member-expression.js:6:14
- Registers: 8
+postfix_increment$cadb66f4 update-member-expression.js:6:14
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] Mov dst:reg5, src:arg0
- [ 18] GetById value_feedback:0, dst:reg6, base:reg5, `count` (obj.count)
- [ 30] PostfixIncrement arith_feedback:0, dst:reg7, src:reg6
- [ 40] PutById base:reg5, `count`, src:reg6, kind:Normal
- [ 60] End value:Undefined
+ [ 8] GetById value_feedback:0, dst:reg5, base:arg0, `count`
+ [ 20] PostfixIncrement arith_feedback:0, dst:reg6, src:reg5
+ [ 30] PutById base:arg0, `count`, src:reg5, kind:Normal
+ [ 50] End value:Undefined
-prefix_decrement$73c0e37a update-member-expression.js:10:5
- Registers: 7
+prefix_decrement$7684d48a update-member-expression.js:10:5
+ Registers: 6
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] Mov dst:reg5, src:arg0
- [ 18] GetById value_feedback:0, dst:reg6, base:reg5, `count` (obj.count)
- [ 30] Decrement arith_feedback:0, dst:reg6
- [ 38] PutById base:reg5, `count`, src:reg6, kind:Normal
- [ 58] End value:Undefined
+ [ 8] GetById value_feedback:0, dst:reg5, base:arg0, `count`
+ [ 20] Decrement arith_feedback:0, dst:reg5
+ [ 28] PutById base:arg0, `count`, src:reg5, kind:Normal
+ [ 48] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/using-declaration-non-local-env.txt b/Tests/LibJS/Bytecode/expected/using-declaration-non-local-env.txt
index ea2b35983de..7fa338f42d3 100644
--- a/Tests/LibJS/Bytecode/expected/using-declaration-non-local-env.txt
+++ b/Tests/LibJS/Bytecode/expected/using-declaration-non-local-env.txt
@@ -1,78 +1,74 @@
-$091ab4cd using-declaration-non-local-env.js:1:1
- Registers: 9
- Blocks: 3
+$84f4cb35 using-declaration-non-local-env.js:1:1
+ Registers: 7
+ Blocks: 4
Locals: e~0
Constants:
[0] = Undefined
+ [1] = <Empty>
block0:
[ 0] Enter
- [ 8] MovSrcUndefined dst:reg5
- [ 10] Jump target:block2
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] Mov dst:reg5, src:Undefined
block1:
- [ 18] Catch value_feedback:0, dst:reg6
- [ 20] Mov3 c0_dst:e~0, c0_src:reg6, c1_dst:reg7, c1_src:Undefined, c2_dst:reg5, c2_src:reg7
- [ 40] End value:reg5
+ [ 28] NewFunction dst:reg6, shared_function_data_index:0
+ [ 40] Call value_feedback:0, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 60] Jump target:block3
block2:
- [ 48] MovSrcUndefined dst:reg6
- [ 50] NewFunction dst:reg8, shared_function_data_index:0
- [ 68] Call value_feedback:1, call_feedback:0, dst:reg7, callee:reg8, this_value:Undefined
- [ 88] Mov2 c0_dst:reg6, c0_src:reg7, c1_dst:reg5, c1_src:reg6
- [ a0] End value:reg5
+ [ 68] Catch value_feedback:1, dst:reg6
+ [ 70] Mov dst:reg5, src:Undefined
+ [ 80] Mov dst:e~0, src:<Empty>
+ [ 90] Mov dst:e~0, src:reg6
+ [ a0] Jump target:block3
+
+block3:
+ [ a8] End value:reg5
Exception handlers:
- [ 48 .. a8] => handler block1
+ [ 28 .. 68] => handler block2
-$9b8ec936 using-declaration-non-local-env.js:1:21
- Registers: 11
- Blocks: 8
+$44ed2954 using-declaration-non-local-env.js:1:19
+ Registers: 10
+ Blocks: 6
Constants:
- [0] = Int32(1)
- [1] = Undefined
- [2] = Int32(0)
- [3] = Int32(2)
+ [0] = Undefined
+ [1] = Int32(0)
+ [2] = Int32(1)
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
[ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateImmutableBinding environment:reg5, `x`, strict_binding:true
+ [ 28] CreateVariable `x`, is_immutable:true, is_global:false, is_strict:true
[ 38] NewDisposableResourceStack dst:reg6
- [ 40] Jump target:block3
block1:
- [ 48] Catch value_feedback:0, dst:reg8
- [ 50] SetLexicalEnvironment environment:reg5
- [ 58] Mov dst:reg7, src:Int32(1)
+ [ 40] NewObject dst:reg9
+ [ 50] AddDisposableResource stack:reg6, value:reg9, hint:0
+ [ 60] InitializeLexicalBinding `x`, src:reg9
+ [ 78] NewFunction dst:reg9, shared_function_data_index:0
+ [ 90] Call value_feedback:0, call_feedback:0, dst:reg9, callee:reg9, this_value:Undefined
+ [ b0] Mov dst:reg7, src:Int32(0)
+ [ c0] Jump target:block3
block2:
- [ 68] DisposeResources stack:reg6, completion_type:reg7, completion_value:reg8
- [ 78] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg7, rhs:0, true_target:block4, false_target:block5
+ [ c8] Catch value_feedback:1, dst:reg8
+ [ d0] SetLexicalEnvironment environment:reg5
+ [ d8] Mov dst:reg7, src:Int32(1)
block3:
- [ 90] NewObject dst:reg9
- [ a0] AddDisposableResource stack:reg6, value:reg9, hint:0
- [ b0] InitializeLexicalBinding `x`, src:reg9
- [ c8] NewFunction dst:reg10, shared_function_data_index:0
- [ e0] Call value_feedback:1, call_feedback:0, dst:reg9, callee:reg10, this_value:Undefined
- [ 100] Mov dst:reg7, src:Int32(0)
- [ 110] JumpLoop target:block2
+ [ e8] DisposeResources stack:reg6, completion_type:reg7, completion_value:reg8
+ [ f8] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg7, rhs:0, true_target:block5, false_target:block4
block4:
- [ 118] SetLexicalEnvironment environment:reg4
- [ 120] End value:Undefined
+ [ 110] Throw src:reg8
block5:
- [ 128] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg7, rhs:2, true_target:block6, false_target:block7
-
-block6:
- [ 140] Return value:reg8
-
-block7:
- [ 148] Throw src:reg8
+ [ 118] SetLexicalEnvironment environment:reg4
+ [ 120] End value:Undefined
Exception handlers:
- [ 90 .. 118] => handler block1
+ [ 40 .. c8] => handler block2
diff --git a/Tests/LibJS/Bytecode/expected/var-binding-access.txt b/Tests/LibJS/Bytecode/expected/var-binding-access.txt
index 91209db24f2..29d595f1630 100644
--- a/Tests/LibJS/Bytecode/expected/var-binding-access.txt
+++ b/Tests/LibJS/Bytecode/expected/var-binding-access.txt
@@ -1,19 +1,20 @@
-$1ed4f972 var-binding-access.js:22:1
- Registers: 8
+$2ca8aec2 var-binding-access.js:22:1
+ Registers: 7
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `var_access`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, var_access
- [ 38] GetGlobal value_feedback:2, dst:reg7, `let_access`
- [ 48] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, let_access
- [ 68] End value:reg6
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `var_access`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] GetGlobal value_feedback:2, dst:reg6, `let_access`
+ [ 58] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined
+ [ 78] End value:reg5
-var_access$e4db39e3 var-binding-access.js:5:5
+var_access$192c9e6f var-binding-access.js:5:9
Registers: 6
Blocks: 1
Constants:
@@ -30,18 +31,16 @@ block0:
[ 78] Return value:reg5
-let_access$eea15a78 var-binding-access.js:14:5
- Registers: 7
+let_access$3bd63894 var-binding-access.js:14:9
+ Registers: 6
Blocks: 1
Constants:
[0] = Int32(1)
block0:
[ 0] Enter
- [ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
- [ 28] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
- [ 38] InitializeLexicalBinding `x`, src:Int32(1)
- [ 50] NewFunction dst:reg6, shared_function_data_index:0
- [ 68] GetBinding value_feedback:0, dst:reg6, `x`
- [ 80] Return value:reg6
+ [ 8] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
+ [ 18] InitializeLexicalBinding `x`, src:Int32(1)
+ [ 30] NewFunction dst:reg5, shared_function_data_index:0
+ [ 48] GetBinding value_feedback:0, dst:reg5, `x`
+ [ 60] Return value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/var-env-capacity-with-param-expressions.txt b/Tests/LibJS/Bytecode/expected/var-env-capacity-with-param-expressions.txt
index 0b553b97b1d..651be3639f9 100644
--- a/Tests/LibJS/Bytecode/expected/var-env-capacity-with-param-expressions.txt
+++ b/Tests/LibJS/Bytecode/expected/var-env-capacity-with-param-expressions.txt
@@ -1,4 +1,4 @@
-$12cfcca1 var-env-capacity-with-param-expressions.js:5:1
+$100bdb91 var-env-capacity-with-param-expressions.js:5:1
Registers: 7
Blocks: 1
Constants:
@@ -6,12 +6,13 @@ $12cfcca1 var-env-capacity-with-param-expressions.js:5:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-f$9f7af34e var-env-capacity-with-param-expressions.js:3:9
+f$e7951be9 var-env-capacity-with-param-expressions.js:1:12
Registers: 10
Blocks: 3
Constants:
@@ -22,7 +23,7 @@ f$9f7af34e var-env-capacity-with-param-expressions.js:3:9
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:2, is_catch_environment:false
+ [ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
[ 28] CreateVariable `x`, is_immutable:false, is_global:false, is_strict:false
[ 38] CreateArguments is_immutable:false, creates_parameter_bindings:false
[ 48] JumpUndefined condition:arg0, true_target:block1, false_target:block2
@@ -34,26 +35,25 @@ block2:
[ 68] InitializeLexicalBinding `x`, src:arg0
[ 80] CreateVariableEnvironment capacity:3
[ 88] GetLexicalEnvironment dst:reg6
- [ 90] MovSrcUndefined dst:reg7
- [ 98] CreateVariable `a`, is_immutable:false, is_global:false, is_strict:false
- [ a8] InitializeVariableBinding `a`, src:reg7
- [ c0] MovSrcUndefined dst:reg7
- [ c8] CreateVariable `b`, is_immutable:false, is_global:false, is_strict:false
- [ d8] InitializeVariableBinding `b`, src:reg7
- [ f0] MovSrcUndefined dst:reg7
+ [ 90] CreateLexicalEnvironment dst:reg7, parent:reg6, capacity:3, is_catch_environment:false
+ [ a8] CreateVariable `a`, is_immutable:false, is_global:false, is_strict:false
+ [ b8] InitializeVariableBinding `a`, src:Undefined
+ [ d0] CreateVariable `b`, is_immutable:false, is_global:false, is_strict:false
+ [ e0] InitializeVariableBinding `b`, src:Undefined
[ f8] CreateVariable `c`, is_immutable:false, is_global:false, is_strict:false
- [ 108] InitializeVariableBinding `c`, src:reg7
+ [ 108] InitializeVariableBinding `c`, src:Undefined
[ 120] DynamicGetCalleeAndThisFromEnvironment value_feedback:0, callee:reg8, this_value:reg9, `eval`
- [ 138] CallDirectEval value_feedback:1, call_feedback:0, dst:reg7, callee:reg8, this_value:reg9, eval, arguments:[String("")]
+ [ 138] CallDirectEval value_feedback:1, call_feedback:0, dst:reg8, callee:reg8, this_value:reg9, arguments:[String("")]
[ 160] End value:Undefined
-eval$3b472b8b
- Registers: 5
+eval$3e0b1c9b
+ Registers: 6
Blocks: 1
Constants:
[0] = Undefined
block0:
[ 0] Enter
- [ 8] End value:Undefined
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] End value:reg5
diff --git a/Tests/LibJS/Bytecode/expected/var-hoisting-tdz.txt b/Tests/LibJS/Bytecode/expected/var-hoisting-tdz.txt
index f750c3d7de2..81849bc705f 100644
--- a/Tests/LibJS/Bytecode/expected/var-hoisting-tdz.txt
+++ b/Tests/LibJS/Bytecode/expected/var-hoisting-tdz.txt
@@ -1,4 +1,4 @@
-$fd650eed var-hoisting-tdz.js:9:1
+$faa11ddd var-hoisting-tdz.js:9:1
Registers: 7
Blocks: 1
Constants:
@@ -6,12 +6,13 @@ $fd650eed var-hoisting-tdz.js:9:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `isect`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, isect
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `isect`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-isect$e526d05d var-hoisting-tdz.js:5:5
+isect$cab742dc var-hoisting-tdz.js:5:12
Registers: 6
Blocks: 7
Locals: i~0
@@ -22,24 +23,25 @@ isect$e526d05d var-hoisting-tdz.js:5:5
block0:
[ 0] Enter
- [ 8] Mov2 c0_dst:i~0, c0_src:Undefined, c1_dst:i~0, c1_src:Int32(0)
- [ 20] Jump target:block2
+ [ 8] Mov dst:i~0, src:Undefined
+ [ 18] Mov dst:i~0, src:Int32(0)
+ [ 28] Jump target:block2
block1:
- [ 28] PostfixIncrement arith_feedback:1, dst:reg5, src:i~0
+ [ 30] Increment arith_feedback:0, dst:i~0
block2:
- [ 38] JumpLessThanLoopRhsInt32 arith_feedback:0, lhs:i~0, rhs:3, true_target:block1, false_target:block3
+ [ 38] JumpLessThanLoopRhsInt32 arith_feedback:1, lhs:i~0, rhs:3, true_target:block1, false_target:block3
block3:
[ 50] Mov dst:i~0, src:Int32(0)
[ 60] Jump target:block5
block4:
- [ 68] PostfixIncrement arith_feedback:3, dst:reg5, src:i~0
+ [ 68] Increment arith_feedback:2, dst:i~0
block5:
- [ 78] JumpLessThanLoopRhsInt32 arith_feedback:2, lhs:i~0, rhs:3, true_target:block4, false_target:block6
+ [ 70] JumpLessThanLoopRhsInt32 arith_feedback:3, lhs:i~0, rhs:3, true_target:block4, false_target:block6
block6:
- [ 90] End value:Undefined
+ [ 88] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/var-init-in-param-body-scope.txt b/Tests/LibJS/Bytecode/expected/var-init-in-param-body-scope.txt
index bf7f7564ca6..05c7f98989b 100644
--- a/Tests/LibJS/Bytecode/expected/var-init-in-param-body-scope.txt
+++ b/Tests/LibJS/Bytecode/expected/var-init-in-param-body-scope.txt
@@ -1,4 +1,4 @@
-$2b997e90 var-init-in-param-body-scope.js:4:1
+$28d58d80 var-init-in-param-body-scope.js:4:1
Registers: 7
Blocks: 1
Constants:
@@ -6,13 +6,14 @@ $2b997e90 var-init-in-param-body-scope.js:4:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `f`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, f
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `f`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-f$ee38e33b
- Registers: 6
+f$1f009ce6 var-init-in-param-body-scope.js:1:12
+ Registers: 5
Blocks: 3
Locals: x~0
Constants:
@@ -28,5 +29,6 @@ block1:
[ 18] Mov dst:arg0, src:Int32(1)
block2:
- [ 28] Mov3 c0_dst:reg5, c0_src:Undefined, c1_dst:x~0, c1_src:reg5, c2_dst:x~0, c2_src:String("inside")
+ [ 28] Mov dst:x~0, src:Undefined
+ [ 38] Mov dst:x~0, src:String("inside")
[ 48] End value:Undefined
diff --git a/Tests/LibJS/Bytecode/expected/var-shadow-in-default-param.txt b/Tests/LibJS/Bytecode/expected/var-shadow-in-default-param.txt
index 63a5c325ec6..e18a459b37d 100644
--- a/Tests/LibJS/Bytecode/expected/var-shadow-in-default-param.txt
+++ b/Tests/LibJS/Bytecode/expected/var-shadow-in-default-param.txt
@@ -1,23 +1,25 @@
-$db17f9c3 var-shadow-in-default-param.js:7:1
- Registers: 8
+$4dd98537 var-shadow-in-default-param.js:7:5
+ Registers: 7
Blocks: 1
Constants:
- [0] = String("outer")
- [1] = Undefined
+ [0] = Undefined
+ [1] = String("outer")
block0:
[ 0] Enter
- [ 8] SetGlobal `shadow`, src:String("outer")
- [ 18] GetGlobal value_feedback:0, dst:reg6, `shadow_in_default`
- [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, shadow_in_default
- [ 48] GetGlobal value_feedback:2, dst:reg7, `no_conflict`
- [ 58] Call value_feedback:3, call_feedback:1, dst:reg6, callee:reg7, this_value:Undefined, no_conflict
- [ 78] End value:reg6
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] SetGlobal `shadow`, src:String("outer")
+ [ 28] GetGlobal value_feedback:0, dst:reg6, `shadow_in_default`
+ [ 38] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 58] GetGlobal value_feedback:2, dst:reg6, `no_conflict`
+ [ 68] Call value_feedback:3, call_feedback:1, dst:reg5, callee:reg6, this_value:Undefined
+ [ 88] End value:reg5
-shadow_in_default$321d2e1f var-shadow-in-default-param.js:8:32
- Registers: 7
+shadow_in_default$cf39b72b var-shadow-in-default-param.js:8:28
+ Registers: 6
Blocks: 3
+ Locals: shadow~0
Constants:
[0] = Undefined
[1] = String("inner")
@@ -27,21 +29,16 @@ block0:
[ 8] JumpUndefined condition:arg0, true_target:block1, false_target:block2
block1:
- [ 18] DynamicGetInitializedBinding value_feedback:0, dst:reg5, `shadow`
- [ 28] Mov dst:arg0, src:reg5
+ [ 18] GetGlobal value_feedback:0, dst:arg0, `shadow`
block2:
- [ 38] CreateVariableEnvironment capacity:1
- [ 40] GetLexicalEnvironment dst:reg5
- [ 48] MovSrcUndefined dst:reg6
- [ 50] CreateVariable `shadow`, is_immutable:false, is_global:false, is_strict:false
- [ 60] InitializeVariableBinding `shadow`, src:reg6
- [ 78] SetLexicalBinding `shadow`, src:String("inner")
- [ 90] Return value:arg0
+ [ 28] Mov dst:shadow~0, src:Undefined
+ [ 38] Mov dst:shadow~0, src:String("inner")
+ [ 48] Return value:arg0
-no_conflict$74ebdc29 var-shadow-in-default-param.js:17:5
- Registers: 6
+no_conflict$9c1d62c4 var-shadow-in-default-param.js:15:22
+ Registers: 5
Blocks: 3
Locals: y~0
Constants:
@@ -57,5 +54,6 @@ block1:
[ 18] Mov dst:arg0, src:Int32(1)
block2:
- [ 28] Mov3 c0_dst:reg5, c0_src:Undefined, c1_dst:y~0, c1_src:reg5, c2_dst:y~0, c2_src:Int32(2)
+ [ 28] Mov dst:y~0, src:Undefined
+ [ 38] Mov dst:y~0, src:Int32(2)
[ 48] Return value:y~0
diff --git a/Tests/LibJS/Bytecode/expected/with-return.txt b/Tests/LibJS/Bytecode/expected/with-return.txt
index 1de772c6ed7..c9f18beb0ed 100644
--- a/Tests/LibJS/Bytecode/expected/with-return.txt
+++ b/Tests/LibJS/Bytecode/expected/with-return.txt
@@ -1,4 +1,4 @@
-$b237dcfe with-return.js:10:1
+$af73ebee with-return.js:10:1
Registers: 8
Blocks: 1
Constants:
@@ -7,19 +7,18 @@ $b237dcfe with-return.js:10:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `with_return`
- [ 18] NewObject dst:reg7
- [ 28] InitObjectLiteralProperty object:reg7, `x`, src:Int32(42), shape_cache_index:0, property_slot:0
- [ 40] CacheObjectShape object:reg7
- [ 50] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, with_return, arguments:[reg7]
- [ 78] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `with_return`
+ [ 28] NewObject dst:reg7
+ [ 38] InitObjectLiteralProperty object:reg7, `x`, src:Int32(42), shape_cache_index:0, property_slot:0
+ [ 50] CacheObjectShape object:reg7
+ [ 60] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, arguments:[reg7]
+ [ 88] End value:reg5
with_return$d690ef5a with-return.js:5:5
Registers: 7
Blocks: 1
- Constants:
- [0] = Undefined
block0:
[ 0] Enter
diff --git a/Tests/LibJS/Bytecode/expected/with-statement.txt b/Tests/LibJS/Bytecode/expected/with-statement.txt
index 753841b0d1c..d63eb151bbc 100644
--- a/Tests/LibJS/Bytecode/expected/with-statement.txt
+++ b/Tests/LibJS/Bytecode/expected/with-statement.txt
@@ -1,4 +1,4 @@
-$d0083583 with-statement.js:7:1
+$cd444473 with-statement.js:7:1
Registers: 7
Blocks: 1
Constants:
@@ -6,13 +6,14 @@ $d0083583 with-statement.js:7:1
block0:
[ 0] Enter
- [ 8] GetGlobal value_feedback:0, dst:reg6, `withBlock`
- [ 18] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined, withBlock
- [ 38] End value:reg5
+ [ 8] Mov dst:reg5, src:Undefined
+ [ 18] GetGlobal value_feedback:0, dst:reg6, `withBlock`
+ [ 28] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg6, this_value:Undefined
+ [ 48] End value:reg5
-withBlock$927ba86b with-statement.js:2:15
- Registers: 10
+withBlock$345aed1d with-statement.js:2:9
+ Registers: 9
Blocks: 1
Locals: obj~0
Constants:
@@ -22,16 +23,17 @@ withBlock$927ba86b with-statement.js:2:15
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
- [ 10] NewObject dst:obj~0
- [ 20] InitObjectLiteralProperty object:obj~0, `x`, src:Int32(42), shape_cache_index:0, property_slot:0
- [ 38] CacheObjectShape object:obj~0
- [ 48] EnterObjectEnvironment dst:reg5, object:obj~0
- [ 58] DynamicGetBinding value_feedback:0, dst:reg7, `console`
- [ 68] GetById value_feedback:1, dst:reg8, base:reg7, `log` (console.log)
- [ 80] DynamicGetBinding value_feedback:2, dst:reg9, `x`
- [ 90] Call value_feedback:3, call_feedback:0, dst:reg6, callee:reg8, this_value:reg7, console.log, arguments:[reg9]
- [ b8] SetLexicalEnvironment environment:reg4
- [ c0] End value:Undefined
+ [ 10] NewObject dst:reg5
+ [ 20] InitObjectLiteralProperty object:reg5, `x`, src:Int32(42), shape_cache_index:0, property_slot:0
+ [ 38] CacheObjectShape object:reg5
+ [ 48] Mov dst:obj~0, src:reg5
+ [ 58] EnterObjectEnvironment dst:reg5, object:obj~0
+ [ 68] DynamicGetBinding value_feedback:0, dst:reg6, `console`
+ [ 78] GetById value_feedback:1, dst:reg7, base:reg6, `log`
+ [ 90] DynamicGetBinding value_feedback:2, dst:reg8, `x`
+ [ a0] Call value_feedback:3, call_feedback:0, dst:reg6, callee:reg7, this_value:reg6, arguments:[reg8]
+ [ c8] SetLexicalEnvironment environment:reg4
+ [ d0] End value:Undefined
42
diff --git a/Tests/LibJS/Bytecode/input/tdz-reset-in-loop.js b/Tests/LibJS/Bytecode/input/tdz-reset-in-loop.js
new file mode 100644
index 00000000000..109131fc0a0
--- /dev/null
+++ b/Tests/LibJS/Bytecode/input/tdz-reset-in-loop.js
@@ -0,0 +1,23 @@
+// A local that a TDZ check reads is emptied at the start of each iteration of the innermost
+// loop around its scope. A local without such a check costs nothing.
+
+function checked(list) {
+ for (let i = 0; i < list.length; i++) {
+ list[i](() => 0, typeof value);
+ let value = i;
+ let plain = value + 1;
+ list[i](plain);
+ }
+}
+
+function nested(list) {
+ while (list.length) {
+ {
+ for (const item of list) item(typeof value);
+ let value = list.pop();
+ }
+ }
+}
+
+checked([]);
+nested([]);
diff --git a/Tests/LibJS/Debugger/expected/block-scopes.txt b/Tests/LibJS/Debugger/expected/block-scopes.txt
new file mode 100644
index 00000000000..a1cb540463e
--- /dev/null
+++ b/Tests/LibJS/Debugger/expected/block-scopes.txt
@@ -0,0 +1,5 @@
+Paused at <ladybird>/Tests/LibJS/Debugger/input/block-scopes.js:11:1 (entry)
+Paused at <ladybird>/Tests/LibJS/Debugger/input/block-scopes.js:5:9 (debugger statement)
+2
+Paused at <ladybird>/Tests/LibJS/Debugger/input/block-scopes.js:7:5 (debugger statement)
+1
diff --git a/Tests/LibJS/Debugger/expected/stepping.txt b/Tests/LibJS/Debugger/expected/stepping.txt
index 3407c7c51d9..6b402916e9e 100644
--- a/Tests/LibJS/Debugger/expected/stepping.txt
+++ b/Tests/LibJS/Debugger/expected/stepping.txt
@@ -1,10 +1,10 @@
Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:7:1 (entry)
-Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:2:5 (step)
-Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:4:18 (step)
+Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:2:9 (step)
+Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:3:9 (step)
Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:8:1 (step)
-Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:2:5 (step)
-Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:4:18 (step)
+Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:2:9 (step)
+Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:3:9 (step)
Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:9:1 (step)
-Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:2:5 (step)
-Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:4:18 (step)
+Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:2:9 (step)
+Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:3:9 (step)
Paused at <ladybird>/Tests/LibJS/Debugger/input/stepping.js:10:1 (step)
diff --git a/Tests/LibJS/Debugger/input/block-scopes.commands b/Tests/LibJS/Debugger/input/block-scopes.commands
new file mode 100644
index 00000000000..fbdddc45314
--- /dev/null
+++ b/Tests/LibJS/Debugger/input/block-scopes.commands
@@ -0,0 +1,5 @@
+c
+p value
+c
+p value
+c
diff --git a/Tests/LibJS/Debugger/input/block-scopes.js b/Tests/LibJS/Debugger/input/block-scopes.js
new file mode 100644
index 00000000000..fc64c47310f
--- /dev/null
+++ b/Tests/LibJS/Debugger/input/block-scopes.js
@@ -0,0 +1,11 @@
+function shadowed() {
+ let value = 1;
+ {
+ let value = 2;
+ debugger;
+ }
+ debugger;
+ return value;
+}
+
+shadowed();
diff --git a/Tests/LibJS/JIT/ir/async-functions.js b/Tests/LibJS/JIT/ir/async-functions.js
index 93a783898c5..41e6176781f 100644
--- a/Tests/LibJS/JIT/ir/async-functions.js
+++ b/Tests/LibJS/JIT/ir/async-functions.js
@@ -15,10 +15,10 @@ for (let i = 0; i < 10; ++i) warm_up.push(sum([1, 2, 3]));
// CHECK-FUNCTION: sum
// CHECK-PASS: graph building
-// CHECK: LoadSlot r5
-// CHECK-NEXT: LoadSlot r6
+// CHECK: LoadSlot r6
// CHECK-NEXT: LoadSlot r7
-// CHECK-NEXT: LoadSlot r12
+// CHECK-NEXT: LoadSlot r8
+// CHECK-NEXT: LoadSlot l0
// CHECK-NEXT: Jump [[CONTINUATION:b[0-9]+]]
// CHECK: InitializeFrame
// CHECK-NOT: Suspend
diff --git a/Tests/LibJS/JIT/ir/exit-unboxing.js b/Tests/LibJS/JIT/ir/exit-unboxing.js
index d330d17dee4..d6326c61faf 100644
--- a/Tests/LibJS/JIT/ir/exit-unboxing.js
+++ b/Tests/LibJS/JIT/ir/exit-unboxing.js
@@ -4,7 +4,10 @@
function sumElements(array, n) {
let sum = 0;
- for (let i = 0; i < n; ++i) sum += array[i];
+ for (let i = 0; i < n; ++i) {
+ const next = sum + array[i];
+ sum = next;
+ }
return sum;
}
jit.prepare(sumElements);
@@ -15,9 +18,9 @@ jit.compile(sumElements);
// CHECK-PASS: loop invariant code motion
// CHECK: [[SUM:v[0-9]+]]:int32 = Int32Add
// CHECK-NEXT: [[BOXED:v[0-9]+]] = BoxInt32 ([[SUM]])
-// CHECK: at {l0={{v[0-9]+}}, l1=[[BOXED]]}
+// CHECK: at {l0=[[BOXED]], l1={{v[0-9]+}}}
// CHECK-PASS: exit unboxing
-// CHECK: at {l0={{v[0-9]+}}, l1=[[SUM]]}
+// CHECK: at {l0=[[SUM]], l1={{v[0-9]+}}}
// CHECK-PASS: dead code elimination
// CHECK-NOT: = BoxInt32 ([[SUM]])
// CHECK: frame states:
diff --git a/Tests/LibJS/JIT/ir/math-and-string-builtins.js b/Tests/LibJS/JIT/ir/math-and-string-builtins.js
index 5fecd1e3ada..e5d2cb089ff 100644
--- a/Tests/LibJS/JIT/ir/math-and-string-builtins.js
+++ b/Tests/LibJS/JIT/ir/math-and-string-builtins.js
@@ -14,7 +14,8 @@ jit.compile(floorPlusAbs);
// CHECK-FUNCTION: floorPlusAbs
// CHECK-PASS: graph building
// CHECK: CheckValue {{0x[0-9a-f]+}} ({{v[0-9]+}})
-// CHECK-NEXT: BranchInt32Value ([[X:v[0-9]+]]) -> [[INT32:b[0-9]+]], [[OTHER:b[0-9]+]]
+// CHECK-NEXT: [[X:v[0-9]+]] = LoadSlot a0
+// CHECK-NEXT: BranchInt32Value ([[X]]) -> [[INT32:b[0-9]+]], [[OTHER:b[0-9]+]]
// CHECK: [[INT32]] <- {{b[0-9]+}}:
// CHECK-NEXT: [[INTEGER:v[0-9]+]] = RefineInt32Value ([[X]])
// CHECK-NEXT: UnboxInt32 ([[INTEGER]])
diff --git a/Tests/LibJS/JIT/ir/number-operators.js b/Tests/LibJS/JIT/ir/number-operators.js
index d5ede9a601c..40ac4350140 100644
--- a/Tests/LibJS/JIT/ir/number-operators.js
+++ b/Tests/LibJS/JIT/ir/number-operators.js
@@ -136,14 +136,33 @@ recompileAfterExit(count, notANumber);
// CHECK-FUNCTION: count
// CHECK-PASS: dead code elimination
// CHECK: Int32Add ({{v[0-9]+}}, #i32:1)
-// CHECK: CallSlowPath PostfixIncrement
-// CHECK-NEXT: SlowPathOutput 1
+// CHECK: CallSlowPath Increment
// CHECK: Float64Add ({{v[0-9]+}}, #0x3ff0000000000000)
// CHECK: [[COUNT:v[0-9]+]] = Phi ({{v[0-9]+}}, {{v[0-9]+}}, {{v[0-9]+}})
// CHECK-NEXT: [[NUMBER:v[0-9]+]]:float64 = CheckNumber ([[COUNT]])
// CHECK-NOT: CallSlowPath LessThan
// CHECK: Float64LessThan ([[NUMBER]], #0x4025000000000000)
+// An update whose old value stays in use gets both values out of its slow path.
+
+function countAndKeep(x) {
+ let n = x;
+ const before = n++;
+ return n + before;
+}
+jit.prepare(countAndKeep);
+for (let i = 0; i < 10; ++i) {
+ countAndKeep(i);
+ countAndKeep(i + 0.25);
+}
+recompileAfterExit(countAndKeep, notANumber);
+
+// CHECK-FUNCTION: countAndKeep
+// CHECK-PASS: dead code elimination
+// CHECK: Int32Add ({{v[0-9]+}}, #i32:1)
+// CHECK: CallSlowPath PostfixIncrement
+// CHECK-NEXT: SlowPathOutput 1
+
// Divisions of int32 values make numbers that are rarely int32 values, so a
// division whose feedback only saw int32 operands checks that they are numbers
// too, and exits for other operands.
diff --git a/Tests/LibJS/JIT/ir/osr-update-step.js b/Tests/LibJS/JIT/ir/osr-update-step.js
index a4854a40631..dc36df3d0ae 100644
--- a/Tests/LibJS/JIT/ir/osr-update-step.js
+++ b/Tests/LibJS/JIT/ir/osr-update-step.js
@@ -1,8 +1,7 @@
// OPTIONS: stress-osr
-// Loops with a continue have their update step in a block of its own, which the back edges jump to and which leads
-// to the loop header. On-stack replacement entries there run the update step themselves and jump to the loop header,
-// so that the loop has one header and loop invariant code motion can hoist the loads of the loop bound and of the
-// object's property.
+// A continue reaches the update step of a loop going forward, like the end of the body, so that the loop has one back
+// edge and one on-stack replacement entry, at its test. That gives it one header, and loop invariant code motion can
+// hoist the loads of the loop bound and of the object's property.
function sumOf(object, n) {
let sum = 0;
@@ -22,13 +21,11 @@ jit.compile(sumOf);
// CHECK: b0:
// CHECK: LoadSlot a1
// CHECK-NEXT: Jump [[HEADER:b[0-9]+]]
+// CHECK: [[HEADER]] (pc {{[0-9]+}}) <- {{b[0-9]+}}, {{b[0-9]+}}, {{b[0-9]+}} loop:
// CHECK: Int32Add ({{v[0-9]+}}, #i32:1)
// CHECK-NEXT: BoxInt32
// CHECK-NEXT: Jump [[HEADER]]
-// CHECK: Int32Add ({{v[0-9]+}}, #i32:1)
-// CHECK-NEXT: BoxInt32
-// CHECK-NEXT: Jump [[HEADER]]
-// CHECK: [[HEADER]] (pc {{[0-9]+}}) <- {{b[0-9]+}}, {{b[0-9]+}}, {{b[0-9]+}}, {{b[0-9]+}}, {{b[0-9]+}} loop:
+// CHECK-COUNT-1: osr entry at pc
// CHECK-PASS: loop invariant code motion
// CHECK: CheckShape
// CHECK-NEXT: CellAddress
@@ -38,3 +35,36 @@ jit.compile(sumOf);
// CHECK: osr entry at pc
console.log(sumOf({ x: 3 }, 5));
+
+// A loop whose test is a constant ends in a back edge that jumps to the start of the body. A body of one block leads
+// to the test, which is the loop's header, so the on-stack replacement entry at that back edge runs the body itself
+// and continues at the header, and the loop stays reducible.
+
+function stopAt(i, n) {
+ if (i === n) throw 0;
+}
+function spin(object, n) {
+ let sum = 0;
+ try {
+ for (let i = 0; true; ++i) {
+ sum = (sum + object.x) | 0;
+ stopAt(i, n);
+ }
+ } catch {
+ return sum;
+ }
+}
+jit.prepare(spin);
+for (let i = 0; i < 10; ++i) spin({ x: i }, 5);
+jit.compile(spin);
+
+// CHECK-FUNCTION: spin
+// CHECK-PASS: graph building
+// CHECK: b1:
+// CHECK: LoadNamed
+// CHECK: Int32Add ({{v[0-9]+}}, #i32:1)
+// CHECK-NEXT: BoxInt32
+// CHECK-NEXT: Jump [[SPIN_HEADER:b[0-9]+]]
+// CHECK: [[SPIN_HEADER]] (pc {{[0-9]+}}) <- {{b[0-9]+}}, {{b[0-9]+}}, {{b[0-9]+}} loop:
+
+console.log(spin({ x: 3 }, 5));
diff --git a/Tests/LibJS/JIT/ir/representation-checked-entries.js b/Tests/LibJS/JIT/ir/representation-checked-entries.js
index 320a4bbbe37..6ed3f31da01 100644
--- a/Tests/LibJS/JIT/ir/representation-checked-entries.js
+++ b/Tests/LibJS/JIT/ir/representation-checked-entries.js
@@ -21,7 +21,7 @@ jit.compile(addOnOddIterations);
// CHECK: CheckInt32
// CHECK-PASS: representation selection
// CHECK: loop:
-// CHECK-NEXT: :int32 = Phi
// CHECK-NEXT: [[STEP:v[0-9]+]]:int32 = Phi
+// CHECK-NEXT: :int32 = Phi
// CHECK: Int32WrappingAdd ({{v[0-9]+}}, [[STEP]])
// CHECK: osr entry at pc
diff --git a/Tests/LibJS/JIT/ir/representation-int32-loop.js b/Tests/LibJS/JIT/ir/representation-int32-loop.js
index f3b59421dcb..d80a83f3db6 100644
--- a/Tests/LibJS/JIT/ir/representation-int32-loop.js
+++ b/Tests/LibJS/JIT/ir/representation-int32-loop.js
@@ -12,8 +12,8 @@ jit.compile(count);
// CHECK-FUNCTION: count
// CHECK-PASS: frame initialization
// CHECK: loop:
-// CHECK-NEXT: [[I:v[0-9]+]]:int32 = Phi (#i32:0, [[NEXT:v[0-9]+]])
// CHECK-NEXT: [[SUM:v[0-9]+]]:int32 = Phi (#i32:0, {{v[0-9]+}})
+// CHECK-NEXT: [[I:v[0-9]+]]:int32 = Phi (#i32:0, [[NEXT:v[0-9]+]])
// CHECK: BranchInt32LessThan ([[I]],
// CHECK: Int32WrappingAdd ([[SUM]], [[I]])
// CHECK: [[NEXT]]:int32 = Int32Add ([[I]], #i32:1)
diff --git a/Tests/LibJS/JIT/ir/representation-phis.js b/Tests/LibJS/JIT/ir/representation-phis.js
index c2b3c62e312..8ec76b792bb 100644
--- a/Tests/LibJS/JIT/ir/representation-phis.js
+++ b/Tests/LibJS/JIT/ir/representation-phis.js
@@ -92,6 +92,7 @@ jit.compile(addActions);
// CHECK-NOT: BoxFloat64
// CHECK: [[START:v[0-9]+]]:int32 = CheckFloat64Int32 ([[ELEMENT]])
// CHECK: loop:
+// CHECK-NEXT: :int32 = Phi
// CHECK-NEXT: [[I:v[0-9]+]]:int32 = Phi ([[START]], {{v[0-9]+}})
// CHECK-NOT: CheckInt32 ({{v[0-9]+}})
// CHECK: CheckBounds ([[I]], {{[^)]+}})
diff --git a/Tests/LibJS/Runtime/arguments-object.js b/Tests/LibJS/Runtime/arguments-object.js
index 9e33e0a9294..20987e5e42c 100644
--- a/Tests/LibJS/Runtime/arguments-object.js
+++ b/Tests/LibJS/Runtime/arguments-object.js
@@ -184,3 +184,148 @@ test("block-level function named arguments with arguments object reached through
}
expect(g(1, 2)).toEqual([2, "function"]);
});
+
+test("var named arguments shares the binding of the arguments object", () => {
+ function capturedBeforeDeclaration() {
+ const length = (() => arguments.length)();
+ var arguments;
+ return [length, arguments.length];
+ }
+ expect(capturedBeforeDeclaration(1, 2)).toEqual([2, 2]);
+
+ function capturedAfterDeclaration() {
+ var arguments;
+ return (() => arguments.length)();
+ }
+ expect(capturedAfterDeclaration(1, 2)).toBe(2);
+
+ function assignedThroughArrowFunction() {
+ var arguments;
+ const assign = () => {
+ arguments = "assigned";
+ };
+ assign();
+ return arguments;
+ }
+ expect(assignedThroughArrowFunction()).toBe("assigned");
+
+ function capturedFunctionDeclaration() {
+ const type = (() => typeof arguments)();
+ function arguments() {}
+ return type;
+ }
+ expect(capturedFunctionDeclaration()).toBe("function");
+
+ function capturedBlockFunction() {
+ const before = (() => typeof arguments)();
+ {
+ function arguments() {}
+ }
+ return [before, typeof arguments];
+ }
+ expect(capturedBlockFunction()).toEqual(["object", "function"]);
+
+ function blockFunctionWithParameterExpression(first = 1) {
+ const before = (() => typeof arguments)();
+ {
+ function arguments() {}
+ }
+ return [before, typeof arguments];
+ }
+ expect(blockFunctionWithParameterExpression()).toEqual(["object", "function"]);
+
+ function laterBindingsKeepTheirPlaces() {
+ var arguments;
+ var first = 1;
+ var second = 2;
+ const read = () => [first, second];
+ first++;
+ return read();
+ }
+ expect(laterBindingsKeepTheirPlaces()).toEqual([2, 2]);
+});
+
+test("lexical declaration named arguments takes the place of the arguments object", () => {
+ function captured() {
+ const before = (() => {
+ try {
+ return arguments;
+ } catch (error) {
+ return error.name;
+ }
+ })();
+ let arguments = 1;
+ return [before, arguments];
+ }
+ expect(captured(1)).toEqual(["ReferenceError", 1]);
+
+ function reachedThroughDirectEval() {
+ const before = (() => {
+ try {
+ return eval("typeof arguments");
+ } catch (error) {
+ return error.name;
+ }
+ })();
+ let arguments = 1;
+ return [before, (() => arguments)()];
+ }
+ expect(reachedThroughDirectEval()).toEqual(["ReferenceError", 1]);
+
+ function laterBindingsStayDeclared() {
+ const before = (() => {
+ try {
+ return arguments;
+ } catch (error) {
+ return error.name;
+ }
+ })();
+ let arguments = 1;
+ var other = 2;
+ const read = () => other;
+ return [before, read()];
+ }
+ expect(laterBindingsStayDeclared()).toEqual(["ReferenceError", 2]);
+});
+
+test("mapped arguments object in the strict code of a class", () => {
+ function computedKey(first) {
+ class C {
+ [arguments[0]]() {}
+ }
+ return Object.getOwnPropertyNames(C.prototype);
+ }
+
+ function heritage(first) {
+ const C = class extends arguments[0] {};
+ return Object.getPrototypeOf(C) === first;
+ }
+
+ function assignment(first) {
+ class C {
+ [(arguments[0] = "assigned")]() {}
+ }
+ return first;
+ }
+
+ function arrowInKey(first) {
+ class C {
+ [(() => arguments[0])()]() {}
+ }
+ return Object.getOwnPropertyNames(C.prototype);
+ }
+
+ function withEnvironment(first) {
+ const capture = () => this;
+ class C {
+ [arguments[0]]() {}
+ }
+ return Object.getOwnPropertyNames(C.prototype);
+ }
+
+ expect(computedKey("key")).toEqual(["constructor", "key"]);
+ expect(heritage(Object)).toBeTrue();
+ expect(assignment("original")).toBe("assigned");
+ expect(arrowInKey("key")).toEqual(["constructor", "key"]);
+ expect(withEnvironment("key")).toEqual(["constructor", "key"]);
+});
diff --git a/Tests/LibJS/Runtime/builtins/Function/Function.js b/Tests/LibJS/Runtime/builtins/Function/Function.js
index 1d54e3bcac2..bd459e9d54c 100644
--- a/Tests/LibJS/Runtime/builtins/Function/Function.js
+++ b/Tests/LibJS/Runtime/builtins/Function/Function.js
@@ -53,9 +53,9 @@ describe("errors", () => {
// Since the body, surrounded by a newline on each side, is first parsed standalone,
// we report unexpected token EOF instead of }.
// FIXME: The position is odd though, I'd expect `line: 2, column: 2` and `line: 3, column: 1`...
- // > eval("\n[") // Uncaught exception: [SyntaxError] Unexpected token Eof. Expected BracketClose (line: 2, column: 2)
- // > eval("\n[\n") // Uncaught exception: [SyntaxError] Unexpected token Eof. Expected BracketClose (line: 2, column: 3)
- .toThrowWithMessage(SyntaxError, "Unexpected token Eof. Expected BracketClose (line: 2, column: 3)");
+ // > eval("\n[") // Uncaught exception: [SyntaxError] Unexpected end of input. Expected ']' (line: 2, column: 2)
+ // > eval("\n[\n") // Uncaught exception: [SyntaxError] Unexpected end of input. Expected ']' (line: 2, column: 3)
+ .toThrowWithMessage(SyntaxError, "Unexpected end of input. Expected ']' (line: 2, column: 3)");
});
test("parameters and body must be valid standalone", () => {
diff --git a/Tests/LibJS/Runtime/classes/class-default-derived-constructor-without-arguments.js b/Tests/LibJS/Runtime/classes/class-default-derived-constructor-without-arguments.js
new file mode 100644
index 00000000000..931c7fee694
--- /dev/null
+++ b/Tests/LibJS/Runtime/classes/class-default-derived-constructor-without-arguments.js
@@ -0,0 +1,24 @@
+test("a default derived constructor called without arguments in a hot loop", () => {
+ class Base {
+ constructor(...args) {
+ this.count = args.length;
+ }
+ }
+ class Derived extends Base {}
+ let total = 0;
+ for (let i = 0; i < 20000; ++i) {
+ total += new Derived().count;
+ }
+ expect(total).toBe(0);
+ expect(new Derived(1, 2).count).toBe(2);
+});
+
+test("a default derived constructor of a builtin called without arguments in a hot loop", () => {
+ class Derived extends Uint8Array {}
+ let total = 0;
+ for (let i = 0; i < 20000; ++i) {
+ total += new Derived().length;
+ }
+ expect(total).toBe(0);
+ expect(new Derived(3).length).toBe(3);
+});
diff --git a/Tests/LibJS/Runtime/classes/class-field-closures-in-functions.js b/Tests/LibJS/Runtime/classes/class-field-closures-in-functions.js
new file mode 100644
index 00000000000..412ac825b60
--- /dev/null
+++ b/Tests/LibJS/Runtime/classes/class-field-closures-in-functions.js
@@ -0,0 +1,34 @@
+test("a closure in a field captures a local of a function with a using declaration", () => {
+ function run() {
+ using resource = null;
+ let base = 1;
+ class C {
+ static fromField = base + 1;
+ field = () => base + C.fromField;
+ static {
+ this.fromBlock = () => base;
+ }
+ }
+ base = 10;
+ return [new C().field(), C.fromBlock()];
+ }
+ expect(run()).toEqual([12, 10]);
+});
+
+test("a closure nested deeper in a field captures a local as well", () => {
+ function run() {
+ using resource = null;
+ const value = 1;
+ class C {
+ field = () => () => {
+ try {
+ value++;
+ } catch {
+ return value;
+ }
+ };
+ }
+ return new C().field()();
+ }
+ expect(run()).toBe(1);
+});
diff --git a/Tests/LibJS/Runtime/closures-before-later-declarations.js b/Tests/LibJS/Runtime/closures-before-later-declarations.js
new file mode 100644
index 00000000000..57210461c25
--- /dev/null
+++ b/Tests/LibJS/Runtime/closures-before-later-declarations.js
@@ -0,0 +1,89 @@
+test("closures in blocks see what gets declared after them", () => {
+ function outer() {
+ let first = 1;
+ const closures = [];
+ {
+ let inner = 2;
+ closures.push(() => first + inner + second);
+ }
+ let second = 3;
+ {
+ let inner = 4;
+ closures.push(() => first + inner + second);
+ }
+ let third = 5;
+ {
+ let inner = 6;
+ closures.push(() => first + inner + second + third);
+ }
+ return closures;
+ }
+
+ expect(outer().map(closure => closure())).toEqual([6, 8, 15]);
+});
+
+test("a closure that runs before a later declaration finds it in its dead zone", () => {
+ function outer() {
+ let closure;
+ {
+ let inner = 1;
+ closure = () => inner + later;
+ }
+ expect(closure).toThrow(ReferenceError);
+ let later = 2;
+ return closure();
+ }
+
+ expect(outer()).toBe(3);
+});
+
+test("a later declaration shadows a global for closures made before it", () => {
+ globalThis.declaredLaterInFunction = "global";
+ function outer() {
+ let closure;
+ {
+ let inner = 1;
+ closure = () => [inner, declaredLaterInFunction];
+ }
+ let declaredLaterInFunction = "local";
+ return closure();
+ }
+
+ expect(outer()).toEqual([1, "local"]);
+ delete globalThis.declaredLaterInFunction;
+});
+
+test("closures made between declarations of nested scopes keep their coordinates", () => {
+ function outer() {
+ const closures = [];
+ let a = "a";
+ {
+ let b = "b";
+ closures.push(() => a + b);
+ {
+ let c = "c";
+ closures.push(() => a + b + c + d);
+ }
+ let d = "d";
+ closures.push(() => a + b + d + e);
+ }
+ let e = "e";
+ return closures;
+ }
+
+ expect(outer().map(closure => closure())).toEqual(["ab", "abcd", "abde"]);
+});
+
+test("direct eval in a closure sees bindings declared after the closure", () => {
+ function outer() {
+ let closure;
+ {
+ let inner = 1;
+ closure = code => eval(code);
+ }
+ let later = 2;
+ return closure("inner + later");
+ }
+
+ expect(outer()).toBe(3);
+});
diff --git a/Tests/LibJS/Runtime/completion-values.js b/Tests/LibJS/Runtime/completion-values.js
new file mode 100644
index 00000000000..ba9004cdf3e
--- /dev/null
+++ b/Tests/LibJS/Runtime/completion-values.js
@@ -0,0 +1,34 @@
+const cases = [
+ ["1;", 1],
+ ["1; var a = 2", 1],
+ ["1; if (true) {}", undefined],
+ ["1; if (false) {}", undefined],
+ ["1; if (false) {} else { 3 }", 3],
+ ["1; while (false);", undefined],
+ ["1; do { 2 } while (false)", 2],
+ ["1; do { 2; if (1) { break } } while (false)", undefined],
+ ["1; do { 2; { break } } while (false)", 2],
+ ["1; for (var i = 0; i < 2; i++) { i }", 1],
+ ["1; for (var k of []) { k }", undefined],
+ ["1; l: { 2; { break l; 3 } }", 2],
+ ["1; switch (1) {}", undefined],
+ ["1; switch (2) { default: 2; case 1: 3 }", 3],
+ ["1; try { 2 } catch (e) {}", 2],
+ ["1; try { throw 2 } catch (e) {}", undefined],
+ ["1; try { 2 } finally { 3 }", 2],
+ ["do { 1; try { 2; break } finally { 3 } } while (0)", 2],
+ ["do { 1; try { 2 } finally { 3; break } } while (0)", 3],
+ ["do { 1; try { 2 } finally { break } } while (0)", undefined],
+ ["1; with ({}) {}", undefined],
+ ["1; with ({}) { 2 }", 2],
+ ["1; { let a = 1 }", 1],
+ ["1; class C {}", 1],
+ ["{ let a = 1; a; let b = (a = 9); }", 1],
+];
+
+test("the value of statements in eval code", () => {
+ for (const [source, value] of cases) {
+ expect(eval(source)).toBe(value);
+ expect((0, eval)(source)).toBe(value);
+ }
+});
diff --git a/Tests/LibJS/Runtime/const-reassignment.js b/Tests/LibJS/Runtime/const-reassignment.js
index 7313b9ddf83..4886a7bb69d 100644
--- a/Tests/LibJS/Runtime/const-reassignment.js
+++ b/Tests/LibJS/Runtime/const-reassignment.js
@@ -86,6 +86,25 @@ test("update expression on const keeps its value", () => {
expect(localConstant()).toBe(1);
});
+test("a single update expression on const keeps its value", () => {
+ function prefix() {
+ const value = 1;
+ try {
+ ++value;
+ } catch {}
+ return value;
+ }
+ function postfix() {
+ const value = "1";
+ try {
+ value--;
+ } catch {}
+ return value;
+ }
+ expect(prefix()).toBe(1);
+ expect(postfix()).toBe("1");
+});
+
test("const creation in inner scope", () => {
const constantValue = 1;
do {
@@ -110,3 +129,36 @@ test("reassignment to destructured const in function", () => {
})();
}).toThrowWithMessage(TypeError, "Invalid assignment to const variable");
});
+
+test("updates of a const run valueOf and leave the value as it is", () => {
+ let valueOfCount = 0;
+ const object = {
+ valueOf() {
+ ++valueOfCount;
+ return 1;
+ },
+ };
+ function postfix(value) {
+ const constant = value;
+ constant++;
+ }
+ function prefix(value) {
+ const constant = value;
+ --constant;
+ }
+ expect(() => postfix(object)).toThrowWithMessage(TypeError, "Invalid assignment to const variable");
+ expect(() => prefix(object)).toThrowWithMessage(TypeError, "Invalid assignment to const variable");
+ expect(valueOfCount).toBe(2);
+
+ function keepsValue() {
+ const constant = Math.abs(1);
+ try {
+ constant++;
+ } catch {}
+ try {
+ --constant;
+ } catch {}
+ return constant;
+ }
+ expect(keepsValue()).toBe(1);
+});
diff --git a/Tests/LibJS/Runtime/destructuring-assignment-with-expression-defaults.js b/Tests/LibJS/Runtime/destructuring-assignment-with-expression-defaults.js
index 0e2ca52e002..d97023f6c86 100644
--- a/Tests/LibJS/Runtime/destructuring-assignment-with-expression-defaults.js
+++ b/Tests/LibJS/Runtime/destructuring-assignment-with-expression-defaults.js
@@ -188,3 +188,8 @@ test("array destructuring default value does not leak class name", () => {
[x = class C {}] = [undefined];
expect(() => C).toThrowWithMessage(ReferenceError, "'C' is not defined");
});
+
+test("parenthesized targets with defaults", () => {
+ expect(new Function("var target; [(target) = 5] = [1]; return target;")()).toBe(1);
+ expect(new Function("var target; [(target) = 5] = []; return target;")()).toBe(5);
+});
diff --git a/Tests/LibJS/Runtime/eval-basic.js b/Tests/LibJS/Runtime/eval-basic.js
index da81b90dcd2..f1bf8afdbc6 100644
--- a/Tests/LibJS/Runtime/eval-basic.js
+++ b/Tests/LibJS/Runtime/eval-basic.js
@@ -63,7 +63,7 @@ test("completion value of a try statement whose catch clause runs", () => {
test("syntax error", () => {
expect(() => {
eval("{");
- }).toThrowWithMessage(SyntaxError, "Unexpected token Eof. Expected CurlyClose (line: 1, column: 2)");
+ }).toThrowWithMessage(SyntaxError, "Unexpected end of input. Expected '}' (line: 1, column: 2)");
});
test("returns 1st argument unless 1st argument is a string", () => {
@@ -128,10 +128,10 @@ test("indirect eval with syntax error can be called multiple times", function ()
}
expect(f).toThrowWithMessage(
SyntaxError,
- "Unexpected token Invalid. Expected statement or declaration (line: 1, column: 1)"
+ "Unexpected token '@'. Expected statement or declaration (line: 1, column: 1)"
);
expect(f).toThrowWithMessage(
SyntaxError,
- "Unexpected token Invalid. Expected statement or declaration (line: 1, column: 1)"
+ "Unexpected token '@'. Expected statement or declaration (line: 1, column: 1)"
);
});
diff --git a/Tests/LibJS/Runtime/functions-parameter-scope.js b/Tests/LibJS/Runtime/functions-parameter-scope.js
new file mode 100644
index 00000000000..bf6de119923
--- /dev/null
+++ b/Tests/LibJS/Runtime/functions-parameter-scope.js
@@ -0,0 +1,118 @@
+var outer = "outer";
+
+test("a function in the parameters does not see the bindings of the body", () => {
+ function f(a = () => outer) {
+ var outer = 1;
+ const read = () => outer;
+ return [a(), read()];
+ }
+ expect(f()).toEqual(["outer", 1]);
+
+ function g(a = () => outer) {
+ function outer() {}
+ return [a(), typeof outer];
+ }
+ expect(g()).toEqual(["outer", "function"]);
+
+ function h(a = () => outer) {
+ let outer = 1;
+ const read = () => outer;
+ return [a(), read()];
+ }
+ expect(h()).toEqual(["outer", 1]);
+});
+
+test("a var of the name of a parameter starts with its value and is a binding of its own", () => {
+ function f(x, read = () => x) {
+ var x;
+ const before = x;
+ x = 2;
+ return [before, read(), x];
+ }
+ expect(f(1)).toEqual([1, 1, 2]);
+
+ function g(x, write = () => (x = 7)) {
+ var x;
+ write();
+ return x;
+ }
+ expect(g(1)).toBe(1);
+
+ function h(x = 1) {
+ var x;
+ const read = () => x;
+ x = 2;
+ return read();
+ }
+ expect(h()).toBe(2);
+
+ function i(x, read = () => x) {
+ try {
+ throw 1;
+ } catch (x) {
+ var x = 6;
+ }
+ return [read(), x];
+ }
+ expect(i(1)).toEqual([1, 1]);
+});
+
+test("a function declaration of the name of a parameter", () => {
+ function f(a, b = a) {
+ function a() {}
+ return [typeof a, typeof b];
+ }
+ expect(f(1)).toEqual(["function", "number"]);
+
+ function g(a, b = () => a) {
+ function a() {}
+ return [typeof a, typeof b()];
+ }
+ expect(g(1)).toEqual(["function", "number"]);
+});
+
+test("a var called arguments", () => {
+ function f(a = () => arguments) {
+ var arguments;
+ return [typeof arguments, a() === arguments];
+ }
+ expect(f()).toEqual(["object", true]);
+
+ function g(a = () => arguments) {
+ var arguments = 5;
+ return [arguments, typeof a()];
+ }
+ expect(g()).toEqual([5, "object"]);
+});
+
+test("generators and async functions", () => {
+ function* f(x, read = () => x) {
+ var x = 2;
+ yield [read(), x];
+ }
+ expect(f(1).next().value).toEqual([1, 2]);
+});
+
+test("a binding of the body that closures capture, seen from a loop of the body", () => {
+ function f(read = () => captured) {
+ var captured = 1;
+ var last;
+ for (var i = 0; i < 2; i++) {
+ let copy = i;
+ last = () => [copy, captured];
+ }
+ return last();
+ }
+ expect(f()).toEqual([1, 1]);
+});
+
+test("a function in a block does not get hoisted to a parameter of the same name", () => {
+ function f(g = 123) {
+ const before = g;
+ {
+ function g() {}
+ }
+ return [before, g];
+ }
+ expect(f()).toEqual([123, 123]);
+});
diff --git a/Tests/LibJS/Runtime/functions-with-direct-eval.js b/Tests/LibJS/Runtime/functions-with-direct-eval.js
new file mode 100644
index 00000000000..a055fc77406
--- /dev/null
+++ b/Tests/LibJS/Runtime/functions-with-direct-eval.js
@@ -0,0 +1,75 @@
+test("a var from eval in a function with parameter expressions is apart from the parameters", () => {
+ function f(a = 1) {
+ eval("var a = 2");
+ return a;
+ }
+ expect(f()).toBe(2);
+
+ function g({ a = 1 }) {
+ eval("var a = 2");
+ return a;
+ }
+ expect(g({})).toBe(2);
+});
+
+test("a var from eval clashes with a let of the function", () => {
+ function f() {
+ let x = 1;
+ eval("var x = 2");
+ }
+ expect(f).toThrow(SyntaxError);
+});
+
+test("a var from eval gets in the way of the name for nested functions", () => {
+ function f() {
+ function read() {
+ return addedByEval;
+ }
+ eval("var addedByEval = 2");
+ return read();
+ }
+ expect(f()).toBe(2);
+});
+
+test("eval in a parenthesis is direct", () => {
+ function f() {
+ const local = 1;
+ return eval("local");
+ }
+ expect(f()).toBe(1);
+});
+
+test("duplicate parameters that eval can see", () => {
+ function f(a, a) {
+ return eval("a");
+ }
+ expect(f(1, 2)).toBe(2);
+
+ function g(a, a, b) {
+ return () => b;
+ }
+ expect(g(1, 2, 3)()).toBe(3);
+});
+
+test("arguments and block functions of that name", () => {
+ function f(a) {
+ arguments[0] = 9;
+ return eval("a");
+ }
+ expect(f(1)).toBe(9);
+
+ function g() {
+ return (() => eval("arguments.length"))();
+ }
+ expect(g(1, 2)).toBe(2);
+});
+
+test("a var from eval next to a let of the function, in calls with different names", () => {
+ function f(source) {
+ let result;
+ result = eval(source);
+ return result;
+ }
+ expect(f("var a = 1; a")).toBe(1);
+ expect(f("var b = 2; b")).toBe(2);
+});
diff --git a/Tests/LibJS/Runtime/functions-with-rare-constructs.js b/Tests/LibJS/Runtime/functions-with-rare-constructs.js
new file mode 100644
index 00000000000..4b1cb8a80d7
--- /dev/null
+++ b/Tests/LibJS/Runtime/functions-with-rare-constructs.js
@@ -0,0 +1,219 @@
+class Base {
+ method() {
+ return 1;
+ }
+}
+
+class Derived extends Base {
+ #field = 1;
+
+ #method() {
+ return this;
+ }
+
+ deleteOfSuper() {
+ return delete super.method;
+ }
+
+ deleteOfSuperWithKey(key) {
+ return delete super[key()];
+ }
+
+ readOptionally(object) {
+ return object?.#field;
+ }
+
+ callOptionally(object) {
+ return object?.#method();
+ }
+
+ callInParentheses(object) {
+ return (object?.#method)();
+ }
+
+ assignToSuperInPatterns() {
+ [super.a] = [1];
+ ({ b: super["b"] } = { b: 2 });
+ return [this.a, this.b];
+ }
+
+ assignToPrivateInPattern() {
+ [this.#field] = [5];
+ return this.#field;
+ }
+
+ loopOverSuperAndPrivate() {
+ for (super.c of [1, 2]);
+ for (super["d"] in { key: 1 });
+ for (this.#field of [7]);
+ return [this.c, this.d, this.#field];
+ }
+}
+
+test("delete of a property of super throws after evaluating the key", () => {
+ expect(() => new Derived().deleteOfSuper()).toThrowWithMessage(
+ ReferenceError,
+ "Can't delete a property on 'super'"
+ );
+ let evaluated = false;
+ expect(() =>
+ new Derived().deleteOfSuperWithKey(() => {
+ evaluated = true;
+ return "method";
+ })
+ ).toThrow(ReferenceError);
+ expect(evaluated).toBeTrue();
+});
+
+test("private names in optional chains", () => {
+ const object = new Derived();
+ expect(object.readOptionally(object)).toBe(1);
+ expect(object.readOptionally(null)).toBeUndefined();
+ expect(object.callOptionally(object)).toBe(object);
+ expect(object.callOptionally(undefined)).toBeUndefined();
+ expect(object.callInParentheses(object)).toBe(object);
+ expect(() => object.callInParentheses(null)).toThrow(TypeError);
+});
+
+test("super and private names as assignment targets", () => {
+ expect(new Derived().assignToSuperInPatterns()).toEqual([1, 2]);
+ expect(new Derived().assignToPrivateInPattern()).toBe(5);
+ expect(new Derived().loopOverSuperAndPrivate()).toEqual([2, "key", 7]);
+});
+
+test("number and BigInt keys of methods and accessors", () => {
+ function f() {
+ return {
+ 1() {},
+ get 2() {
+ return 2;
+ },
+ 3n() {},
+ get 4n() {
+ return 4;
+ },
+ 5n: 6,
+ 6n: function () {},
+ 7n: class {
+ static n = this.name;
+ },
+ };
+ }
+ const object = f();
+ expect(object[1].name).toBe("1");
+ expect(object[2]).toBe(2);
+ expect(object[3].name).toBe("3");
+ expect(Object.getOwnPropertyDescriptor(object, "4").get.name).toBe("get 4");
+ expect(object[5]).toBe(6);
+ expect(object[6].name).toBe("6");
+ expect(object[7].n).toBe("7");
+});
+
+test("an optional chain in parentheses keeps what it gets called on", () => {
+ function f() {
+ const object = {
+ method() {
+ return this;
+ },
+ nested: {
+ method() {
+ return this;
+ },
+ },
+ };
+ expect((object?.method)()).toBe(object);
+ expect((object?.["method"])()).toBe(object);
+ expect((object?.nested.method)()).toBe(object.nested);
+ expect(object?.method?.()).toBe(object);
+ expect((object?.method)``).toBe(object);
+ const nothing = null;
+ expect(() => (nothing?.method)()).toThrow(TypeError);
+ expect(nothing?.method?.()).toBeUndefined();
+ }
+ f();
+});
+
+test("a call as a target throws after evaluating the call, and before the value", () => {
+ const log = [];
+ const call = () => {
+ log.push("call");
+ return {};
+ };
+ const value = () => {
+ log.push("value");
+ };
+ const sources = [
+ "call() = value();",
+ "call() += value();",
+ "++call();",
+ "const object = {}; object.a = call()++;",
+ "const object = {}; object.a = call() = value();",
+ "call()-- + value();",
+ "value(-(call() += value()));",
+ "for (call() of [1]);",
+ "for (call() in { key: 1 });",
+ ];
+ for (const source of sources) {
+ log.length = 0;
+ const f = new Function("call", "value", source);
+ expect(() => f(call, value)).toThrowWithMessage(ReferenceError, "Invalid left-hand side in assignment");
+ expect(log).toEqual(["call"]);
+ }
+ expect(new Function("call", "for (call() of []); return 1;")(call)).toBe(1);
+});
+
+test("patterns nested in a rest element", () => {
+ function f() {
+ let a, b;
+ const object = {};
+ [...[a = 1, b]] = [];
+ [...[object.c = 2]] = [];
+ [...[[object.d = 3] = []]] = [];
+ [...{ length: object.e }] = [1, 2];
+ return [a, b, object];
+ }
+ expect(f()).toEqual([1, undefined, { c: 2, d: 3, e: 2 }]);
+});
+
+test("a var initializer in the head of a for-in loop", () => {
+ function f() {
+ function read() {
+ return x;
+ }
+ const before = read();
+ for (var x = (1) in {});
+ return [before, read()];
+ }
+ expect(f()).toEqual([undefined, 1]);
+
+ function g() {
+ const object = { p: 1 };
+ with (object) {
+ for (var p = (delete object.p) in {});
+ }
+ return [object.p, p];
+ }
+ expect(g()).toEqual([true, undefined]);
+});
+
+test("BigInt keys of fields and patterns", () => {
+ function f() {
+ class C {
+ 1n = 1;
+ static 2n = () => {};
+ }
+ const { 3n: a, 0x4n: b = 5 } = { 3: 4 };
+ return [new C()[1], C[2].name, a, b];
+ }
+ expect(f()).toEqual([1, "2", 4, 5]);
+});
+
+test("a rest element whose target is a member", () => {
+ function f() {
+ const object = {};
+ const value = [1, 2];
+ const result = ([object.first, ...object.rest] = value);
+ return [result === value, object.first, object.rest];
+ }
+ expect(f()).toEqual([true, 1, [2]]);
+});
diff --git a/Tests/LibJS/Runtime/functions/annex-b-function-after-blocking-let.js b/Tests/LibJS/Runtime/functions/annex-b-function-after-blocking-let.js
new file mode 100644
index 00000000000..7979ff76de2
--- /dev/null
+++ b/Tests/LibJS/Runtime/functions/annex-b-function-after-blocking-let.js
@@ -0,0 +1,42 @@
+test("a let later in an enclosing block keeps a function from hoisting", () => {
+ function run() {
+ var outer;
+ {
+ function x() {
+ return 1;
+ }
+ outer = x;
+ }
+ {
+ {
+ function x() {
+ return 2;
+ }
+ }
+ let x;
+ }
+ {
+ let x;
+ {
+ function x() {
+ return 3;
+ }
+ }
+ }
+ return x === outer;
+ }
+ expect(run()).toBeTrue();
+});
+
+test("a let later in the function keeps a function from hoisting", () => {
+ function run() {
+ {
+ function x() {
+ return 1;
+ }
+ }
+ let x = 2;
+ return x;
+ }
+ expect(run()).toBe(2);
+});
diff --git a/Tests/LibJS/Runtime/functions/function-destructuring-parameters.js b/Tests/LibJS/Runtime/functions/function-destructuring-parameters.js
index 011f9268849..41f7bb8fae3 100644
--- a/Tests/LibJS/Runtime/functions/function-destructuring-parameters.js
+++ b/Tests/LibJS/Runtime/functions/function-destructuring-parameters.js
@@ -179,3 +179,41 @@ describe("evaluating", () => {
expect(testFunction({ b: 42 })).toBe("2742");
});
});
+
+describe("names of a parameter's binding pattern are uninitialized until they are bound", () => {
+ test("read by an initializer", () => {
+ function arrayPattern([a = b, b]) {}
+ function objectPattern({ a = b, b }) {}
+ function earlierPattern([a = b], [b]) {}
+ function plainParameter(a = b, [b]) {}
+ function typeofName([a = typeof b, b]) {}
+ const arrow = ([a = b, b]) => {};
+
+ expect(() => arrayPattern([])).toThrow(ReferenceError);
+ expect(() => objectPattern({})).toThrow(ReferenceError);
+ expect(() => earlierPattern([], [])).toThrow(ReferenceError);
+ expect(() => plainParameter(undefined, [])).toThrow(ReferenceError);
+ expect(() => typeofName([])).toThrow(ReferenceError);
+ expect(() => arrow([])).toThrow(ReferenceError);
+ });
+
+ test("assigned by an initializer", () => {
+ function assigned([a = (b = 1), b]) {}
+ function updated([a = b++, b]) {}
+
+ expect(() => assigned([])).toThrow(ReferenceError);
+ expect(() => updated([])).toThrow(ReferenceError);
+ });
+
+ test("read once they are bound", () => {
+ function arrayPattern([a, b = a]) {
+ return b;
+ }
+ function objectPattern({ a, b = a }, c = b) {
+ return c;
+ }
+
+ expect(arrayPattern([1])).toBe(1);
+ expect(objectPattern({ a: 2 })).toBe(2);
+ });
+});
diff --git a/Tests/LibJS/Runtime/functions/function-duplicate-parameters.js b/Tests/LibJS/Runtime/functions/function-duplicate-parameters.js
index 1bd413cecf7..eb7e46b9ec0 100644
--- a/Tests/LibJS/Runtime/functions/function-duplicate-parameters.js
+++ b/Tests/LibJS/Runtime/functions/function-duplicate-parameters.js
@@ -73,3 +73,27 @@ test("syntax errors", () => {
({ foo(bar, ...bar) {} });
`).not.toEval();
});
+
+test("sloppy generators and async functions with a simple parameter list may repeat a parameter name", () => {
+ expect("function* g(a, a) {}").toEval();
+ expect("async function f(a, a) {}").toEval();
+ expect("async function* h(a, a) {}").toEval();
+ expect("(function* (a, a) {})").toEval();
+ expect("(async function (a, a) {})").toEval();
+ expect("(async function* (a, a) {})").toEval();
+
+ function* generator(a, a) {
+ yield a;
+ }
+ expect(generator(1, 2).next().value).toBe(2);
+});
+
+test("other generators and async functions may not repeat a parameter name", () => {
+ expect("'use strict'; function* g(a, a) {}").not.toEval();
+ expect("async function f(a, a) { 'use strict'; }").not.toEval();
+ expect("function* g(a, [a]) {}").not.toEval();
+ expect("async function f(a, a = 1) {}").not.toEval();
+ expect("async (a, a) => {}").not.toEval();
+ expect("({ *m(a, a) {} })").not.toEval();
+ expect("({ async m(a, a) {} })").not.toEval();
+});
diff --git a/Tests/LibJS/Runtime/functions/function-expression-name-redeclaration.js b/Tests/LibJS/Runtime/functions/function-expression-name-redeclaration.js
new file mode 100644
index 00000000000..a09f4efc7c3
--- /dev/null
+++ b/Tests/LibJS/Runtime/functions/function-expression-name-redeclaration.js
@@ -0,0 +1,33 @@
+test("parameter with the name of the function expression", () => {
+ const function_ = function name(name) {
+ var captured = [1];
+ function read() {
+ return captured.length;
+ }
+ return [name, read()];
+ };
+ expect(function_(7)).toEqual([7, 1]);
+});
+
+test("var with the name of the function expression", () => {
+ const function_ = function name() {
+ var name;
+ name = 1;
+ function read() {
+ return name;
+ }
+ return read();
+ };
+ expect(function_()).toBe(1);
+});
+
+test("function declaration with the name of the function expression", () => {
+ const function_ = function name() {
+ var other = 2;
+ function name() {
+ return other;
+ }
+ return name();
+ };
+ expect(function_()).toBe(2);
+});
diff --git a/Tests/LibJS/Runtime/functions/function-name-from-string-key.js b/Tests/LibJS/Runtime/functions/function-name-from-string-key.js
new file mode 100644
index 00000000000..514380af94c
--- /dev/null
+++ b/Tests/LibJS/Runtime/functions/function-name-from-string-key.js
@@ -0,0 +1,20 @@
+test("anonymous functions take their names from the string keys of object literals", () => {
+ function make() {
+ return { "with space": () => 1, "with-dash": function () {}, "1x": class {} };
+ }
+ const object = make();
+ expect(object["with space"].name).toBe("with space");
+ expect(object["with-dash"].name).toBe("with-dash");
+ expect(object["1x"].name).toBe("1x");
+});
+
+test("anonymous classes take their names from computed keys, in parentheses too", () => {
+ function make(key) {
+ // prettier-ignore
+ return { [key]: class {}, [key + "2"]: (class {}), [key + "3"]: class { static name = 1; } };
+ }
+ const object = make("key");
+ expect(object.key.name).toBe("key");
+ expect(object.key2.name).toBe("key2");
+ expect(object.key3.name).toBe(1);
+});
diff --git a/Tests/LibJS/Runtime/functions/function-spread.js b/Tests/LibJS/Runtime/functions/function-spread.js
index fcfcd9cd48d..efe11b453ea 100644
--- a/Tests/LibJS/Runtime/functions/function-spread.js
+++ b/Tests/LibJS/Runtime/functions/function-spread.js
@@ -36,3 +36,13 @@ test("spreading non iterable", () => {
[...1];
}).toThrowWithMessage(TypeError, "1 is not iterable");
});
+
+test("call of a function named async with spread arguments", () => {
+ const async = (...values) => values;
+
+ expect(async(...[1, 2], 3)).toEqual([1, 2, 3]);
+ expect(async(0, ...[1, 2])).toEqual([0, 1, 2]);
+ expect(async(0, ...[1], 2, ...[3], 4)).toEqual([0, 1, 2, 3, 4]);
+ expect(async(...[1, 2])).toEqual([1, 2]);
+ expect(async(...[1, 2]).length).toBe(2);
+});
diff --git a/Tests/LibJS/Runtime/let-in-loop-initializer.js b/Tests/LibJS/Runtime/let-in-loop-initializer.js
new file mode 100644
index 00000000000..91f7e85635c
--- /dev/null
+++ b/Tests/LibJS/Runtime/let-in-loop-initializer.js
@@ -0,0 +1,24 @@
+test("the initializer of a let in a loop sees it in its dead zone in every iteration", () => {
+ function run() {
+ const results = [];
+ for (let i = 0; i < 2; ++i) {
+ try {
+ if (i === 0) continue;
+ let value = value;
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ }
+ for (let i = 0; i < 2; ++i) {
+ try {
+ let value = i === 0 ? 1 : value;
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ }
+ return results;
+ }
+ expect(run()).toEqual(["ReferenceError", 1, "ReferenceError"]);
+});
diff --git a/Tests/LibJS/Runtime/long-operator-chains.js b/Tests/LibJS/Runtime/long-operator-chains.js
new file mode 100644
index 00000000000..bae6c8486fa
--- /dev/null
+++ b/Tests/LibJS/Runtime/long-operator-chains.js
@@ -0,0 +1,73 @@
+const repeat = (first, rest, count) => {
+ const parts = [first];
+ for (let i = 1; i < count; ++i) parts.push(rest(i));
+ return parts.join("");
+};
+
+test("a long chain of one operator", () => {
+ expect(eval(repeat("1", () => " + 1", 16000))).toBe(16000);
+});
+
+test("a long chain of alternating operators", () => {
+ expect(eval(repeat("1", i => (i % 2 ? " * 1" : " + 1"), 16000))).toBe(8000);
+});
+
+test("a long chain of alternating logical operators", () => {
+ expect(eval(repeat("1", i => (i % 2 ? " && 1" : " || 1"), 16000))).toBe(1);
+});
+
+test("a long chain in a function", () => {
+ const f = new Function(`return ${repeat("1", () => " + 1", 16000)};`);
+ expect(f()).toBe(16000);
+});
+
+test("a template normalizes line terminators", () => {
+ const tag = strings => [strings[0], strings.raw[0]];
+ expect(eval("tag`a\rb\r\nc`")).toEqual(["a\nb\nc", "a\nb\nc"]);
+ expect(eval("`a\rb`")).toBe("a\nb");
+});
+
+describe("chains of operators of any length, at the top level of code", () => {
+ const length = 500000;
+ const prelude = "var a = function () { return a; }; a.b = a; a[0] = a;";
+ const chains = {
+ "binary operators": ["1" + "+1".repeat(length), length + 1],
+ "logical operators": ["true" + "&&true".repeat(length), true],
+ "member expressions": ["typeof a" + ".b".repeat(length), "function"],
+ "computed member expressions": ["typeof a" + "[0]".repeat(length), "function"],
+ calls: ["typeof a" + "()".repeat(length), "function"],
+ "tagged templates": ["typeof a" + "``".repeat(length), "function"],
+ "a chain in an operand": ["[0" + "+1".repeat(length) + "][0]", length],
+ "a chain in a class field": ["new (class { x = 1" + "+1".repeat(length) + "; })().x", length + 1],
+ };
+
+ for (const [name, [source, expected]] of Object.entries(chains)) {
+ test(name, () => {
+ expect((0, eval)(`${prelude}${source}`)).toBe(expected);
+ expect(new Function(`${prelude}return ${source}`)()).toBe(expected);
+ });
+ }
+
+ test("in the targets of a destructuring assignment", () => {
+ const member = (0, eval)(`${prelude}[a${".b".repeat(length)}.c] = [1]; a.c`);
+ expect(member).toBe(1);
+ const key = (0, eval)(`${prelude}[a[0${"+1".repeat(length)}]] = [1]; Object.keys(a).length`);
+ expect(key).toBe(3);
+ });
+});
+
+test("nested code that eval gets at the end of the stack does not run out of it", () => {
+ const nested = "(".repeat(1900) + "1" + ")".repeat(1900);
+ function atTheEndOfTheStack() {
+ try {
+ return atTheEndOfTheStack();
+ } catch (error) {
+ try {
+ return eval(nested);
+ } catch {
+ return 1;
+ }
+ }
+ }
+ expect(atTheEndOfTheStack()).toBe(1);
+});
diff --git a/Tests/LibJS/Runtime/loops/tdz-on-each-iteration.js b/Tests/LibJS/Runtime/loops/tdz-on-each-iteration.js
index 8e106c0866e..1115ed42455 100644
--- a/Tests/LibJS/Runtime/loops/tdz-on-each-iteration.js
+++ b/Tests/LibJS/Runtime/loops/tdz-on-each-iteration.js
@@ -114,4 +114,232 @@ describe("a lexical binding is uninitialized again on each iteration", () => {
expect(loop()).toEqual([0, "ReferenceError"]);
});
+
+ test("a block in a loop that an inner loop breaks out of", () => {
+ function loop() {
+ const results = [];
+ for (let i = 0; i < 2; i++) {
+ for (;;) {
+ try {
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ let value = i;
+ break;
+ }
+ }
+ return results;
+ }
+
+ expect(loop()).toEqual(["ReferenceError", "ReferenceError"]);
+ });
+
+ test("a scope around an inner loop that reads the binding", () => {
+ function loop() {
+ const results = [];
+ for (let i = 0; i < 2; i++) {
+ {
+ for (let j = 0; j < 2; j++) {
+ try {
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ }
+ let value = i;
+ }
+ }
+ return results;
+ }
+
+ expect(loop()).toEqual(["ReferenceError", "ReferenceError", "ReferenceError", "ReferenceError"]);
+ });
+
+ test("a loop that reads a binding of the scope around it keeps the binding", () => {
+ function afterClass() {
+ const results = [];
+ {
+ class C {}
+ for (let i = 0; i < 2; i++) results.push(typeof C);
+ }
+ return results;
+ }
+
+ function afterCase(which) {
+ const results = [];
+ switch (which) {
+ case 0:
+ let value = "initialized";
+ case 1:
+ for (let i = 0; i < 2; i++) {
+ try {
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ }
+ }
+ return results;
+ }
+
+ expect(afterClass()).toEqual(["function", "function"]);
+ expect(afterCase(0)).toEqual(["initialized", "initialized"]);
+ expect(afterCase(1)).toEqual(["ReferenceError", "ReferenceError"]);
+ });
+
+ test("loop bodies that a statement around the scope starts", () => {
+ function whileLoop() {
+ const results = [];
+ let i = 0;
+ while (i < 2) {
+ if (i >= 0) {
+ try {
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ let value = i++;
+ }
+ }
+ return results;
+ }
+
+ function doWhileLoop() {
+ const results = [];
+ let i = 0;
+ do {
+ label: {
+ try {
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ let value = i++;
+ if (i > 0) break label;
+ }
+ } while (i < 2);
+ return results;
+ }
+
+ function forInLoop() {
+ const results = [];
+ for (const key in { a: 1, b: 2 }) {
+ try {
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ let value = key;
+ }
+ return results;
+ }
+
+ function forOfLoop() {
+ const results = [];
+ for (const element of [1, 2]) {
+ try {
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ let value = element;
+ }
+ return results;
+ }
+
+ function* generatorLoop() {
+ for (let i = 0; i < 2; i++) {
+ try {
+ yield value;
+ } catch (error) {
+ yield error.name;
+ }
+ let value = i;
+ yield "initialized";
+ }
+ }
+
+ const twice = ["ReferenceError", "ReferenceError"];
+ expect(whileLoop()).toEqual(twice);
+ expect(doWhileLoop()).toEqual(twice);
+ expect(forInLoop()).toEqual(twice);
+ expect(forOfLoop()).toEqual(twice);
+ expect([...generatorLoop()]).toEqual(["ReferenceError", "initialized", "ReferenceError", "initialized"]);
+ });
+
+ test("head of a loop in a loop without a block around it", () => {
+ function forLoopHead() {
+ const results = [];
+ for (let i = 0; i < 2; i++)
+ try {
+ for (let value = value; ; ) break;
+ } catch (error) {
+ results.push(error.name);
+ }
+ return results;
+ }
+
+ function forOfHeadInIf() {
+ const results = [];
+ for (let i = 0; i < 2; i++) {
+ try {
+ if (i >= 0) for (let value of i === 0 ? [i] : [value]) results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ }
+ return results;
+ }
+
+ function forInHeadInLabel() {
+ const results = [];
+ for (let i = 0; i < 2; i++) {
+ try {
+ label: for (let value in i === 0 ? { key: 1 } : value) results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ }
+ return results;
+ }
+
+ expect(forLoopHead()).toEqual(["ReferenceError", "ReferenceError"]);
+ expect(forOfHeadInIf()).toEqual([0, "ReferenceError"]);
+ expect(forInHeadInLabel()).toEqual(["key", "ReferenceError"]);
+ });
+
+ test("code that a function does not hold the locals of", () => {
+ expect(
+ eval(`
+ const results = [];
+ for (let i = 0; i < 2; i++) {
+ try {
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ let value = i;
+ }
+ results;
+ `)
+ ).toEqual(["ReferenceError", "ReferenceError"]);
+
+ const results = [];
+ for (let i = 0; i < 2; i++) {
+ class C {
+ static {
+ for (let j = 0; j < 2; j++) {
+ try {
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ let value = j;
+ }
+ }
+ }
+ }
+ expect(results).toEqual(["ReferenceError", "ReferenceError", "ReferenceError", "ReferenceError"]);
+ });
});
diff --git a/Tests/LibJS/Runtime/modules/basic-modules.js b/Tests/LibJS/Runtime/modules/basic-modules.js
index 8e9cca195ed..528ccbb47c7 100644
--- a/Tests/LibJS/Runtime/modules/basic-modules.js
+++ b/Tests/LibJS/Runtime/modules/basic-modules.js
@@ -192,10 +192,18 @@ describe("in- and exports", () => {
expectModulePassed("./declarations-tests.mjs");
});
+ test("var declarations can repeat a name", () => {
+ expectModulePassed("./var-redeclaration.mjs");
+ });
+
test("string '*' is not a full namespace import", () => {
expectModulePassed("./string-import-names.mjs");
});
+ test("a name after the empty name keeps its meaning in functions", () => {
+ expectModulePassed("./empty-string-export-after-functions.mjs");
+ });
+
test("can combine string and default exports", () => {
expectModulePassed("./string-import-namespace.mjs");
});
diff --git a/Tests/LibJS/Runtime/modules/empty-string-export-after-functions.mjs b/Tests/LibJS/Runtime/modules/empty-string-export-after-functions.mjs
new file mode 100644
index 00000000000..7bd2c25ea64
--- /dev/null
+++ b/Tests/LibJS/Runtime/modules/empty-string-export-after-functions.mjs
@@ -0,0 +1,9 @@
+import { "" as empty } from "./default-and-star-export.mjs";
+
+const afterTheEmptyName = 1;
+
+function read() {
+ return afterTheEmptyName;
+}
+
+export const passed = read() === 1 && empty === "empty";
diff --git a/Tests/LibJS/Runtime/modules/var-redeclaration.mjs b/Tests/LibJS/Runtime/modules/var-redeclaration.mjs
new file mode 100644
index 00000000000..f5100b4869c
--- /dev/null
+++ b/Tests/LibJS/Runtime/modules/var-redeclaration.mjs
@@ -0,0 +1,13 @@
+var repeated = 1;
+var repeated;
+var other = 2,
+ repeated;
+
+for (var repeated of []) {
+}
+
+{
+ var other;
+}
+
+export const passed = repeated === 1 && other === 2;
diff --git a/Tests/LibJS/Runtime/operands-across-held-registers.js b/Tests/LibJS/Runtime/operands-across-held-registers.js
new file mode 100644
index 00000000000..2e13e57b2ad
--- /dev/null
+++ b/Tests/LibJS/Runtime/operands-across-held-registers.js
@@ -0,0 +1,54 @@
+test("operands survive a class whose computed key branches", () => {
+ function run() {
+ let a = 1;
+ let object = {};
+ let condition = "x";
+ let key = 2;
+ return [
+ a,
+ (object[
+ class {
+ [condition ? key : 0]() {}
+ }.name
+ ] += 1),
+ ];
+ }
+ const result = run();
+ expect(result).toHaveLength(2);
+ expect(result[0]).toBe(1);
+ expect(result[1]).toBeNaN();
+});
+
+test("operands survive an array pattern whose default branches", () => {
+ function run() {
+ let a = 1;
+ let b = 2;
+ let condition = true;
+ let target;
+ const pattern = ([target = condition ? 3 : 4] = []);
+ return [a, b, ([target = condition ? 5 : 6] = []), (a += b), target, pattern.length];
+ }
+ const result = run();
+ expect(result[0]).toBe(1);
+ expect(result[1]).toBe(2);
+ expect(result[2]).toEqual([]);
+ expect(result[3]).toBe(3);
+ expect(result[4]).toBe(5);
+ expect(result[5]).toBe(0);
+});
+
+test("operands survive an object pattern whose computed key branches", () => {
+ function run() {
+ let a = 1;
+ let object = { x: 2 };
+ let condition = true;
+ let target;
+ return [a, object, ({ [condition ? "x" : "y"]: target } = object), target, a];
+ }
+ const result = run();
+ expect(result[0]).toBe(1);
+ expect(result[1].x).toBe(2);
+ expect(result[2].x).toBe(2);
+ expect(result[3]).toBe(2);
+ expect(result[4]).toBe(1);
+});
diff --git a/Tests/LibJS/Runtime/parser-line-terminators.js b/Tests/LibJS/Runtime/parser-line-terminators.js
index 9fb09e43cb3..55d78a41e9a 100644
--- a/Tests/LibJS/Runtime/parser-line-terminators.js
+++ b/Tests/LibJS/Runtime/parser-line-terminators.js
@@ -13,38 +13,38 @@ function anonymous(
test("LINE FEED is a line terminator", () => {
expect(() => {
Function("\n\n@");
- }).toThrowWithMessage(SyntaxError, "Unexpected token Invalid. Expected CurlyClose (line: 4, column: 1)");
+ }).toThrowWithMessage(SyntaxError, "Unexpected token '@'. Expected '}' (line: 4, column: 1)");
});
test("CARRIAGE RETURN is a line terminator", () => {
expect(() => {
Function("\r\r@");
- }).toThrowWithMessage(SyntaxError, "Unexpected token Invalid. Expected CurlyClose (line: 4, column: 1)");
+ }).toThrowWithMessage(SyntaxError, "Unexpected token '@'. Expected '}' (line: 4, column: 1)");
});
test("LINE SEPARATOR is a line terminator", () => {
expect(() => {
Function("

@");
- }).toThrowWithMessage(SyntaxError, "Unexpected token Invalid. Expected CurlyClose (line: 4, column: 1)");
+ }).toThrowWithMessage(SyntaxError, "Unexpected token '@'. Expected '}' (line: 4, column: 1)");
});
test("PARAGRAPH SEPARATOR is a line terminator", () => {
expect(() => {
Function("

@");
- }).toThrowWithMessage(SyntaxError, "Unexpected token Invalid. Expected CurlyClose (line: 4, column: 1)");
+ }).toThrowWithMessage(SyntaxError, "Unexpected token '@'. Expected '}' (line: 4, column: 1)");
});
test("CR LF is counted as only one line terminator", () => {
expect(() => {
Function("\r\n\r\n@");
- }).toThrowWithMessage(SyntaxError, "Unexpected token Invalid. Expected CurlyClose (line: 4, column: 1)");
+ }).toThrowWithMessage(SyntaxError, "Unexpected token '@'. Expected '}' (line: 4, column: 1)");
});
test("LF/CR are not allowed in string literal", () => {
expect(() => {
Function(`"
"`);
- }).toThrowWithMessage(SyntaxError, "Unexpected token UnterminatedStringLiteral");
+ }).toThrowWithMessage(SyntaxError, "Unterminated string literal");
});
test("LS/PS are allowed in string literal", () => {
@@ -55,7 +55,7 @@ test("LS/PS are allowed in string literal", () => {
test("line terminators can be mixed (but please don't)", () => {
expect(() => {
Function("\r
\r\n
\n\r@");
- }).toThrowWithMessage(SyntaxError, "Unexpected token Invalid. Expected CurlyClose (line: 8, column: 1)");
+ }).toThrowWithMessage(SyntaxError, "Unexpected token '@'. Expected '}' (line: 8, column: 1)");
});
test("all line terminators are valid for line continuations", () => {
diff --git a/Tests/LibJS/Runtime/postfix-update-after-for-update.js b/Tests/LibJS/Runtime/postfix-update-after-for-update.js
new file mode 100644
index 00000000000..a0368be8e3e
--- /dev/null
+++ b/Tests/LibJS/Runtime/postfix-update-after-for-update.js
@@ -0,0 +1,9 @@
+test("the update of a for loop leaves nothing behind for the next function", () => {
+ // NB: Which rows of the two functions line up depends on the padding.
+ for (let padding = 0; padding < 32; ++padding) {
+ const first = new Function("let a = 1; for (; false; a--); return a;");
+ const second = new Function(`let a = 1; return [${"0, ".repeat(padding)}a--];`);
+ expect(first()).toBe(1);
+ expect(second().at(-1)).toBe(1);
+ }
+});
diff --git a/Tests/LibJS/Runtime/reference-text-in-errors.js b/Tests/LibJS/Runtime/reference-text-in-errors.js
new file mode 100644
index 00000000000..13fefd1abea
--- /dev/null
+++ b/Tests/LibJS/Runtime/reference-text-in-errors.js
@@ -0,0 +1,528 @@
+// The text of a reference comes from the source when an error gets thrown, so that how the source is written matters.
+const object = {
+ m() {
+ return this;
+ },
+ g: 1,
+ K: function () {},
+ a2: [1, 2],
+ tag() {},
+};
+object.o = object;
+
+function Constructor() {}
+Constructor.prototype = object;
+Constructor.nope = undefined;
+
+class Base {}
+Base.prototype.m = function () {
+ return this;
+};
+
+const names = ["o", "u", "nk", "kg", "i0", "a2", "nf", "C", "K0", "f0", "tag", "it"];
+const values = [
+ object,
+ undefined,
+ "nope",
+ "g",
+ 0,
+ [1, 2],
+ 5,
+ Constructor,
+ Base,
+ function () {},
+ function () {},
+ { [Symbol.iterator]: () => ({ next: () => ({ done: true }) }) },
+];
+
+function expectMessage(source, message) {
+ const f = new Function(...names, source);
+ expect(() => f.call(object, ...values)).toThrowWithMessage(TypeError, message);
+}
+
+test("calls of members", () => {
+ const cases = [
+ ["u()", "undefined is not a function (evaluated from 'u')"],
+ ["u(\n )", "undefined is not a function (evaluated from 'u')"],
+ ["o.nope()", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o\n .nope(\n )", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o.o.nope()", "undefined is not a function (evaluated from 'o.o.nope')"],
+ ["o\n .o\n .nope(\n )", "undefined is not a function (evaluated from 'o.o.nope')"],
+ ['o["nope"]()', "undefined is not a function (evaluated from 'o['nope']')"],
+ ['o["nope"](\n )', "undefined is not a function (evaluated from 'o['nope']')"],
+ ["o[nk]()", "undefined is not a function (evaluated from 'o[nk]')"],
+ ["o[nk](\n )", "undefined is not a function (evaluated from 'o[nk]')"],
+ ["o.m().nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["o\n .m(\n )\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ['o.m()["nope"]()', "undefined is not a function (evaluated from '<object>['nope']')"],
+ ['o\n .m(\n )["nope"](\n )', "undefined is not a function (evaluated from '<object>['nope']')"],
+ ["o?.nope()", "undefined is not a function"],
+ ["o?.nope(\n )", "undefined is not a function"],
+ ["o?.o.nope()", "undefined is not a function"],
+ ["o?.o\n .nope(\n )", "undefined is not a function"],
+ ['o?.["nope"]()', "undefined is not a function"],
+ ['o?.["nope"](\n )', "undefined is not a function"],
+ ["new o.nope()", "undefined is not a constructor (evaluated from 'o.nope')"],
+ ["new o\n .nope(\n )", "undefined is not a constructor (evaluated from 'o.nope')"],
+ ["new o.nope", "undefined is not a constructor (evaluated from 'o.nope')"],
+ ["new o\n .nope", "undefined is not a constructor (evaluated from 'o.nope')"],
+ ["new u()", "undefined is not a constructor (evaluated from 'u')"],
+ ["new u(\n )", "undefined is not a constructor (evaluated from 'u')"],
+ ["new o.g()", "1 is not a constructor (evaluated from 'o.g')"],
+ ["new o\n .g(\n )", "1 is not a constructor (evaluated from 'o.g')"],
+ ["new (o.nope)()", "undefined is not a constructor (evaluated from 'o.nope')"],
+ ["new (\n o\n .nope)(\n )", "undefined is not a constructor (evaluated from 'o.nope')"],
+ ["new (o.m())()", "[object Object] is not a constructor"],
+ ["new (\n o\n .m(\n ))()", "[object Object] is not a constructor"],
+ ["new (o.m().nope)()", "undefined is not a constructor (evaluated from '<object>.nope')"],
+ ["new (\n o\n .m(\n )\n .nope)()", "undefined is not a constructor (evaluated from '<object>.nope')"],
+ ["new nf()", "5 is not a constructor (evaluated from 'nf')"],
+ ["new nf(\n )", "5 is not a constructor (evaluated from 'nf')"],
+ ["new o.o.nope()", "undefined is not a constructor (evaluated from 'o.o.nope')"],
+ ["new o\n .o\n .nope(\n )", "undefined is not a constructor (evaluated from 'o.o.nope')"],
+ ['new o["nope"]()', "undefined is not a constructor (evaluated from 'o['nope']')"],
+ ['new o["nope"](\n )', "undefined is not a constructor (evaluated from 'o['nope']')"],
+ ["new o[nk]()", "undefined is not a constructor (evaluated from 'o[nk]')"],
+ ["new o[nk](\n )", "undefined is not a constructor (evaluated from 'o[nk]')"],
+ ["nf()", "5 is not a function (evaluated from 'nf')"],
+ ["nf(\n )", "5 is not a function (evaluated from 'nf')"],
+ ["1()", "1 is not a function"],
+ ["1(\n )", "1 is not a function"],
+ ['"s"()', "s is not a function"],
+ ['"s"(\n )', "s is not a function"],
+ ["null()", "null is not a function"],
+ ["null(\n )", "null is not a function"],
+ ["o.g()", "1 is not a function (evaluated from 'o.g')"],
+ ["o\n .g(\n )", "1 is not a function (evaluated from 'o.g')"],
+ ["o.o()", "[object Object] is not a function (evaluated from 'o.o')"],
+ ["o\n .o(\n )", "[object Object] is not a function (evaluated from 'o.o')"],
+ ["(o.nope)()", "undefined is not a function (evaluated from 'o.nope')"],
+ ["(\n o\n .nope)(\n )", "undefined is not a function (evaluated from 'o.nope')"],
+ ["(o.m().nope)()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(\n o\n .m(\n )\n .nope)()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(o).nope()", "undefined is not a function (evaluated from 'o.nope')"],
+ ["(\n o)\n .nope(\n )", "undefined is not a function (evaluated from 'o.nope')"],
+ ["((o)).nope()", "undefined is not a function (evaluated from 'o.nope')"],
+ ["(\n (\n o))\n .nope()", "undefined is not a function (evaluated from 'o.nope')"],
+ ["(o.o).nope()", "undefined is not a function (evaluated from 'o.o.nope')"],
+ ["(\n o\n .o)\n .nope(\n )", "undefined is not a function (evaluated from 'o.o.nope')"],
+ ["(0, o.nope)()", "undefined is not a function"],
+ ["(\n 0, o\n .nope)(\n )", "undefined is not a function"],
+ ["(u || o).nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(\n u || o)\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(u ?? o).nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(\n u ?? o)\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(1 + 2)()", "3 is not a function"],
+ ["(\n 1 + 2)(\n )", "3 is not a function"],
+ ["(o, o).nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(\n o, o)\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(function () {}).nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(\n function (\n ) {})\n .nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(() => {}).nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(\n (\n ) => {})\n .nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(class {}).nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(\n class {})\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["[].nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["[]\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["[1, 2].nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["[1, 2]\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["[o][0].nope()", "undefined is not a function (evaluated from '<object>[0].nope')"],
+ ["[o][0]\n .nope(\n )", "undefined is not a function (evaluated from '<object>[0].nope')"],
+ ["({}).nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(\n {})\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["({a: 1}).nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(\n {a: 1})\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ['"str".nope()', "undefined is not a function (evaluated from ''str'.nope')"],
+ ['"str".nope(\n )', "undefined is not a function (evaluated from ''str'.nope')"],
+ ["'str'.nope()", "undefined is not a function (evaluated from ''str'.nope')"],
+ ["'str'.nope(\n )", "undefined is not a function (evaluated from ''str'.nope')"],
+ ['"s\'q".nope()', "undefined is not a function (evaluated from ''s'q'.nope')"],
+ ['"s\'q".nope(\n )', "undefined is not a function (evaluated from ''s'q'.nope')"],
+ ["`tpl`.nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["`tpl`.nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["`t${1}`.nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["`t${1}`.nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["1 .nope()", "undefined is not a function (evaluated from '1.nope')"],
+ ["1 .nope(\n )", "undefined is not a function (evaluated from '1.nope')"],
+ ["1.5.nope()", "undefined is not a function (evaluated from '1.5.nope')"],
+ ["1.5\n .nope(\n )", "undefined is not a function (evaluated from '1.5.nope')"],
+ ["(1).nope()", "undefined is not a function (evaluated from '1.nope')"],
+ ["(\n 1)\n .nope(\n )", "undefined is not a function (evaluated from '1.nope')"],
+ ["0x10.nope()", "undefined is not a function (evaluated from '16.nope')"],
+ ["0x10\n .nope(\n )", "undefined is not a function (evaluated from '16.nope')"],
+ ["1n.nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["1n\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["true.nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["true\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["/re/.nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["/re/.nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["this.nope()", "undefined is not a function (evaluated from 'this.nope')"],
+ ["this\n .nope(\n )", "undefined is not a function (evaluated from 'this.nope')"],
+ ["this.o.nope()", "undefined is not a function (evaluated from 'this.o.nope')"],
+ ["this\n .o\n .nope(\n )", "undefined is not a function (evaluated from 'this.o.nope')"],
+ ['this["nope"]()', "undefined is not a function (evaluated from 'this['nope']')"],
+ ['this["nope"](\n )', "undefined is not a function (evaluated from 'this['nope']')"],
+ ["new C().nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["new C(\n )\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["new C().m().nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["new C(\n )\n .m(\n )\n .nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["new C.nope()", "undefined is not a constructor (evaluated from 'C.nope')"],
+ ["new C\n .nope(\n )", "undefined is not a constructor (evaluated from 'C.nope')"],
+ ["new o.K().nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["new o\n .K(\n )\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ['new C()["nope"]()', "undefined is not a function (evaluated from '<object>['nope']')"],
+ ['new C(\n )["nope"](\n )', "undefined is not a function (evaluated from '<object>['nope']')"],
+ ["new C()[nk]()", "undefined is not a function (evaluated from '<object>[nk]')"],
+ ["new C(\n )[nk](\n )", "undefined is not a function (evaluated from '<object>[nk]')"],
+ ["f0()()", "undefined is not a function"],
+ ["f0(\n )(\n )", "undefined is not a function"],
+ ["a2[0].nope()", "undefined is not a function (evaluated from 'a2[0].nope')"],
+ ["a2[0]\n .nope(\n )", "undefined is not a function (evaluated from 'a2[0].nope')"],
+ ["a2[0]()", "1 is not a function (evaluated from 'a2[0]')"],
+ ["a2[0](\n )", "1 is not a function (evaluated from 'a2[0]')"],
+ ["a2[1 + 0]()", "2 is not a function (evaluated from 'a2[<object>]')"],
+ ["a2[1 + 0](\n )", "2 is not a function (evaluated from 'a2[<object>]')"],
+ ["a2[i0]()", "1 is not a function (evaluated from 'a2[i0]')"],
+ ["a2[i0](\n )", "1 is not a function (evaluated from 'a2[i0]')"],
+ ["a2[i0 + 1]()", "2 is not a function (evaluated from 'a2[<object>]')"],
+ ["a2[i0 + 1](\n )", "2 is not a function (evaluated from 'a2[<object>]')"],
+ ["a2[f0()]()", "undefined is not a function (evaluated from 'a2[<object>]')"],
+ ["a2[f0(\n )](\n )", "undefined is not a function (evaluated from 'a2[<object>]')"],
+ ["a2[o.g]()", "2 is not a function (evaluated from 'a2[o.g]')"],
+ ["a2[o\n .g](\n )", "2 is not a function (evaluated from 'a2[o.g]')"],
+ ["a2[o.m()]()", "undefined is not a function (evaluated from 'a2[<object>]')"],
+ ["a2[o\n .m(\n )](\n )", "undefined is not a function (evaluated from 'a2[<object>]')"],
+ ['a2["x"]()', "undefined is not a function (evaluated from 'a2['x']')"],
+ ['a2["x"](\n )', "undefined is not a function (evaluated from 'a2['x']')"],
+ ["a2['x']()", "undefined is not a function (evaluated from 'a2['x']')"],
+ ["a2['x'](\n )", "undefined is not a function (evaluated from 'a2['x']')"],
+ ["a2[`x`]()", "undefined is not a function (evaluated from 'a2[<object>]')"],
+ ["a2[`x`](\n )", "undefined is not a function (evaluated from 'a2[<object>]')"],
+ ["a2[1.5]()", "undefined is not a function (evaluated from 'a2[1.5]')"],
+ ["a2[1.5](\n )", "undefined is not a function (evaluated from 'a2[1.5]')"],
+ ["a2[-1]()", "undefined is not a function (evaluated from 'a2[<object>]')"],
+ ["a2[-1](\n )", "undefined is not a function (evaluated from 'a2[<object>]')"],
+ ["a2[this]()", "undefined is not a function (evaluated from 'a2[this]')"],
+ ["a2[this](\n )", "undefined is not a function (evaluated from 'a2[this]')"],
+ ["o.a2[0]()", "1 is not a function (evaluated from 'o.a2[0]')"],
+ ["o\n .a2[0](\n )", "1 is not a function (evaluated from 'o.a2[0]')"],
+ ["o.a2[0].nope()", "undefined is not a function (evaluated from 'o.a2[0].nope')"],
+ ["o\n .a2[0]\n .nope(\n )", "undefined is not a function (evaluated from 'o.a2[0].nope')"],
+ ["o.a2[o.g]()", "2 is not a function (evaluated from 'o.a2[o.g]')"],
+ ["o\n .a2[o\n .g](\n )", "2 is not a function (evaluated from 'o.a2[o.g]')"],
+ ["f0(1)(2)", "undefined is not a function"],
+ ["f0(\n 1)(\n 2)", "undefined is not a function"],
+ ['o.m(1, "a").nope()', "undefined is not a function (evaluated from '<object>.nope')"],
+ ['o\n .m(\n 1, "a")\n .nope(\n )', "undefined is not a function (evaluated from '<object>.nope')"],
+ ["o.m(function () {}).nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ [
+ "o\n .m(\n function (\n ) {})\n .nope()",
+ "undefined is not a function (evaluated from '<object>.nope')",
+ ],
+ ["o /* c */ .nope()", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o /* c */ .nope(\n )", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o // c\n .nope()", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o // c\n .nope(\n )", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o\n .nope()", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o\n .nope(\n )", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o.\n nope()", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o.\n nope(\n )", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o.m()\n .nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["o\n .m(\n )\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["o . nope ()", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o . nope (\n )", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o.nope ()", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o\n .nope (\n )", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o.nope (1)", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o\n .nope (\n 1)", "undefined is not a function (evaluated from 'o.nope')"],
+ ['o["nope"] ()', "undefined is not a function (evaluated from 'o['nope']')"],
+ ['o["nope"] (\n )', "undefined is not a function (evaluated from 'o['nope']')"],
+ ['o[ "nope" ]()', "undefined is not a function (evaluated from 'o['nope']')"],
+ ['o[ "nope" ](\n )', "undefined is not a function (evaluated from 'o['nope']')"],
+ ["o[ nk ]()", "undefined is not a function (evaluated from 'o[nk]')"],
+ ["o[ nk ](\n )", "undefined is not a function (evaluated from 'o[nk]')"],
+ ["o [nk]()", "undefined is not a function (evaluated from 'o[nk]')"],
+ ["o [nk](\n )", "undefined is not a function (evaluated from 'o[nk]')"],
+ [
+ "class S1 extends K0 { m() { super.nope() } } new S1().m()",
+ "undefined is not a function (evaluated from '<object>.nope')",
+ ],
+ [
+ "class S1 extends K0 { m(\n ) { super\n .nope(\n ) } } new S1()\n .m()",
+ "undefined is not a function (evaluated from '<object>.nope')",
+ ],
+ [
+ 'class S2 extends K0 { m() { super["nope"]() } } new S2().m()',
+ "undefined is not a function (evaluated from '<object>['nope']')",
+ ],
+ [
+ 'class S2 extends K0 { m(\n ) { super["nope"](\n ) } } new S2()\n .m()',
+ "undefined is not a function (evaluated from '<object>['nope']')",
+ ],
+ [
+ "class S3 extends K0 { m() { super[nk]() } } new S3().m()",
+ "undefined is not a function (evaluated from '<object>[nk]')",
+ ],
+ [
+ "class S3 extends K0 { m(\n ) { super[nk](\n ) } } new S3()\n .m()",
+ "undefined is not a function (evaluated from '<object>[nk]')",
+ ],
+ [
+ "class S6 extends K0 { m() { super.m().nope() } } new S6().m()",
+ "undefined is not a function (evaluated from '<object>.nope')",
+ ],
+ [
+ "class S6 extends K0 { m(\n ) { super\n .m(\n )\n .nope() } } new S6()\n .m()",
+ "undefined is not a function (evaluated from '<object>.nope')",
+ ],
+ ["class S7 extends u { }", "Class extends value undefined is not a constructor or null"],
+ ["tag`x``y`", "undefined is not a function"],
+ ["o.nope`x`", "undefined is not a function"],
+ ["o\n .nope`x`", "undefined is not a function"],
+ ['o["nope"]`x`', "undefined is not a function"],
+ ["o.m().nope`x`", "undefined is not a function"],
+ ["o\n .m(\n )\n .nope`x`", "undefined is not a function"],
+ ["nf`x`", "5 is not a function"],
+ ["u`x`", "undefined is not a function"],
+ ["new o.nope`x`", "undefined is not a function"],
+ ["new o\n .nope`x`", "undefined is not a function"],
+ ["(o.nope)`x`", "undefined is not a function"],
+ ["(\n o\n .nope)`x`", "undefined is not a function"],
+ ["o?.m().nope()", "undefined is not a function"],
+ ["o?.m(\n )\n .nope(\n )", "undefined is not a function"],
+ ["o?.m()?.nope()", "undefined is not a function"],
+ ["o?.m(\n )?.nope(\n )", "undefined is not a function"],
+ ["o?.m?.().nope()", "undefined is not a function"],
+ ["o?.m?.(\n )\n .nope(\n )", "undefined is not a function"],
+ ["o.m?.().nope()", "undefined is not a function"],
+ ["o\n .m?.(\n )\n .nope(\n )", "undefined is not a function"],
+ ['o?.m()["nope"]()', "undefined is not a function"],
+ ['o?.m(\n )["nope"](\n )', "undefined is not a function"],
+ ['o?.["m"]().nope()', "undefined is not a function"],
+ ['o?.["m"](\n )\n .nope(\n )', "undefined is not a function"],
+ ["(o?.nope)()", "undefined is not a function"],
+ ["(\n o?.nope)(\n )", "undefined is not a function"],
+ ["(o?.o).nope()", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["(\n o?.o)\n .nope(\n )", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["o.nope(...[1])", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o\n .nope(\n ...[1])", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o.nope(...it)", "undefined is not a function (evaluated from 'o.nope')"],
+ ["o\n .nope(\n ...it)", "undefined is not a function (evaluated from 'o.nope')"],
+ ["new o.nope(...it)", "undefined is not a constructor (evaluated from 'o.nope')"],
+ ["new o\n .nope(\n ...it)", "undefined is not a constructor (evaluated from 'o.nope')"],
+ ["new nf(...it)", "5 is not a constructor (evaluated from 'nf')"],
+ ["new nf(\n ...it)", "5 is not a constructor (evaluated from 'nf')"],
+ ["nf(...it)", "5 is not a function (evaluated from 'nf')"],
+ ["nf(\n ...it)", "5 is not a function (evaluated from 'nf')"],
+ ["u(...it)", "undefined is not a function (evaluated from 'u')"],
+ ["u(\n ...it)", "undefined is not a function (evaluated from 'u')"],
+ ["o.m().nope(...it)", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["o\n .m(\n )\n .nope(\n ...it)", "undefined is not a function (evaluated from '<object>.nope')"],
+ ["f0()(...it)", "undefined is not a function"],
+ ["f0(\n )(\n ...it)", "undefined is not a function"],
+ ["a2[o.g](...it)", "2 is not a function (evaluated from 'a2[o.g]')"],
+ ["a2[o\n .g](\n ...it)", "2 is not a function (evaluated from 'a2[o.g]')"],
+ ["o instanceof o", "[object Object] is not a function"],
+ ["o.o.o.nope()", "undefined is not a function (evaluated from 'o.o.o.nope')"],
+ ["o\n .o\n .o\n .nope(\n )", "undefined is not a function (evaluated from 'o.o.o.nope')"],
+ ["[u][0]()", "undefined is not a function (evaluated from '<object>[0]')"],
+ ["[u][0](\n )", "undefined is not a function (evaluated from '<object>[0]')"],
+ ["({}).x()", "undefined is not a function (evaluated from '<object>.x')"],
+ ["(\n {})\n .x(\n )", "undefined is not a function (evaluated from '<object>.x')"],
+ ["a2[9]()", "undefined is not a function (evaluated from 'a2[9]')"],
+ ["a2[9](\n )", "undefined is not a function (evaluated from 'a2[9]')"],
+ ["new C.x", "undefined is not a constructor (evaluated from 'C.x')"],
+ ["new C\n .x", "undefined is not a constructor (evaluated from 'C.x')"],
+ ];
+ for (const [source, message] of cases) expectMessage(source, message);
+});
+
+test("bases of member accesses", () => {
+ const cases = [
+ ["u.x", 'Cannot access property "x" on undefined object "u"'],
+ ["u\n .x", 'Cannot access property "x" on undefined object "u"'],
+ ["u.x.y", 'Cannot access property "x" on undefined object "u"'],
+ ["u\n .x\n .y", 'Cannot access property "x" on undefined object "u"'],
+ ['u["x"]', 'Cannot access property "x" on undefined object "u"'],
+ ["u[kg]", 'Cannot access property "g" on undefined object "u"'],
+ ["u.x = 1", 'Cannot access property "x" on undefined object "u"'],
+ ["u\n .x\n =\n 1", 'Cannot access property "x" on undefined object "u"'],
+ ['u["x"] = 1', 'Cannot access property "x" on undefined object "u"'],
+ ['u["x"]\n =\n 1', 'Cannot access property "x" on undefined object "u"'],
+ ["u[kg] = 1", 'Cannot access property "g" on undefined object "u"'],
+ ["u[kg]\n =\n 1", 'Cannot access property "g" on undefined object "u"'],
+ ["u.x += 1", 'Cannot access property "x" on undefined object "u"'],
+ ["u\n .x += 1", 'Cannot access property "x" on undefined object "u"'],
+ ["u.x++", 'Cannot access property "x" on undefined object "u"'],
+ ["u\n .x++", 'Cannot access property "x" on undefined object "u"'],
+ ["u.x()", 'Cannot access property "x" on undefined object "u"'],
+ ["u\n .x(\n )", 'Cannot access property "x" on undefined object "u"'],
+ ["o.nope.x", 'Cannot access property "x" on undefined object "o.nope"'],
+ ["o\n .nope\n .x", 'Cannot access property "x" on undefined object "o.nope"'],
+ ["o.nope.x()", 'Cannot access property "x" on undefined object "o.nope"'],
+ ["o\n .nope\n .x(\n )", 'Cannot access property "x" on undefined object "o.nope"'],
+ ["o.m().nope.x", 'Cannot access property "x" on undefined object ".nope"'],
+ ["o\n .m(\n )\n .nope\n .x", 'Cannot access property "x" on undefined object ".nope"'],
+ ["o.m().nope.x = 1", 'Cannot access property "x" on undefined object ".nope"'],
+ ["o\n .m(\n )\n .nope\n .x\n =\n 1", 'Cannot access property "x" on undefined object ".nope"'],
+ ["o.nope.x = 1", 'Cannot access property "x" on undefined object "o.nope"'],
+ ["o\n .nope\n .x\n =\n 1", 'Cannot access property "x" on undefined object "o.nope"'],
+ ["o.nope[kg] = 1", 'Cannot access property "g" on undefined object "o.nope"'],
+ ["o\n .nope[kg]\n =\n 1", 'Cannot access property "g" on undefined object "o.nope"'],
+ ["o[nk].x", 'Cannot access property "x" on undefined object "o[nk]"'],
+ ["o[nk]\n .x", 'Cannot access property "x" on undefined object "o[nk]"'],
+ ["o[nk].x = 1", 'Cannot access property "x" on undefined object "o[nk]"'],
+ ["o[nk]\n .x\n =\n 1", 'Cannot access property "x" on undefined object "o[nk]"'],
+ ["o?.nope.x", 'Cannot access property "x" on undefined object'],
+ ["o?.nope\n .x", 'Cannot access property "x" on undefined object'],
+ ["(function () {})().nope()", 'Cannot access property "nope" on undefined object'],
+ ["(\n function (\n ) {})()\n .nope()", 'Cannot access property "nope" on undefined object'],
+ ["tag`x`.nope()", 'Cannot access property "nope" on undefined object'],
+ ["tag`x`.nope(\n )", 'Cannot access property "nope" on undefined object'],
+ ["null.nope()", 'Cannot access property "nope" on null object'],
+ ["null\n .nope(\n )", 'Cannot access property "nope" on null object'],
+ ["new o.K().o.nope()", 'Cannot access property "nope" on undefined object ".o"'],
+ ["new o\n .K(\n )\n .o\n .nope(\n )", 'Cannot access property "nope" on undefined object ".o"'],
+ ["f0().nope()", 'Cannot access property "nope" on undefined object'],
+ ["f0(\n )\n .nope(\n )", 'Cannot access property "nope" on undefined object'],
+ ["f0()[kg]()", 'Cannot access property "g" on undefined object'],
+ ["f0(\n )[kg](\n )", 'Cannot access property "g" on undefined object'],
+ ["f0().x", 'Cannot access property "x" on undefined object'],
+ ["f0(\n )\n .x", 'Cannot access property "x" on undefined object'],
+ ["f0().x = 1", 'Cannot access property "x" on undefined object'],
+ ["f0(\n )\n .x\n =\n 1", 'Cannot access property "x" on undefined object'],
+ ["f0().x.y", 'Cannot access property "x" on undefined object'],
+ ["f0(\n )\n .x\n .y", 'Cannot access property "x" on undefined object'],
+ ["a2[nk].nope()", 'Cannot access property "nope" on undefined object "a2[nk]"'],
+ ["a2[nk]\n .nope(\n )", 'Cannot access property "nope" on undefined object "a2[nk]"'],
+ ["f0(1, 2).nope()", 'Cannot access property "nope" on undefined object'],
+ ["f0(\n 1, 2)\n .nope(\n )", 'Cannot access property "nope" on undefined object'],
+ [
+ "class S4 extends K0 { m() { super.nope.x } } new S4().m()",
+ 'Cannot access property "x" on undefined object ".nope"',
+ ],
+ [
+ "class S4 extends K0 { m(\n ) { super\n .nope\n .x } } new S4(\n )\n .m()",
+ 'Cannot access property "x" on undefined object ".nope"',
+ ],
+ [
+ "class S5 extends K0 { m() { super.nope.x() } } new S5().m()",
+ 'Cannot access property "x" on undefined object ".nope"',
+ ],
+ [
+ "class S5 extends K0 { m(\n ) { super\n .nope\n .x(\n ) } } new S5()\n .m()",
+ 'Cannot access property "x" on undefined object ".nope"',
+ ],
+ ["u.x`x`", 'Cannot access property "x" on undefined object "u"'],
+ ["u\n .x`x`", 'Cannot access property "x" on undefined object "u"'],
+ ["(o?.nope).x", 'Cannot access property "x" on undefined object'],
+ ["(\n o?.nope)\n .x", 'Cannot access property "x" on undefined object'],
+ ["(o?.nope).x = 1", 'Cannot access property "x" on undefined object'],
+ ["(\n o?.nope)\n .x\n =\n 1", 'Cannot access property "x" on undefined object'],
+ ["({x: u.y} = {})", 'Cannot access property "y" on undefined object'],
+ ["(\n {x: u\n .y}\n =\n {})", 'Cannot access property "y" on undefined object'],
+ ["[u.y] = [1]", 'Cannot access property "y" on undefined object'],
+ ["[u\n .y]\n =\n [1]", 'Cannot access property "y" on undefined object'],
+ ["for (u.x of [1]);", 'Cannot access property "x" on undefined object'],
+ ["for (\n u\n .x of [1]);", 'Cannot access property "x" on undefined object'],
+ ["for (u.x in {a: 1});", 'Cannot access property "x" on undefined object'],
+ ["for (\n u\n .x in {a: 1});", 'Cannot access property "x" on undefined object'],
+ ["u.x(...it)", 'Cannot access property "x" on undefined object "u"'],
+ ["u\n .x(\n ...it)", 'Cannot access property "x" on undefined object "u"'],
+ ["(1).x.y", 'Cannot access property "y" on undefined object "1.x"'],
+ ["(\n 1)\n .x\n .y", 'Cannot access property "y" on undefined object "1.x"'],
+ ['"s".x.y', 'Cannot access property "y" on undefined object "\'s\'.x"'],
+ ['"s".x\n .y', 'Cannot access property "y" on undefined object "\'s\'.x"'],
+ ["o.g.x.y.z", 'Cannot access property "y" on undefined object "o.g.x"'],
+ ["o\n .g\n .x\n .y\n .z", 'Cannot access property "y" on undefined object "o.g.x"'],
+ ["o.o.o.nope.x", 'Cannot access property "x" on undefined object "o.o.o.nope"'],
+ ["o\n .o\n .o\n .nope\n .x", 'Cannot access property "x" on undefined object "o.o.o.nope"'],
+ ["u.x?.y", 'Cannot access property "x" on undefined object "u"'],
+ ["u\n .x?.y", 'Cannot access property "x" on undefined object "u"'],
+ ["(u).x", 'Cannot access property "x" on undefined object "u"'],
+ ["(\n u)\n .x", 'Cannot access property "x" on undefined object "u"'],
+ ["(u.x)", 'Cannot access property "x" on undefined object "u"'],
+ ["(\n u\n .x)", 'Cannot access property "x" on undefined object "u"'],
+ ["(u).x = 1", 'Cannot access property "x" on undefined object "u"'],
+ ["(\n u)\n .x\n =\n 1", 'Cannot access property "x" on undefined object "u"'],
+ ["((u)).x", 'Cannot access property "x" on undefined object "u"'],
+ ["(\n (\n u))\n .x", 'Cannot access property "x" on undefined object "u"'],
+ ["(1, u).x", 'Cannot access property "x" on undefined object'],
+ ["(\n 1, u)\n .x", 'Cannot access property "x" on undefined object'],
+ ["(u || u).x", 'Cannot access property "x" on undefined object'],
+ ["(\n u || u)\n .x", 'Cannot access property "x" on undefined object'],
+ ["(u ? u : u).x", 'Cannot access property "x" on undefined object'],
+ ["(\n u ? u : u)\n .x", 'Cannot access property "x" on undefined object'],
+ ["(o.nope).x", 'Cannot access property "x" on undefined object "o.nope"'],
+ ["(\n o\n .nope)\n .x", 'Cannot access property "x" on undefined object "o.nope"'],
+ ["(o.m().nope).x", 'Cannot access property "x" on undefined object ".nope"'],
+ ["(\n o\n .m(\n )\n .nope)\n .x", 'Cannot access property "x" on undefined object ".nope"'],
+ ["(f0()).x", 'Cannot access property "x" on undefined object'],
+ ["(\n f0(\n ))\n .x", 'Cannot access property "x" on undefined object'],
+ ["(f0()).x = 1", 'Cannot access property "x" on undefined object'],
+ ["(\n f0(\n ))\n .x\n =\n 1", 'Cannot access property "x" on undefined object'],
+ ["(function () {})().x", 'Cannot access property "x" on undefined object'],
+ ["(\n function (\n ) {})()\n .x", 'Cannot access property "x" on undefined object'],
+ ["[][0].x", 'Cannot access property "x" on undefined object "[0]"'],
+ ["[][0]\n .x", 'Cannot access property "x" on undefined object "[0]"'],
+ ["[][0].x = 1", 'Cannot access property "x" on undefined object "[0]"'],
+ ["[][0]\n .x\n =\n 1", 'Cannot access property "x" on undefined object "[0]"'],
+ ["[u][0].x", 'Cannot access property "x" on undefined object "[0]"'],
+ ["[u][0]\n .x", 'Cannot access property "x" on undefined object "[0]"'],
+ ["({}).x.y", 'Cannot access property "y" on undefined object ".x"'],
+ ["(\n {})\n .x\n .y", 'Cannot access property "y" on undefined object ".x"'],
+ ['"s"[0].x.y', 'Cannot access property "y" on undefined object "\'s\'[0].x"'],
+ ['"s"[0]\n .x\n .y', 'Cannot access property "y" on undefined object "\'s\'[0].x"'],
+ ["1[0].x", 'Cannot access property "x" on undefined object "1[0]"'],
+ ["1[0]\n .x", 'Cannot access property "x" on undefined object "1[0]"'],
+ ['1["x"].y', 'Cannot access property "y" on undefined object "1[\'x\']"'],
+ ['1["x"]\n .y', 'Cannot access property "y" on undefined object "1[\'x\']"'],
+ ["a2[9].x", 'Cannot access property "x" on undefined object "a2[9]"'],
+ ["a2[9]\n .x", 'Cannot access property "x" on undefined object "a2[9]"'],
+ ["a2[9].x = 1", 'Cannot access property "x" on undefined object "a2[9]"'],
+ ["a2[9]\n .x\n =\n 1", 'Cannot access property "x" on undefined object "a2[9]"'],
+ ["a2[nk].x", 'Cannot access property "x" on undefined object "a2[nk]"'],
+ ["a2[nk]\n .x", 'Cannot access property "x" on undefined object "a2[nk]"'],
+ ["a2[i0 + 9].x", 'Cannot access property "x" on undefined object "a2"'],
+ ["a2[i0 + 9]\n .x", 'Cannot access property "x" on undefined object "a2"'],
+ ["a2[i0 + 9].x = 1", 'Cannot access property "x" on undefined object "a2"'],
+ ["a2[i0 + 9]\n .x\n =\n 1", 'Cannot access property "x" on undefined object "a2"'],
+ ["a2[f0()].x", 'Cannot access property "x" on undefined object "a2"'],
+ ["a2[f0(\n )]\n .x", 'Cannot access property "x" on undefined object "a2"'],
+ ["a2[f0()].x = 1", 'Cannot access property "x" on undefined object "a2"'],
+ ["a2[f0(\n )]\n .x\n =\n 1", 'Cannot access property "x" on undefined object "a2"'],
+ ['a2["z"].x', 'Cannot access property "x" on undefined object "a2[\'z\']"'],
+ ['a2["z"]\n .x', 'Cannot access property "x" on undefined object "a2[\'z\']"'],
+ ["a2['z'].x", 'Cannot access property "x" on undefined object "a2[\'z\']"'],
+ ["a2['z']\n .x", 'Cannot access property "x" on undefined object "a2[\'z\']"'],
+ ["a2[`z`].x", 'Cannot access property "x" on undefined object "a2"'],
+ ["a2[`z`]\n .x", 'Cannot access property "x" on undefined object "a2"'],
+ ["a2[this].x", 'Cannot access property "x" on undefined object "a2[this]"'],
+ ["a2[this]\n .x", 'Cannot access property "x" on undefined object "a2[this]"'],
+ ["this.u0.x", 'Cannot access property "x" on undefined object "this.u0"'],
+ ["this\n .u0\n .x", 'Cannot access property "x" on undefined object "this.u0"'],
+ ["new C().nope.x", 'Cannot access property "x" on undefined object ".nope"'],
+ ["new C(\n )\n .nope\n .x", 'Cannot access property "x" on undefined object ".nope"'],
+ ["new C().nope.x = 1", 'Cannot access property "x" on undefined object ".nope"'],
+ ["new C(\n )\n .nope\n .x\n =\n 1", 'Cannot access property "x" on undefined object ".nope"'],
+ ["new o.nope.x", 'Cannot access property "x" on undefined object "o.nope"'],
+ ["new o\n .nope\n .x", 'Cannot access property "x" on undefined object "o.nope"'],
+ ];
+ for (const [source, message] of cases) expectMessage(source, message);
+});
+
+test("references that are longer than what gets looked at", () => {
+ const long = "a".repeat(5000);
+ expect(new Function(`new '${long}'.nope();`)).toThrow(TypeError);
+ expect(new Function(`'${long}'.nope();`)).toThrow(TypeError);
+ expect(new Function(`var ${long} = {}; ${long}.nope();`)).toThrow(TypeError);
+ expect(new Function(`var ${long}; ${long}.nope = 1;`)).toThrow(TypeError);
+ expect(new Function(`[${long}].nope.x = 1; var ${long};`)).toThrow(TypeError);
+});
+
+test("source that looks like something else", () => {
+ expectMessage("o /* ) */ .nope();", "undefined is not a function (evaluated from 'o.nope')");
+ expectMessage("o // )\n .nope();", "undefined is not a function (evaluated from 'o.nope')");
+ expectMessage("o[')'].nope();", `Cannot access property "nope" on undefined object "o[')']"`);
+ expectMessage("o[']'].nope();", `Cannot access property "nope" on undefined object "o[']']"`);
+});
diff --git a/Tests/LibJS/Runtime/regress/bytecode-generator-operand-lifetimes.js b/Tests/LibJS/Runtime/regress/bytecode-generator-operand-lifetimes.js
index ef650932a5a..5d3bb0db865 100644
--- a/Tests/LibJS/Runtime/regress/bytecode-generator-operand-lifetimes.js
+++ b/Tests/LibJS/Runtime/regress/bytecode-generator-operand-lifetimes.js
@@ -133,4 +133,32 @@ describe("bytecode generator operand lifetime regressions", () => {
expect(bindingPattern.call(receiver)).toEqual([receiver, 1]);
expect(classElement.call(receiver)).toEqual([receiver, true]);
});
+
+ test("a destructuring assignment evaluates to the value it started with", () => {
+ function objectPattern() {
+ const source = { a: 1 };
+ let value = source;
+ const result = ({ a: value } = value);
+ return [result === source, value];
+ }
+
+ function arrayPattern() {
+ const source = [1];
+ let value = source;
+ const result = ([value] = value);
+ return [result === source, value];
+ }
+
+ function computedKey() {
+ const source = { a: 1 };
+ let value = source;
+ let target;
+ const result = ({ [((value = null), "a")]: target } = value);
+ return [result === source, target];
+ }
+
+ expect(objectPattern()).toEqual([true, 1]);
+ expect(arrayPattern()).toEqual([true, 1]);
+ expect(computedKey()).toEqual([true, 1]);
+ });
});
diff --git a/Tests/LibJS/Runtime/source-positions-of-errors.js b/Tests/LibJS/Runtime/source-positions-of-errors.js
new file mode 100644
index 00000000000..3ae31608a8c
--- /dev/null
+++ b/Tests/LibJS/Runtime/source-positions-of-errors.js
@@ -0,0 +1,202 @@
+// Each source has an @ where the instruction that matters is.
+function positionOfMarker(source) {
+ const before = source.slice(0, source.indexOf("@")).split("\n");
+ // NB: The function around the source starts two lines above it.
+ return [before.length + 2, before[before.length - 1].length + 1];
+}
+
+function positionInStack(stack) {
+ const frame = stack.split("\n").find(line => line.includes("at anonymous"));
+ const match = frame.match(/(\d+):(\d+)\)?$/);
+ return [Number(match[1]), Number(match[2])];
+}
+
+function positionSeenByProbe(source) {
+ let position = null;
+ const probe = () => {
+ position ??= positionInStack(new Error().stack);
+ };
+ const object = {
+ get getter() {
+ probe();
+ return 1;
+ },
+ set setter(value) {
+ probe();
+ },
+ get callable() {
+ probe();
+ return () => {};
+ },
+ method() {
+ probe();
+ },
+ };
+ object.object = object;
+ const value = {
+ toString() {
+ probe();
+ return "";
+ },
+ };
+ const iterable = {
+ [Symbol.iterator]() {
+ probe();
+ return { next: () => ({ done: true }) };
+ },
+ };
+ const proxy = new Proxy(
+ {},
+ {
+ ownKeys() {
+ probe();
+ return [];
+ },
+ has(target, key) {
+ if (key !== Symbol.unscopables) probe();
+ return true;
+ },
+ get: () => () => {},
+ }
+ );
+ new Function("object", "value", "iterable", "proxy", "call", "Class", "key", source.replace("@", ""))(
+ object,
+ value,
+ iterable,
+ proxy,
+ () => probe(),
+ function () {
+ probe();
+ },
+ "setter"
+ );
+ return position;
+}
+
+function expectProbePositions(sources) {
+ for (const source of sources)
+ expect([source, positionSeenByProbe(source)]).toEqual([source, positionOfMarker(source)]);
+}
+
+function positionOfError(source) {
+ const u = undefined;
+ const object = {};
+ try {
+ new Function("u", "object", "key", source.replace("@", ""))(u, object, "key");
+ } catch (error) {
+ return positionInStack(error.stack);
+ }
+ return null;
+}
+
+function expectErrorPositions(sources) {
+ for (const source of sources) expect([source, positionOfError(source)]).toEqual([source, positionOfMarker(source)]);
+}
+
+test("stores are where their operator is", () => {
+ expectProbePositions([
+ "object.setter @= 1;",
+ "object.object.setter @= 1;",
+ 'object["setter"] @= 1;',
+ "object[key] @= 1;",
+ "(object).setter @= 1;",
+ "object\n .setter\n @= 1;",
+ "object.setter @+= 1;",
+ "object[key] @+= 1;",
+ "object.setter @||= 1;",
+ "object.setter @??= 1;",
+ "object.setter@++;",
+ "object.setter@--;",
+ "object[key]@++;",
+ "@++object.setter;",
+ "@--object[key];",
+ ]);
+});
+
+test("stores of patterns are where the assignment is", () => {
+ expectProbePositions([
+ "[object.setter] @= [1];",
+ "({ a: object.setter } @= { a: 1 });",
+ "[object.setter = 1] @= [];",
+ "[...object.setter] @= [];",
+ ]);
+});
+
+test("stores of loop heads are where the keyword is", () => {
+ expectProbePositions(["for (object.setter @of [1]);", "for (object.setter @in { a: 1 });"]);
+});
+
+test("calls are where their arguments start", () => {
+ expectProbePositions([
+ "call@();",
+ "object.method@();",
+ 'object["method"]@();',
+ "object\n .method@();",
+ "(object.method)@();",
+ "@new Class();",
+ "@new Class;",
+ ]);
+});
+
+test("reading what gets called is where the call is", () => {
+ expectProbePositions(["object.callable@();", "object\n .callable\n @();"]);
+});
+
+test("member accesses are where their operator is", () => {
+ expectProbePositions([
+ "object\n @.getter;",
+ 'object@["getter"];',
+ "object.object@['getter'];",
+ ]);
+});
+
+test("everything in an optional chain is where the chain starts", () => {
+ expectProbePositions(["object@?.getter;", "object@?.object.getter;", "object@?.method();", "object.method@?.();"]);
+});
+
+test("iteration of a spread element is where what it is in is", () => {
+ expectProbePositions(["@[...iterable];", "@[1, ...iterable];", "call@(...iterable);", "@new Class(...iterable);"]);
+});
+
+test("patterns of declarations are where the declaration is", () => {
+ expectProbePositions([
+ "@var [a] = iterable;",
+ "@let [a] = iterable;",
+ "@const { getter } = object;",
+ "for (var a @of iterable);",
+ "@try { throw object; } catch ({ getter }) {}",
+ ]);
+});
+
+test("other constructs", () => {
+ expectProbePositions([
+ "@`${value}`;",
+ "(@{ ...proxy });",
+ "with (proxy) { missing@(); }",
+ "with (proxy) { missing @= 1; }",
+ "with (proxy) { @typeof missing; }",
+ "with (proxy) { @delete missing; }",
+ ]);
+});
+
+test("errors", () => {
+ expectErrorPositions([
+ "u@[key];",
+ "u.x @= 1;",
+ "u[key] @= 1;",
+ "u.x @+= 1;",
+ "u.x@++;",
+ "@++u.x;",
+ "u.x@();",
+ "object.missing@();",
+ "object.missing.x @= 1;",
+ "@new u();",
+ "@class C extends u {}",
+ "@with (u) {}",
+ "typeof @tdz; let tdz;",
+ ]);
+});
diff --git a/Tests/LibJS/Runtime/syntax-error-messages.js b/Tests/LibJS/Runtime/syntax-error-messages.js
new file mode 100644
index 00000000000..cb0ea0365c5
--- /dev/null
+++ b/Tests/LibJS/Runtime/syntax-error-messages.js
@@ -0,0 +1,35 @@
+describe("syntax error messages", () => {
+ function expectMessage(source, message) {
+ expect(source).not.toEval();
+ expect(() => eval(source)).toThrowWithMessage(SyntaxError, message);
+ }
+
+ test("name the unexpected token as the source spells it", () => {
+ expectMessage("let x = ;", "Unexpected token ';'. Expected primary expression");
+ expectMessage("x y", "Unexpected token 'y'. Expected ';'");
+ expectMessage("if (1) )", "Unexpected token ')'. Expected statement");
+ });
+
+ test("name the end of the input", () => {
+ expectMessage("if (x) { y", "Unexpected end of input. Expected '}'");
+ expectMessage("(", "Unexpected end of input");
+ });
+
+ test("name both ways a list can go on", () => {
+ expectMessage("foo(1, 2", "Unexpected end of input. Expected ',' or ')'");
+ expectMessage("function f(a b) {}", "Unexpected token 'b'. Expected ',' or ')'");
+ expectMessage("[1 2]", "Unexpected token '2'. Expected ',' or ']'");
+ expectMessage("({ a: 1 b: 2 })", "Unexpected token 'b'. Expected ',' or '}'");
+ });
+
+ test("cut long tokens short", () => {
+ const name = "a".repeat(100);
+ expectMessage(`x ${name}`, `Unexpected token '${"a".repeat(40)}...'. Expected ';'`);
+ });
+
+ test("unterminated literals", () => {
+ expectMessage('"abc', "Unterminated string literal");
+ expectMessage("`abc", "Unterminated template literal");
+ expectMessage("/abc", "Unterminated regular expression literal");
+ });
+});
diff --git a/Tests/LibJS/Runtime/syntax/latin1-source.js b/Tests/LibJS/Runtime/syntax/latin1-source.js
new file mode 100644
index 00000000000..0165b7e8bd0
--- /dev/null
+++ b/Tests/LibJS/Runtime/syntax/latin1-source.js
@@ -0,0 +1,63 @@
+// NB: This file and the code handed to eval() below have one-byte storage, which the parser reads as it is.
+
+function fonctionÉté(paramètre, àvec) {
+ return paramètre + àvec;
+}
+
+class Élément {
+ #privé = 1;
+ get privé() {
+ return this.#privé;
+ }
+}
+
+test("identifiers with Latin-1 letters", () => {
+ var café = 1;
+ const ñandú = { clé: 2, clé2: 3 };
+ expect(fonctionÉté(café, ñandú.clé)).toBe(3);
+ expect(ñandú.clé2).toBe(3);
+ expect(fonctionÉté.name).toBe("fonctionÉté");
+ expect(new Élément().privé).toBe(1);
+ expect(Object.keys(ñandú)).toEqual(["clé", "clé2"]);
+});
+
+test("escapes and Latin-1 letters spell the same identifier", () => {
+ var éa = 1;
+ expect(éa).toBe(1);
+ var aé = 2;
+ expect(aé).toBe(2);
+});
+
+test("string, template and regular expression literals", () => {
+ const value = "héllo\xE9";
+ expect(value.length).toBe(6);
+ expect(value.charCodeAt(1)).toBe(0xe9);
+ expect(value.charCodeAt(5)).toBe(0xe9);
+ expect(`ÿ${value}þ`.length).toBe(8);
+ expect(String.raw`é\n`.length).toBe(3);
+ expect(/caf[é-ÿ]/.test("café")).toBeTrue();
+ expect(/caf[é-ÿ]/.source).toBe("caf[é-ÿ]");
+});
+
+test("no-break space is whitespace, and the multiplication sign and U+0085 are neither names nor whitespace", () => {
+ expect(eval("1 + 1")).toBe(2);
+ expect(() => eval("var a×b;")).toThrow(SyntaxError);
+ expect(() => eval("1\u0085")).toThrow(SyntaxError);
+});
+
+test("source offsets count code units", () => {
+ const code = "/* éééé */ (function é(à) { return 'é' + à; })";
+ const value = eval(code);
+ expect(value.toString()).toBe("function é(à) { return 'é' + à; }");
+ expect(value("è")).toBe("éè");
+});
+
+test("error positions count code units", () => {
+ let message = "";
+ try {
+ eval("/* éééé */ @");
+ } catch (error) {
+ message = error.message;
+ }
+ expect(message.includes("column: 12")).toBeTrue();
+});
diff --git a/Tests/LibJS/Runtime/syntax/lazy-compilation.js b/Tests/LibJS/Runtime/syntax/lazy-compilation.js
new file mode 100644
index 00000000000..cbfbb8d739e
--- /dev/null
+++ b/Tests/LibJS/Runtime/syntax/lazy-compilation.js
@@ -0,0 +1,227 @@
+// NB: Functions get parsed again on their first call, on their own, from what the first parse of the source recorded.
+
+test("early errors in functions that never run are reported right away", () => {
+ expect(() => eval("function outer() { function inner() { let a; let a; } }")).toThrow(SyntaxError);
+ expect(() => eval("function outer() { return () => { break; }; }")).toThrow(SyntaxError);
+ expect(() => eval("class C { method() { this.#missing; } }")).toThrow(SyntaxError);
+ expect(() => new Function("function inner(a = 1) { 'use strict'; }")).toThrow(SyntaxError);
+ expect(() => eval("function outer() { function inner() { return 1 +; } }")).toThrow(SyntaxError);
+});
+
+test("source text of functions that never ran", () => {
+ function outer(a, b = () => a) {
+ return function inner() {
+ return a;
+ };
+ }
+ class C {
+ field = () => 1;
+ method(a) {
+ return a;
+ }
+ static block() {}
+ }
+ expect(outer.toString().includes("function outer(a, b = () => a)")).toBeTrue();
+ expect(outer(1).toString().includes("function inner()")).toBeTrue();
+ expect(new C().field.toString()).toBe("() => 1");
+ expect(C.prototype.method.toString().includes("method(a)")).toBeTrue();
+ expect(C.block.toString()).toBe("block() {}");
+ expect(C.toString().includes("class C")).toBeTrue();
+});
+
+test("functions in the parameters of arrow functions", () => {
+ function outer() {
+ const first = (
+ a = function () {
+ return 1;
+ },
+ b = () => 2
+ ) => a() + b();
+ const second = ({ c = () => 3 }, d = async () => 4) => c();
+ return first() + second({});
+ }
+ expect(outer()).toBe(6);
+});
+
+test("functions at the very end of a source", () => {
+ expect(eval("(function () { return 1; })")()).toBe(1);
+ expect(eval("x => x + 1")(1)).toBe(2);
+ expect(eval("() => 1")()).toBe(1);
+ expect(eval("async () => 1")()).toBeInstanceOf(Promise);
+ expect(eval("(class { value = 2 })").name).toBe("");
+ expect(new (eval("(class { value = 2 })"))().value).toBe(2);
+ expect(new (eval("(class extends Array {})"))()).toBeInstanceOf(Array);
+ expect(eval("(class { static value = 3; static { this.other = 4; } })").other).toBe(4);
+ expect(eval("/* a long way to go */ (a, b) => a + b // and some more\n ")(1, 2)).toBe(3);
+});
+
+test("names of the code around a function", () => {
+ var captured = 1;
+ let outerLet = 2;
+ const outerConst = 3;
+ function first() {
+ function second() {
+ function third() {
+ captured++;
+ return captured + outerLet + outerConst;
+ }
+ return third();
+ }
+ return second();
+ }
+ expect(first()).toBe(7);
+ expect(captured).toBe(2);
+
+ function constAssignment() {
+ return () => {
+ outerConst = 1;
+ };
+ }
+ expect(constAssignment()).toThrow(TypeError);
+});
+
+test("functions in default parameters", () => {
+ function outer(
+ a = () => b,
+ b = 2,
+ c = function () {
+ return () => a() + b;
+ }
+ ) {
+ var b = 10;
+ return [a(), c()(), b];
+ }
+ expect(outer()).toEqual([2, 4, 10]);
+
+ let nested = (a = (b = (c = () => 3) => c()) => b()) => a();
+ expect(nested()).toBe(3);
+});
+
+test("arrow functions take what they use from the function around them", () => {
+ function outer() {
+ const read = () => [this.value, arguments[0], new.target];
+ return () => read();
+ }
+ expect(outer.call({ value: 1 }, 2)()).toEqual([1, 2, undefined]);
+
+ class Base {
+ value() {
+ return 1;
+ }
+ }
+ class Derived extends Base {
+ constructor() {
+ const init = () => super();
+ init();
+ }
+ value() {
+ return (() => super.value() + 1)();
+ }
+ }
+ expect(new Derived().value()).toBe(2);
+});
+
+test("eval and with around a function keep names from being what they look like", () => {
+ function sloppy() {
+ eval("var injected = 1");
+ function inner() {
+ return injected;
+ }
+ return inner();
+ }
+ expect(sloppy()).toBe(1);
+
+ const object = { value: 1 };
+ const code = "with (object) { var read = function () { return value; }; } read";
+ expect(eval(code)()).toBe(1);
+
+ function parameterEval(before = () => injectedInParameters, after = (eval("var injectedInParameters = 2"), 0)) {
+ return before();
+ }
+ expect(parameterEval()).toBe(2);
+});
+
+test("the code of a class", () => {
+ let counter = 0;
+ const key = "computed";
+ class C {
+ #secret = 1;
+ field = ++counter;
+ [key] = this.#secret + 1;
+ anonymous = function () {};
+ arrow = () => this;
+ static staticField = "static";
+ static {
+ this.fromBlock = this.staticField + counter;
+ let local = 1;
+ this.closure = () => local++;
+ }
+ reveal() {
+ return this.#secret;
+ }
+ }
+ const instance = new C();
+ expect(instance.field).toBe(1);
+ expect(instance.computed).toBe(2);
+ expect(instance.anonymous.name).toBe("anonymous");
+ expect(instance.arrow()).toBe(instance);
+ expect(instance.reveal()).toBe(1);
+ expect(C.fromBlock).toBe("static0");
+ expect(C.closure()).toBe(1);
+ expect(C.closure()).toBe(2);
+ expect(new C().field).toBe(2);
+});
+
+test("named function expressions and block functions", () => {
+ const factorial = function self(n) {
+ return n <= 1 ? 1 : n * self(n - 1);
+ };
+ expect(factorial(4)).toBe(24);
+
+ const shadowed = function self() {
+ var self = 1;
+ return self;
+ };
+ expect(shadowed()).toBe(1);
+
+ function annexB() {
+ {
+ function hoisted() {
+ return 1;
+ }
+ }
+ return () => hoisted();
+ }
+ expect(annexB()()).toBe(1);
+});
+
+test("generators and async functions", () => {
+ function* generator(a) {
+ const inner = () => a;
+ yield inner();
+ yield* [2];
+ }
+ expect([...generator(1)]).toEqual([1, 2]);
+
+ async function asyncFunction() {
+ return await (async () => 1)();
+ }
+ expect(asyncFunction()).toBeInstanceOf(Promise);
+});
+
+test("a long chain of operators takes no stack to generate", () => {
+ const long = new Function("return " + "1+".repeat(500000) + "1");
+ expect(long()).toBe(500001);
+});
+
+test("code too deep for the stack that is left compiles once there is enough of it", () => {
+ const deep = new Function("return " + "(".repeat(200) + "1" + ")".repeat(200));
+ function atTheEndOfTheStack() {
+ try {
+ return atTheEndOfTheStack();
+ } catch (error) {
+ return deep();
+ }
+ }
+ expect(atTheEndOfTheStack()).toBe(1);
+});
diff --git a/Tests/LibJS/Runtime/syntax/optional-chaining.js b/Tests/LibJS/Runtime/syntax/optional-chaining.js
index c5d55364c3d..fd1aee1ed4b 100644
--- a/Tests/LibJS/Runtime/syntax/optional-chaining.js
+++ b/Tests/LibJS/Runtime/syntax/optional-chaining.js
@@ -52,3 +52,11 @@ test("delete optional-chaining property references", () => {
expect(delete { inner: null }?.inner?.value).toBeTrue();
});
+
+test("delete of an optional chain", () => {
+ function deleteAll(object) {
+ return [delete object?.x, object, delete object?.["y"], delete object?.z.w];
+ }
+ expect(deleteAll({ x: 1, y: 2, z: { w: 3 } })).toEqual([true, { z: {} }, true, true]);
+ expect(deleteAll(null)).toEqual([true, null, true, true]);
+});
diff --git a/Tests/LibJS/Runtime/top-level-patterns.js b/Tests/LibJS/Runtime/top-level-patterns.js
new file mode 100644
index 00000000000..b2ca7f25ab4
--- /dev/null
+++ b/Tests/LibJS/Runtime/top-level-patterns.js
@@ -0,0 +1,11 @@
+let [first, second = 2] = [1];
+const { third, ...others } = { third: 3, fourth: 4 };
+var [fifth] = [5];
+
+test("patterns in declarations of the top level", () => {
+ expect(first).toBe(1);
+ expect(second).toBe(2);
+ expect(third).toBe(3);
+ expect(others).toEqual({ fourth: 4 });
+ expect(fifth).toBe(5);
+});
diff --git a/Tests/LibJS/Runtime/try-catch-finally.js b/Tests/LibJS/Runtime/try-catch-finally.js
index 3b24393a0ea..ab449ed7adb 100644
--- a/Tests/LibJS/Runtime/try-catch-finally.js
+++ b/Tests/LibJS/Runtime/try-catch-finally.js
@@ -214,3 +214,55 @@ test("var declaration named like the catch parameter leaves the function binding
}
expect(captured()).toBeUndefined();
});
+
+describe("names of a catch parameter's binding pattern are uninitialized until they are bound", () => {
+ function caughtName(thrown, handler) {
+ try {
+ handler(thrown);
+ } catch (error) {
+ return error.name;
+ }
+ return "nothing";
+ }
+
+ test("read by an initializer", () => {
+ expect(
+ caughtName({}, value => {
+ try {
+ throw value;
+ } catch ({ a = b, b }) {}
+ })
+ ).toBe("ReferenceError");
+ expect(
+ caughtName([], value => {
+ try {
+ throw value;
+ } catch ([a = b, b]) {}
+ })
+ ).toBe("ReferenceError");
+ });
+
+ test("read by an initializer on each iteration of a loop", () => {
+ const results = [];
+ for (let i = 0; i < 2; i++) {
+ try {
+ try {
+ throw { b: i === 0 ? undefined : 1 };
+ } catch ({ a = i === 0 ? 0 : b, b }) {
+ results.push(a);
+ }
+ } catch (error) {
+ results.push(error.name);
+ }
+ }
+ expect(results).toEqual([0, "ReferenceError"]);
+ });
+
+ test("read once they are bound", () => {
+ try {
+ throw { a: 1 };
+ } catch ({ a, b = a }) {
+ expect(b).toBe(1);
+ }
+ });
+});