Skip to content

Truly independent web browser

8.2 KB
Raw Blame
/*
 * Copyright (c) 2026-present, the Ladybird developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

//! Writes a #[repr(C)] view of every bytecode instruction, laid out as flapc lays it out, and the Values record of
//! every instruction whose slow path receives one. Each offset flapc computed is asserted on the generated type.

use std::collections::BTreeSet;
use std::fmt::Write;

use flapc::metadata::{InstructionDefinition, SlowPathLayout, field_type_info};
use flapc::rust_bytecode::scaled;

const RUST_KEYWORDS: &[&str] = &[
    "abstract", "as", "async", "await", "become", "box", "break", "const", "continue", "do", "dyn", "else", "enum",
    "extern", "false", "final", "fn", "for", "gen", "if", "impl", "in", "let", "loop", "macro", "match", "mod", "move",
    "mut", "override", "priv", "pub", "ref", "return", "static", "struct", "trait", "true", "try", "type", "typeof",
    "unsafe", "unsized", "use", "virtual", "where", "while", "yield",
];

pub fn rust_identifier(name: &str) -> String {
    if RUST_KEYWORDS.contains(&name) {
        format!("r#{name}")
    } else {
        name.to_string()
    }
}

/// The Rust name of a bytecode field, without the m_ prefix of its name in the instruction definitions.
pub fn field_name(name: &str) -> String {
    rust_identifier(name.strip_prefix("m_").unwrap_or(name))
}

fn rust_type(ty: &str) -> String {
    match ty {
        "Operand" => "Operand".to_string(),
        "Optional<Operand>" => "OptionalOperand".to_string(),
        "Label" => "Label".to_string(),
        "Optional<Label>" => "OptionalLabel".to_string(),
        "IdentifierTableIndex" | "PropertyKeyTableIndex" | "StringTableIndex" => ty.to_string(),
        "Optional<IdentifierTableIndex>" => "OptionalIndex<IdentifierTableIndex>".to_string(),
        "Optional<StringTableIndex>" => "OptionalIndex<StringTableIndex>".to_string(),
        "EnvironmentCoordinate" => "BytecodeEnvironmentCoordinate".to_string(),
        "Value" => "Value".to_string(),
        "Builtin" => "u8".to_string(),
        _ => {
            let info = field_type_info(ty);
            match info.kind {
                "bool" | "u8" | "u16" | "i32" | "u32" | "u64" => info.kind.to_string(),
                "byte_count" => "u8".to_string(),
                "cache_index" => "u16".to_string(),
                other => panic!("no Rust view for bytecode field type {ty} ({other})"),
            }
        }
    }
}

pub fn generate(ops: &[InstructionDefinition], ops_with_values: &BTreeSet<String>) -> String {
    let mut out = String::new();
    out.push_str("// Generated by the libjs_rust build script -- DO NOT EDIT\n\n");

    for op in ops {
        if op.name == "Instruction" {
            continue;
        }
        let _ = writeln!(
            out,
            "#[repr(C, packed)]\npub struct {} {{\n    pub header: InstructionHeader,",
            op.name
        );
        let mut assertions = String::new();
        for field in &op.fields {
            if field.name == "m_type" || field.name == "m_strict" {
                continue;
            }
            let name = field_name(&field.name);
            let ty = rust_type(&field.ty);
            if field.is_array {
                let _ = writeln!(out, "    pub {name}: [{ty}; 0],");
            } else {
                let _ = writeln!(out, "    pub {name}: {ty},");
            }
            let offset = op.layout.field_offsets[&field.name];
            let _ = writeln!(
                assertions,
                "const _: () = assert!(core::mem::offset_of!({}, {name}) == {offset});",
                op.name
            );
        }
        // NB: Only bytecode holds instructions, so nothing outside this module can make one.
        out.push_str("    _view_of_bytecode: (),\n}\n");
        out.push_str(&assertions);
        let _ = writeln!(
            out,
            "// SAFETY: The struct lays out the instruction of this opcode, and is only ever a view of bytecode.\nunsafe impl super::BytecodeOp for {name} {{\n    const OPCODE: u8 = crate::bytecode::instruction::OpCode::{name} as u8;\n\n    fn length(&self) -> u32 {{\n        {name}::length(self)\n    }}\n}}",
            name = op.name
        );
        if let Some(array) = &op.array {
            let array_field = &op.fields[array.field_index];
            let count_field = field_name(&op.fields[array.count_field_index].name);
            let name = field_name(&array_field.name);
            let ty = rust_type(&array_field.ty);
            let accessor = if ty == "Value" {
                format!(
                    "impl {op_name} {{\n    /// The elements the instruction holds after its fixed fields, within the length it records.\n    pub fn {name}(&self) -> impl ExactSizeIterator<Item = Value> + '_ {{\n        let count = self.{count_field} as usize;\n        assert!(core::mem::offset_of!({op_name}, {name}) + count * size_of::<Value>() <= self.length() as usize);\n        let elements = core::ptr::addr_of!(self.{name}).cast::<Value>();\n        // SAFETY: The instruction is a view of bytecode that holds the length it records, which the elements are\n        //         within. They can be unaligned, so they are read as such.\n        (0..count).map(move |index| unsafe {{ elements.add(index).read_unaligned() }})\n    }}\n}}",
                    op_name = op.name
                )
            } else {
                format!(
                    "impl {op_name} {{\n    /// The elements the instruction holds after its fixed fields, within the length it records.\n    pub fn {name}(&self) -> &[{ty}] {{\n        let count = self.{count_field} as usize;\n        assert!(core::mem::offset_of!({op_name}, {name}) + count * size_of::<{ty}>() <= self.length() as usize);\n        // SAFETY: The instruction is a view of bytecode that holds the length it records, which the elements are\n        //         within. {ty} has an alignment of 1.\n        unsafe {{ ak::slice_from_raw_parts(core::ptr::addr_of!(self.{name}).cast::<{ty}>(), count) }}\n    }}\n}}",
                    op_name = op.name
                )
            };
            out.push_str(&accessor);
            out.push('\n');
        }
        match (op.layout.size, &op.array) {
            (Some(size), _) => {
                let _ = writeln!(
                    out,
                    "impl {} {{\n    /// The size of every {} instruction in the bytecode.\n    pub const LENGTH: u32 = {size};\n\n    pub fn length(&self) -> u32 {{\n        Self::LENGTH\n    }}\n}}",
                    op.name, op.name
                );
            }
            (None, Some(array)) => {
                let count_field = &op.fields[array.count_field_index];
                let count_name = field_name(&count_field.name);
                let count = if rust_type(&count_field.ty) == "u32" {
                    format!("self.{count_name}")
                } else {
                    format!("u32::from(self.{count_name})")
                };
                let _ = writeln!(
                    out,
                    "impl {} {{\n    /// The instruction's size in the bytecode.\n    pub fn length(&self) -> u32 {{\n        let count = {count};\n        {} + {}\n    }}\n}}",
                    op.name,
                    op.layout.minimum_size,
                    scaled("count", array.element_size)
                );
            }
            (None, None) => panic!("{} has neither a fixed size nor a count field", op.name),
        }

        if ops_with_values.contains(&op.name) {
            let layout = SlowPathLayout::new(op);
            let _ = writeln!(out, "#[repr(C)]\npub struct {}Values {{", op.name);
            let mut assertions = String::new();
            for field in &layout.fields {
                let name = field_name(&field.name);
                let _ = writeln!(out, "    pub {name}: Value,");
                let _ = writeln!(
                    assertions,
                    "const _: () = assert!(core::mem::offset_of!({}Values, {name}) == {});",
                    op.name, field.value_offset
                );
            }
            if let Some(array) = &layout.array {
                let _ = writeln!(out, "    pub {}: [Value; 0],", field_name(&array.name));
            }
            out.push_str("}\n");
            out.push_str(&assertions);
        }
        out.push('\n');
    }
    out
}