Skip to content

Truly independent web browser

LibWeb: Generate the WebGL command vocabulary and constants in Rust

Aliaksandr Kalenik341e31ae5246
diff --git a/Cargo.lock b/Cargo.lock
index b3bc7f460b5..7f7a17a6926 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -980,6 +980,7 @@ dependencies = [
"liburl_rust",
"libweb_rust",
"rustc-demangle",
+ "serde_json",
]
[[package]]
diff --git a/Libraries/LibWeb/Bindings/Rust/Cargo.toml b/Libraries/LibWeb/Bindings/Rust/Cargo.toml
index 1220e7dc07d..bc56be3bf49 100644
--- a/Libraries/LibWeb/Bindings/Rust/Cargo.toml
+++ b/Libraries/LibWeb/Bindings/Rust/Cargo.toml
@@ -26,5 +26,11 @@ liburl_rust = { path = "../../../LibURL/Rust", default-features = false }
libweb_rust = { path = "../../Rust" }
rustc-demangle = "0.1"
+[build-dependencies]
+serde_json = { version = "1", features = ["float_roundtrip", "preserve_order"] }
+
+[dev-dependencies]
+serde_json = { version = "1", features = ["float_roundtrip", "preserve_order"] }
+
[lints]
workspace = true
diff --git a/Libraries/LibWeb/Bindings/Rust/build.rs b/Libraries/LibWeb/Bindings/Rust/build.rs
index 09be68dd504..a36a286c6b5 100644
--- a/Libraries/LibWeb/Bindings/Rust/build.rs
+++ b/Libraries/LibWeb/Bindings/Rust/build.rs
@@ -9,12 +9,83 @@
//! LIBWEB_RUST_BINDINGS (Libraries/LibWeb/CMakeLists.txt). Building the crate on its own, as cargo test and cargo
//! clippy do, leaves the bindings out and compiles the implementations without them. rustc tracks the file itself, as
//! the crate includes it.
+//!
+//! Also generates what the WebGL implementation shares with the rest of the tree: the vocabulary of the command
+//! stream and the GL constants. Those do not need the bindings, so every build of the crate has them.
use std::env;
-use std::path::PathBuf;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+#[path = "generate/webgl_constants.rs"]
+mod webgl_constants;
+
+#[path = "generate/webgl_wire.rs"]
+mod webgl_wire;
+
+#[path = "generate/webgl_wire_model.rs"]
+mod webgl_wire_model;
+
+fn read_tracked(path: &Path) -> String {
+ println!("cargo:rerun-if-changed={}", path.display());
+ fs::read_to_string(path).unwrap_or_else(|error| panic!("read {}: {error}", path.display()))
+}
+
+fn generate_webgl_wire_vocabulary(libraries: &Path, out_dir: &Path) {
+ let functions_path = libraries.join("LibCompositing/WebGL/GLFunctions.json");
+ let generated = webgl_wire_model::parse_functions(&read_tracked(&functions_path))
+ .and_then(|functions| {
+ Ok(webgl_wire::write_wire_vocabulary(&webgl_wire_model::vocabulary(
+ &functions,
+ )?))
+ })
+ .unwrap_or_else(|error| panic!("{}: {error}", functions_path.display()));
+ fs::write(out_dir.join("webgl_wire.rs"), generated).expect("write webgl_wire.rs");
+}
+
+fn idl_files_in(directory: &Path, idl_files: &mut Vec<PathBuf>) {
+ // NB: Tracking the directory reruns the script when an IDL file is added to it or removed from it.
+ println!("cargo:rerun-if-changed={}", directory.display());
+ let entries = fs::read_dir(directory).unwrap_or_else(|error| panic!("read {}: {error}", directory.display()));
+ for entry in entries {
+ let path = entry.expect("directory entry").path();
+ if path.is_dir() {
+ idl_files_in(&path, idl_files);
+ } else if path.extension().is_some_and(|extension| extension == "idl") {
+ idl_files.push(path);
+ }
+ }
+}
+
+fn generate_webgl_constants(libraries: &Path, out_dir: &Path) {
+ let mut idl_files = Vec::new();
+ idl_files_in(&libraries.join("LibWeb/WebGL"), &mut idl_files);
+ // NB: The order of a directory listing is not defined, and the order of the constants follows from it.
+ idl_files.sort();
+ let mut constants = Vec::new();
+ for idl_file in &idl_files {
+ webgl_constants::collect_constants(&read_tracked(idl_file), &mut constants)
+ .unwrap_or_else(|error| panic!("{}: {error}", idl_file.display()));
+ }
+ fs::write(
+ out_dir.join("webgl_constants.rs"),
+ webgl_constants::write_constants(&constants),
+ )
+ .expect("write webgl_constants.rs");
+}
fn main() {
println!("cargo:rerun-if-changed=build.rs");
+ println!("cargo:rerun-if-changed=generate");
+ let manifest_dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
+ let out_dir = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR"));
+ let libraries = manifest_dir
+ .ancestors()
+ .nth(3)
+ .expect("the crate is in Libraries/LibWeb/Bindings/Rust");
+ generate_webgl_wire_vocabulary(libraries, &out_dir);
+ generate_webgl_constants(libraries, &out_dir);
+
println!("cargo:rustc-check-cfg=cfg(web_idl_bindings)");
println!("cargo:rerun-if-env-changed=LIBWEB_RUST_BINDINGS");
let Some(bindings) = env::var_os("LIBWEB_RUST_BINDINGS") else {
diff --git a/Libraries/LibWeb/Bindings/Rust/generate/webgl_constants.rs b/Libraries/LibWeb/Bindings/Rust/generate/webgl_constants.rs
new file mode 100644
index 00000000000..775f2ebf857
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/generate/webgl_constants.rs
@@ -0,0 +1,354 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Writes the GL constants that the WebGL interfaces define, from the `const` members of their IDL, so that the
+//! implementation names a value as the specifications do and cannot disagree with the constant that script reads.
+
+use std::fmt::Write;
+
+#[derive(Debug)]
+pub struct Constant {
+ pub name: String,
+ pub rust_type: &'static str,
+ /// The value as the first definition of the constant spells it, which the generated constant keeps.
+ pub spelling: String,
+ pub value: i128,
+}
+
+/// A comment becomes a space, which keeps the words around it apart, and a string literal keeps only its quotes: both
+/// can hold a `;` or a `const`, and neither holds a statement.
+fn without_comments_and_string_contents(idl: &str) -> String {
+ let mut out = String::with_capacity(idl.len());
+ let mut rest = idl;
+ while let Some(start) = rest.find(['/', '"']) {
+ let (before, found) = rest.split_at(start);
+ out.push_str(before);
+ rest = if let Some(comment) = found.strip_prefix("//") {
+ out.push(' ');
+ comment.find('\n').map_or("", |end| &comment[end..])
+ } else if let Some(comment) = found.strip_prefix("/*") {
+ out.push(' ');
+ comment.find("*/").map_or("", |end| &comment[end + 2..])
+ } else if let Some(string) = found.strip_prefix('"') {
+ out.push_str("\"\"");
+ string.find('"').map_or("", |end| &string[end + 1..])
+ } else {
+ out.push('/');
+ &found[1..]
+ };
+ }
+ out.push_str(rest);
+ out
+}
+
+/// The value of an integer of the IDL, https://webidl.spec.whatwg.org/#prod-integer, whose spelling Rust reads as the
+/// same integer: decimal digits without a leading zero, which makes an integer of the IDL octal, or hexadecimal digits
+/// after `0x`.
+fn integer_value(spelling: &str) -> Option<i128> {
+ let digits = spelling.strip_prefix('-').unwrap_or(spelling);
+ let magnitude = match digits.strip_prefix("0x") {
+ Some(hex_digits) if hex_digits.bytes().all(|byte| byte.is_ascii_hexdigit()) => {
+ i128::from_str_radix(hex_digits, 16).ok()?
+ }
+ None if digits.bytes().all(|byte| byte.is_ascii_digit()) && (digits == "0" || !digits.starts_with('0')) => {
+ digits.parse::<i128>().ok()?
+ }
+ _ => return None,
+ };
+ // NB: The spelling is written to Rust as it is, where an unsigned type does not take the sign of -0.
+ match (spelling.starts_with('-'), magnitude) {
+ (true, 0) => None,
+ (true, magnitude) => Some(-magnitude),
+ (false, magnitude) => Some(magnitude),
+ }
+}
+
+/// https://webidl.spec.whatwg.org/#prod-ExtendedAttributeList
+fn without_leading_extended_attributes(statement: &str) -> &str {
+ let statement = statement.trim_start();
+ statement
+ .strip_prefix('[')
+ .and_then(|attributes_and_member| attributes_and_member.split_once(']'))
+ .map_or(statement, |(_attributes, member)| member)
+}
+
+fn parse_constant(statement: &str) -> Result<Constant, String> {
+ let unreadable = || {
+ let statement = statement.split_whitespace().collect::<Vec<_>>().join(" ");
+ format!("the WebGL constants cannot be read from the IDL statement {statement:?}")
+ };
+ let declaration = statement.strip_suffix(';').ok_or_else(unreadable)?;
+ let (type_and_name, spelling) = declaration.split_once('=').ok_or_else(unreadable)?;
+ let mut words = type_and_name.split_whitespace().skip(1);
+ let (Some(idl_type), Some(name), None) = (words.next(), words.next(), words.next()) else {
+ return Err(unreadable());
+ };
+ if !name.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') {
+ return Err(unreadable());
+ }
+ let (rust_type, values_of_type) = match idl_type {
+ "GLenum" => ("u32", 0..=i128::from(u32::MAX)),
+ "GLint64" => ("i64", i128::from(i64::MIN)..=i128::from(i64::MAX)),
+ _ => {
+ return Err(format!(
+ "the WebGL constant {name} has the type {idl_type}, which has no Rust type yet"
+ ));
+ }
+ };
+ let spelling = spelling.trim();
+ let value = integer_value(spelling)
+ .filter(|value| values_of_type.contains(value))
+ .ok_or_else(unreadable)?;
+ Ok(Constant {
+ name: name.to_string(),
+ rust_type,
+ spelling: spelling.to_string(),
+ value,
+ })
+}
+
+/// Several interfaces define the same constant, which then has to have the same value in each, however each spells
+/// it.
+pub fn collect_constants(idl: &str, constants: &mut Vec<Constant>) -> Result<(), String> {
+ // NB: The first member of an interface follows a `{`, and every other one follows the `;` of the member before it.
+ for statement in without_comments_and_string_contents(idl).split_inclusive([';', '{', '}']) {
+ let statement = without_leading_extended_attributes(statement);
+ if statement.split_whitespace().next() != Some("const") {
+ continue;
+ }
+ let constant = parse_constant(statement)?;
+ match constants.iter().find(|existing| existing.name == constant.name) {
+ None => constants.push(constant),
+ Some(existing) if existing.rust_type == constant.rust_type && existing.value == constant.value => {}
+ Some(existing) => {
+ return Err(format!(
+ "the WebGL constant {} is defined as the {} {} and as the {} {}",
+ constant.name, existing.rust_type, existing.spelling, constant.rust_type, constant.spelling
+ ));
+ }
+ }
+ }
+ Ok(())
+}
+
+pub fn write_constants(constants: &[Constant]) -> String {
+ let mut out =
+ String::from("// Generated by build.rs from the constants of the IDL files of Libraries/LibWeb/WebGL.\n\n");
+ for constant in constants {
+ writeln!(
+ out,
+ "pub(crate) const GL_{}: {} = {};",
+ constant.name, constant.rust_type, constant.spelling
+ )
+ .unwrap();
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn written_constants(idl_files: &[&str]) -> Result<Vec<String>, String> {
+ let mut constants = Vec::new();
+ for idl in idl_files {
+ collect_constants(idl, &mut constants)?;
+ }
+ let written = write_constants(&constants);
+ Ok(written.lines().skip(2).map(str::to_string).collect())
+ }
+
+ fn unreadable(statement: &str) -> String {
+ format!("the WebGL constants cannot be read from the IDL statement {statement:?}")
+ }
+
+ #[test]
+ fn constants_are_collected_once() {
+ let idl_files = [
+ "interface mixin A {\n const GLenum DEPTH_BUFFER_BIT = 0x00000100;\n const GLenum ZERO = 0;\n\
+ // const GLenum NOT_THIS = 1;\n const GLint64 TIMEOUT_IGNORED = -1; // forever\n undefined f();\n};\n",
+ "interface B {\n const GLenum ZERO = 0;\n};\n",
+ ];
+ assert_eq!(
+ written_constants(&idl_files).unwrap(),
+ [
+ "pub(crate) const GL_DEPTH_BUFFER_BIT: u32 = 0x00000100;",
+ "pub(crate) const GL_ZERO: u32 = 0;",
+ "pub(crate) const GL_TIMEOUT_IGNORED: i64 = -1;",
+ ]
+ );
+ }
+
+ #[test]
+ fn a_constant_keeps_its_first_spelling_whatever_the_later_ones_are() {
+ let idl_files = [
+ "interface A { const GLenum DEPTH_BUFFER_BIT = 0x0100; };",
+ "interface B { const GLenum DEPTH_BUFFER_BIT = 256; };",
+ "interface C { const GLenum DEPTH_BUFFER_BIT = 0x00000100; };",
+ ];
+ assert_eq!(
+ written_constants(&idl_files).unwrap(),
+ ["pub(crate) const GL_DEPTH_BUFFER_BIT: u32 = 0x0100;"]
+ );
+ }
+
+ #[test]
+ fn a_constant_has_one_value_and_one_type() {
+ assert_eq!(
+ written_constants(&["const GLenum ONE = 1;", "const GLenum ONE = 0x2;"]).unwrap_err(),
+ "the WebGL constant ONE is defined as the u32 1 and as the u32 0x2"
+ );
+ assert_eq!(
+ written_constants(&["const GLenum ONE = 1;", "const GLint64 ONE = 1;"]).unwrap_err(),
+ "the WebGL constant ONE is defined as the u32 1 and as the i64 1"
+ );
+ }
+
+ #[test]
+ fn constants_are_read_by_statement_and_not_by_line() {
+ let idl = "interface A { const GLenum ONE = 1; const GLenum TWO = 2;\n const GLenum\n THREE\n =\n\
+ 3;const GLenum FOUR=4;\n undefined f(); const GLenum FIVE = 5 ; };";
+ assert_eq!(
+ written_constants(&[idl]).unwrap(),
+ [
+ "pub(crate) const GL_ONE: u32 = 1;",
+ "pub(crate) const GL_TWO: u32 = 2;",
+ "pub(crate) const GL_THREE: u32 = 3;",
+ "pub(crate) const GL_FOUR: u32 = 4;",
+ "pub(crate) const GL_FIVE: u32 = 5;",
+ ]
+ );
+ }
+
+ #[test]
+ fn a_constant_can_follow_extended_attributes() {
+ let idl = "interface A {\n [Exposed=Window] const GLenum ON_THE_SAME_LINE = 1;\n \
+ [Exposed=(Window,Worker)]\n const GLenum ON_THE_NEXT_LINE = 2;\n \
+ [Exposed=Window]const GLenum WITHOUT_A_SPACE = 3;\n \
+ [Exposed=Window] undefined f(long const);\n};";
+ assert_eq!(
+ written_constants(&[idl]).unwrap(),
+ [
+ "pub(crate) const GL_ON_THE_SAME_LINE: u32 = 1;",
+ "pub(crate) const GL_ON_THE_NEXT_LINE: u32 = 2;",
+ "pub(crate) const GL_WITHOUT_A_SPACE: u32 = 3;",
+ ]
+ );
+ assert_eq!(
+ written_constants(&["interface A { [Exposed=Window] const GLenum NAMED = OTHER; };"]).unwrap_err(),
+ unreadable("const GLenum NAMED = OTHER;")
+ );
+ }
+
+ #[test]
+ fn braces_that_are_not_of_an_interface_end_a_statement_too() {
+ let idl = "dictionary D { long member = 1; };\ninterface A {\n \
+ undefined f(optional D d = {}); const GLenum AFTER_A_DEFAULT_VALUE = 1;\n};\n\
+ namespace N { const GLenum IN_A_NAMESPACE = 2; };";
+ assert_eq!(
+ written_constants(&[idl]).unwrap(),
+ [
+ "pub(crate) const GL_AFTER_A_DEFAULT_VALUE: u32 = 1;",
+ "pub(crate) const GL_IN_A_NAMESPACE: u32 = 2;",
+ ]
+ );
+ }
+
+ #[test]
+ fn a_line_can_end_with_a_carriage_return_before_its_line_feed() {
+ let idl = "interface A {\r\n const GLenum BEFORE = 0x10;\r\n // const GLenum IN_A_LINE = 1;\r\n \
+ const GLenum AFTER = 2;\r\n};\r\n";
+ assert_eq!(
+ written_constants(&[idl]).unwrap(),
+ [
+ "pub(crate) const GL_BEFORE: u32 = 0x10;",
+ "pub(crate) const GL_AFTER: u32 = 2;",
+ ]
+ );
+ }
+
+ #[test]
+ fn comments_and_string_literals_define_no_constants() {
+ let idl = "interface A {\n /* const GLenum IN_A_BLOCK = 1; */\n /*\n const GLenum IN_A_LONG_BLOCK = 2;\n\
+ */\n // const GLenum IN_A_LINE = 3;\n const GLenum /* between */ KEPT = 4; // const GLenum AFTER = 5;\n\
+ attribute DOMString a = \"; const GLenum IN_A_STRING = 6;\"; const GLenum AFTER_A_STRING = 7;\n\
+ attribute DOMString b = \"//\"; const GLenum AFTER_A_STRING_WITH_SLASHES = 8;\n\
+ [Reflect=a/b] attribute DOMString c; const GLenum AFTER_A_SLASH = 9;\n};\n\
+ /* const GLenum IN_A_BLOCK_WITHOUT_AN_END = 10;";
+ assert_eq!(
+ written_constants(&[idl]).unwrap(),
+ [
+ "pub(crate) const GL_KEPT: u32 = 4;",
+ "pub(crate) const GL_AFTER_A_STRING: u32 = 7;",
+ "pub(crate) const GL_AFTER_A_STRING_WITH_SLASHES: u32 = 8;",
+ "pub(crate) const GL_AFTER_A_SLASH: u32 = 9;",
+ ]
+ );
+ }
+
+ #[test]
+ fn a_value_is_within_the_range_of_its_type() {
+ let idl = "const GLenum HIGHEST = 0xFFFFFFFF; const GLenum HIGHEST_IN_DECIMAL = 4294967295;\n\
+ const GLint64 LOWEST_OF_64_BITS = -9223372036854775808;\n\
+ const GLint64 LOWEST_OF_64_BITS_IN_HEXADECIMAL = -0x8000000000000000;\n\
+ const GLint64 HIGHEST_OF_64_BITS = 0x7fffffffffffffff;";
+ assert_eq!(
+ written_constants(&[idl]).unwrap(),
+ [
+ "pub(crate) const GL_HIGHEST: u32 = 0xFFFFFFFF;",
+ "pub(crate) const GL_HIGHEST_IN_DECIMAL: u32 = 4294967295;",
+ "pub(crate) const GL_LOWEST_OF_64_BITS: i64 = -9223372036854775808;",
+ "pub(crate) const GL_LOWEST_OF_64_BITS_IN_HEXADECIMAL: i64 = -0x8000000000000000;",
+ "pub(crate) const GL_HIGHEST_OF_64_BITS: i64 = 0x7fffffffffffffff;",
+ ]
+ );
+ for statement in [
+ "const GLenum TOO_HIGH = 0x100000000;",
+ "const GLenum TOO_HIGH = 4294967296;",
+ "const GLenum NEGATIVE = -1;",
+ "const GLenum NEGATIVE_ZERO = -0;",
+ "const GLint64 TOO_LOW = -9223372036854775809;",
+ "const GLint64 TOO_LOW = -0x8000000000000001;",
+ "const GLint64 TOO_HIGH = 9223372036854775808;",
+ "const GLint64 TOO_HIGH_FOR_ANY_TYPE = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;",
+ ] {
+ assert_eq!(written_constants(&[statement]).unwrap_err(), unreadable(statement));
+ }
+ }
+
+ #[test]
+ fn a_statement_that_cannot_be_read_is_named() {
+ for statement in [
+ "const GLenum NAMED = OTHER;",
+ "const GLenum OCTAL = 010;",
+ "const GLenum UPPER_CASE_PREFIX = 0X10;",
+ "const GLenum WITHOUT_DIGITS = 0x;",
+ "const GLenum SIGN_AFTER_PREFIX = 0x-1;",
+ "const GLenum PLUS = +1;",
+ "const GLenum WITHOUT_VALUE = ;",
+ "const GLenum WITHOUT_VALUE;",
+ "const GLenum = 1;",
+ "const unsigned long TYPE_OF_TWO_WORDS = 1;",
+ "const GLenum NOT-A-NAME = 1;",
+ "const GLenum UNFINISHED = 1",
+ ] {
+ assert_eq!(written_constants(&[statement]).unwrap_err(), unreadable(statement));
+ }
+ assert_eq!(
+ written_constants(&["interface A {\n const GLenum UNFINISHED = 1\n};"]).unwrap_err(),
+ unreadable("const GLenum UNFINISHED = 1 }")
+ );
+ assert_eq!(
+ written_constants(&["interface A {\n const GLenum\n FIRST = 1,\n SECOND = 2;\n};"])
+ .unwrap_err(),
+ unreadable("const GLenum FIRST = 1, SECOND = 2;")
+ );
+ assert_eq!(
+ written_constants(&["const GLfloat HALF = 0.5;"]).unwrap_err(),
+ "the WebGL constant HALF has the type GLfloat, which has no Rust type yet"
+ );
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rs b/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rs
new file mode 100644
index 00000000000..9dbed163c7b
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rs
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Writes the vocabulary of the WebGL command stream: the command types, the synchronous call types and the struct of
+//! each, which src/web_gl/proxy/vocabulary.rs includes. The C++ side of the stream gets the same from
+//! Meta/Generators/generate_libweb_webgl_commands.py.
+
+use std::fmt::Write;
+
+use crate::webgl_wire_model::{Vocabulary, WireStruct, WireType, rust_identifier, wire_layout_name_hash};
+
+/// A field of the Rust struct: one of the model, or the bytes that the C ABI leaves unused, which the struct spells
+/// out so that all of its bytes are initialized and it can be written to the stream as bytes.
+struct RustField {
+ name: String,
+ rust_type: String,
+ zero: String,
+}
+
+fn rust_fields(layout: &WireStruct) -> Vec<RustField> {
+ let mut fields = Vec::new();
+ if layout.fields.is_empty() {
+ fields.push(RustField {
+ name: "_empty".into(),
+ rust_type: "u8".into(),
+ zero: "0".into(),
+ });
+ return fields;
+ }
+ for (index, field) in layout.fields.iter().enumerate() {
+ let end = field.offset + field.wire_type.size();
+ let next_offset = layout.fields.get(index + 1).map_or(layout.size, |next| next.offset);
+ let zero = match field.wire_type {
+ WireType::Bool => "false",
+ WireType::F32 => "0.0",
+ WireType::DataSpan => "DataSpan::EMPTY",
+ WireType::U8 | WireType::U32 | WireType::I32 | WireType::I64 | WireType::U64 => "0",
+ };
+ fields.push(RustField {
+ name: rust_identifier(&field.spec.name),
+ rust_type: field.wire_type.rust_type().into(),
+ zero: zero.into(),
+ });
+ if next_offset > end {
+ let padding = next_offset - end;
+ fields.push(RustField {
+ name: format!("_padding_after_{}", field.spec.name),
+ rust_type: format!("[u8; {padding}]"),
+ zero: format!("[0; {padding}]"),
+ });
+ }
+ }
+ fields
+}
+
+fn write_struct(out: &mut String, rust_name: &str, layout: &WireStruct) {
+ let fields = rust_fields(layout);
+ writeln!(out, " /// `{}`", layout.cpp_name).unwrap();
+ out.push_str(" #[derive(Clone, Copy, Debug, PartialEq)]\n #[repr(C)]\n");
+ writeln!(out, " pub(crate) struct {rust_name} {{").unwrap();
+ for field in &fields {
+ writeln!(out, " pub(crate) {}: {},", field.name, field.rust_type).unwrap();
+ }
+ out.push_str(" }\n");
+ // NB: The assertions below are what the safety of the implementation rests on: the fields are where the C ABI
+ // puts them and fill the struct, so it has no byte that the compiler could leave uninitialized.
+ out.push_str(" // SAFETY: The struct is repr(C) and made of plain values that fill it, as asserted below.\n");
+ writeln!(out, " unsafe impl WireStruct for {rust_name} {{").unwrap();
+ out.push_str(" const ZEROED: Self = Self {\n");
+ for field in &fields {
+ writeln!(out, " {}: {},", field.name, field.zero).unwrap();
+ }
+ out.push_str(" };\n }\n");
+ out.push_str(" const _: () = {\n");
+ writeln!(out, " assert!(size_of::<{rust_name}>() == {});", layout.size).unwrap();
+ writeln!(
+ out,
+ " assert!(align_of::<{rust_name}>() == {});",
+ layout.alignment
+ )
+ .unwrap();
+ for field in &layout.fields {
+ let name = rust_identifier(&field.spec.name);
+ writeln!(
+ out,
+ " assert!(offset_of!({rust_name}, {name}) == {});",
+ field.offset
+ )
+ .unwrap();
+ }
+ out.push_str(" };\n\n");
+}
+
+fn write_type_enum(out: &mut String, enum_name: &str, count_name: &str, description: &str, names: &[&str]) {
+ writeln!(out, "/// {description}").unwrap();
+ out.push_str("#[derive(Clone, Copy, Debug, PartialEq, Eq)]\n#[repr(u16)]\n");
+ writeln!(out, "pub(crate) enum {enum_name} {{").unwrap();
+ for name in names {
+ writeln!(out, " {name},").unwrap();
+ }
+ out.push_str("}\n\n");
+ writeln!(out, "pub(crate) const {count_name}: u16 = {};\n", names.len()).unwrap();
+}
+
+fn write_layout_words(out: &mut String, rust_path: &str, layout: &WireStruct) {
+ writeln!(out, " // {}", layout.cpp_name).unwrap();
+ writeln!(
+ out,
+ " {:#010x}, size_of::<{rust_path}>() as u32, align_of::<{rust_path}>() as u32, {},",
+ wire_layout_name_hash(&layout.cpp_name),
+ layout.fields.len()
+ )
+ .unwrap();
+ for field in &layout.fields {
+ writeln!(
+ out,
+ " {:#010x}, {:#010x}, offset_of!({rust_path}, {}) as u32, size_of::<{}>() as u32,",
+ wire_layout_name_hash(&field.spec.name),
+ wire_layout_name_hash(&field.spec.cpp_type),
+ rust_identifier(&field.spec.name),
+ field.wire_type.rust_type()
+ )
+ .unwrap();
+ }
+}
+
+pub fn write_wire_vocabulary(vocabulary: &Vocabulary) -> String {
+ let mut out = String::from("// Generated by build.rs from Libraries/LibCompositing/WebGL/GLFunctions.json.\n\n");
+ out.push_str("use core::mem::offset_of;\n\n");
+ out.push_str("use crate::web_gl::proxy::wire::DataSpan;\n\n");
+
+ let command_names: Vec<&str> = vocabulary
+ .commands
+ .iter()
+ .map(|entry| entry.function.command_name())
+ .collect();
+ write_type_enum(
+ &mut out,
+ "CommandType",
+ "COMMAND_TYPE_COUNT",
+ "What a record of the command stream is, in the order of the C++ enum `WebGLCommandType`.",
+ &command_names,
+ );
+ let sync_call_names: Vec<&str> = vocabulary
+ .sync_calls
+ .iter()
+ .map(|entry| entry.function.command_name())
+ .collect();
+ write_type_enum(
+ &mut out,
+ "SyncCallType",
+ "SYNC_CALL_TYPE_COUNT",
+ "What a synchronous call is, in the order of the C++ enum `WebGLSyncCallType`.",
+ &sync_call_names,
+ );
+
+ out.push_str(
+ "/// The structs of the records of the command stream, which are those of the C++ namespace `Commands`.\n",
+ );
+ out.push_str("pub(crate) mod commands {\n");
+ out.push_str(" use core::mem::offset_of;\n\n");
+ out.push_str(" use super::CommandType;\n");
+ out.push_str(" use crate::web_gl::proxy::wire::{Command, DataSpan, WireStruct};\n\n");
+ for entry in &vocabulary.commands {
+ let name = entry.function.command_name();
+ write_struct(&mut out, name, &entry.layout);
+ writeln!(out, " impl Command for {name} {{").unwrap();
+ writeln!(out, " const TYPE: CommandType = CommandType::{name};").unwrap();
+ out.push_str(" }\n\n");
+ }
+ out.push_str("}\n\n");
+
+ out.push_str("/// The structs of the synchronous calls, which are those of the C++ namespace `SyncCalls`.\n");
+ out.push_str("pub(crate) mod sync_calls {\n");
+ out.push_str(" use core::mem::offset_of;\n\n");
+ out.push_str(" use super::SyncCallType;\n");
+ out.push_str(" use crate::web_gl::proxy::wire::{DataSpan, SyncReply, SyncRequest, WireStruct};\n\n");
+ for entry in &vocabulary.sync_calls {
+ let name = entry.function.command_name();
+ write_struct(&mut out, &format!("{name}Request"), &entry.request);
+ write_struct(&mut out, &format!("{name}Reply"), &entry.reply);
+ writeln!(out, " impl SyncRequest for {name}Request {{").unwrap();
+ writeln!(out, " const TYPE: SyncCallType = SyncCallType::{name};").unwrap();
+ writeln!(out, " type Reply = {name}Reply;").unwrap();
+ out.push_str(" }\n");
+ // NB: vocabulary() rejects a reply with a field that some bit pattern is no value of.
+ out.push_str(" // SAFETY: Every field of the struct is a number or made of numbers.\n");
+ writeln!(out, " unsafe impl SyncReply for {name}Reply {{}}\n").unwrap();
+ }
+ out.push_str("}\n\n");
+
+ out.push_str(
+ "/// The layout of every struct above as this compiler laid it out, in the form of the table that the C++ side\n\
+ /// reports: per struct the hash of its C++ name, its size, its alignment and the number of its fields, then\n\
+ /// per field the hash of its name, the hash of the name of its C++ type, its offset and its size.\n",
+ );
+ out.push_str("#[allow(clippy::unreadable_literal, reason = \"the hashes are not read\")]\n");
+ out.push_str("pub(crate) static WIRE_STRUCT_LAYOUTS: &[u32] = &[\n");
+ for entry in &vocabulary.commands {
+ write_layout_words(
+ &mut out,
+ &format!("commands::{}", entry.function.command_name()),
+ &entry.layout,
+ );
+ }
+ for entry in &vocabulary.sync_calls {
+ let name = entry.function.command_name();
+ write_layout_words(&mut out, &format!("sync_calls::{name}Request"), &entry.request);
+ write_layout_words(&mut out, &format!("sync_calls::{name}Reply"), &entry.reply);
+ }
+ out.push_str("];\n");
+ out
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire_model.rs b/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire_model.rs
new file mode 100644
index 00000000000..98b5e43f801
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire_model.rs
@@ -0,0 +1,727 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The model of Libraries/LibCompositing/WebGL/GLFunctions.json: which entries the command stream carries and which
+//! structs they serialize to. It mirrors Meta/Generators/libweb_webgl.py, which the C++ side of the stream is
+//! generated from, so the two have to change together. What keeps them from drifting apart silently: the model
+//! rejects everything in the JSON that it does not know, and the recorder compares the layout of its structs with
+//! the one that the C++ side reports before it records anything.
+
+use serde_json::{Map, Value};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Category {
+ Command,
+ Gen,
+ Sync,
+ Custom,
+ BuiltinCommand,
+}
+
+#[derive(Debug)]
+pub struct Argument {
+ pub cpp_type: String,
+ pub name: String,
+ /// The C++ expression for the number of bytes that a pointer argument points at.
+ pub payload: Option<String>,
+ pub is_object: bool,
+ pub is_out: bool,
+ pub is_offset: bool,
+ pub is_string: bool,
+ pub is_nullable: bool,
+}
+
+impl Argument {
+ pub fn is_pointer(&self) -> bool {
+ self.cpp_type.ends_with('*')
+ }
+
+ pub fn is_const_pointer(&self) -> bool {
+ self.is_pointer() && self.cpp_type.contains("const")
+ }
+
+ pub fn pointee_cpp_type(&self) -> String {
+ self.cpp_type.replace('*', "").trim().to_string()
+ }
+}
+
+/// A field of a struct of the command stream, before it has a place in the struct.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct FieldSpec {
+ pub cpp_type: String,
+ pub name: String,
+}
+
+#[derive(Debug)]
+pub struct Function {
+ pub name: String,
+ pub category: Category,
+ /// The built-in commands, which are no GL functions, have none.
+ pub return_type: Option<String>,
+ pub arguments: Vec<Argument>,
+ wire_command: Option<Vec<FieldSpec>>,
+ wire_request: Option<Vec<FieldSpec>>,
+ wire_reply: Option<Vec<FieldSpec>>,
+}
+
+const FUNCTION_KEYS: [&str; 8] = [
+ "name",
+ "category",
+ "return",
+ "args",
+ // What the replayer does with the objects that a function deletes, which the recorder has no part in.
+ "deletes_objects",
+ "wire_command",
+ "wire_request",
+ "wire_reply",
+];
+
+const ARGUMENT_KEYS: [&str; 10] = [
+ "type",
+ "name",
+ "payload",
+ "object",
+ "out",
+ "offset",
+ "string",
+ "nullable",
+ // How the replayer resolves an argument, which the recorder has no part in.
+ "zero_means_default",
+ "host_override",
+];
+
+fn reject_unknown_keys(object: &Map<String, Value>, known_keys: &[&str], what: &str) -> Result<(), String> {
+ match object.keys().find(|key| !known_keys.contains(&key.as_str())) {
+ Some(key) => Err(format!(
+ "{what} has the key {key:?}, which the model of the WebGL functions does not know"
+ )),
+ None => Ok(()),
+ }
+}
+
+fn string_member(object: &Map<String, Value>, key: &str, what: &str) -> Result<Option<String>, String> {
+ match object.get(key) {
+ None => Ok(None),
+ Some(Value::String(string)) => Ok(Some(string.clone())),
+ Some(other) => Err(format!("{what} has {other} for {key:?}, which is not a string")),
+ }
+}
+
+fn required_string_member(object: &Map<String, Value>, key: &str, what: &str) -> Result<String, String> {
+ string_member(object, key, what)?.ok_or_else(|| format!("{what} has no {key:?}"))
+}
+
+fn flag(object: &Map<String, Value>, key: &str, what: &str) -> Result<bool, String> {
+ match object.get(key) {
+ None => Ok(false),
+ Some(Value::Bool(true)) => Ok(true),
+ Some(other) => Err(format!("{what} has {other} for {key:?}, which can only be true")),
+ }
+}
+
+fn parse_argument(value: &Value, function_name: &str) -> Result<Argument, String> {
+ let what = format!("an argument of {function_name}");
+ let object = value.as_object().ok_or_else(|| format!("{what} is not an object"))?;
+ reject_unknown_keys(object, &ARGUMENT_KEYS, &what)?;
+ Ok(Argument {
+ cpp_type: required_string_member(object, "type", &what)?,
+ name: required_string_member(object, "name", &what)?,
+ payload: string_member(object, "payload", &what)?,
+ is_object: flag(object, "object", &what)?,
+ is_out: flag(object, "out", &what)?,
+ is_offset: flag(object, "offset", &what)?,
+ is_string: flag(object, "string", &what)?,
+ is_nullable: flag(object, "nullable", &what)?,
+ })
+}
+
+fn parse_wire_fields(
+ object: &Map<String, Value>,
+ key: &str,
+ function_name: &str,
+) -> Result<Option<Vec<FieldSpec>>, String> {
+ let Some(value) = object.get(key) else {
+ return Ok(None);
+ };
+ let what = format!("{key:?} of {function_name}");
+ let fields = value.as_array().ok_or_else(|| format!("{what} is not an array"))?;
+ let mut field_specs = Vec::new();
+ for field in fields {
+ let field = field
+ .as_object()
+ .ok_or_else(|| format!("a field of {what} is not an object"))?;
+ reject_unknown_keys(field, &["type", "name"], &format!("a field of {what}"))?;
+ field_specs.push(FieldSpec {
+ cpp_type: required_string_member(field, "type", &what)?,
+ name: required_string_member(field, "name", &what)?,
+ });
+ }
+ Ok(Some(field_specs))
+}
+
+fn parse_function(value: &Value) -> Result<Function, String> {
+ let object = value
+ .as_object()
+ .ok_or("an entry of the WebGL functions is not an object")?;
+ let name = required_string_member(object, "name", "an entry of the WebGL functions")?;
+ reject_unknown_keys(object, &FUNCTION_KEYS, &name)?;
+ let category = match required_string_member(object, "category", &name)?.as_str() {
+ "command" => Category::Command,
+ "gen" => Category::Gen,
+ "sync" => Category::Sync,
+ "custom" => Category::Custom,
+ "builtin-command" => Category::BuiltinCommand,
+ other => {
+ return Err(format!(
+ "{name} has the category {other:?}, which the model of the WebGL functions does not know"
+ ));
+ }
+ };
+ let mut arguments = Vec::new();
+ if let Some(values) = object.get("args") {
+ let values = values
+ .as_array()
+ .ok_or_else(|| format!("\"args\" of {name} is not an array"))?;
+ for value in values {
+ arguments.push(parse_argument(value, &name)?);
+ }
+ }
+ let function = Function {
+ return_type: string_member(object, "return", &name)?,
+ arguments,
+ wire_command: parse_wire_fields(object, "wire_command", &name)?,
+ wire_request: parse_wire_fields(object, "wire_request", &name)?,
+ wire_reply: parse_wire_fields(object, "wire_reply", &name)?,
+ category,
+ name,
+ };
+ function.check_shape()?;
+ Ok(function)
+}
+
+/// In the order of the JSON, which is the order of the command types.
+pub fn parse_functions(json: &str) -> Result<Vec<Function>, String> {
+ let value: Value =
+ serde_json::from_str(json).map_err(|error| format!("the WebGL functions are not JSON: {error}"))?;
+ let entries = value.as_array().ok_or("the WebGL functions are not an array")?;
+ entries.iter().map(parse_function).collect()
+}
+
+impl Function {
+ fn check_shape(&self) -> Result<(), String> {
+ let name = &self.name;
+ let has_signature = self.return_type.is_some();
+ let has_wire_structs = self.wire_command.is_some() || self.wire_request.is_some() || self.wire_reply.is_some();
+ match self.category {
+ Category::BuiltinCommand => {
+ if has_signature || !self.arguments.is_empty() || self.wire_command.is_none() {
+ return Err(format!(
+ "{name} is a built-in command, which is its \"wire_command\" and nothing else"
+ ));
+ }
+ }
+ Category::Command | Category::Gen | Category::Sync => {
+ if !has_signature || has_wire_structs {
+ return Err(format!(
+ "the structs of {name} follow from its signature, which is all it can have"
+ ));
+ }
+ }
+ Category::Custom => {
+ if !has_signature {
+ return Err(format!("{name} has no \"return\""));
+ }
+ }
+ }
+ if self.wire_request.is_some() != self.wire_reply.is_some() {
+ return Err(format!("{name} has only one of \"wire_request\" and \"wire_reply\""));
+ }
+ if self.wire_command.is_some() && self.wire_request.is_some() {
+ return Err(format!("{name} is both a command and a synchronous call"));
+ }
+ if !self.is_builtin() && !self.name.starts_with("gl") {
+ return Err(format!("the name of {name} does not start with \"gl\""));
+ }
+ Ok(())
+ }
+
+ fn is_builtin(&self) -> bool {
+ self.category == Category::BuiltinCommand
+ }
+
+ pub fn returns_void(&self) -> bool {
+ self.return_type.as_deref() == Some("void")
+ }
+
+ pub fn command_name(&self) -> &str {
+ if self.is_builtin() { &self.name } else { &self.name[2..] }
+ }
+
+ pub fn is_command_stream_entry(&self) -> bool {
+ matches!(self.category, Category::Command | Category::Gen) || self.wire_command.is_some()
+ }
+
+ pub fn is_sync_call(&self) -> bool {
+ self.category == Category::Sync || self.wire_request.is_some()
+ }
+
+ fn unhandled_pointer(&self, argument: &Argument) -> String {
+ format!(
+ "the model of the WebGL functions does not handle the pointer argument {} of {}",
+ argument.name, self.name
+ )
+ }
+
+ pub fn command_fields(&self) -> Result<Vec<FieldSpec>, String> {
+ if let Some(fields) = &self.wire_command {
+ return Ok(fields.clone());
+ }
+ let is_gen = self.category == Category::Gen;
+ let mut fields = Vec::new();
+ if is_gen && !self.returns_void() {
+ fields.push(FieldSpec {
+ cpp_type: "WebGLObjectId".into(),
+ name: "id".into(),
+ });
+ }
+ for argument in &self.arguments {
+ let name = title_case_to_snake_case(&argument.name);
+ let cpp_type = if is_gen && argument.is_pointer() && !argument.is_const_pointer() {
+ // The ids that the recorder allocated.
+ "WebGLDataSpan"
+ } else if argument.is_object && !argument.is_pointer() {
+ "WebGLObjectId"
+ } else if (argument.is_object && argument.is_const_pointer()) || argument.is_string {
+ "WebGLDataSpan"
+ } else if argument.is_offset {
+ "GLintptr"
+ } else if argument.payload.is_some() {
+ if argument.is_nullable {
+ fields.push(FieldSpec {
+ cpp_type: "bool".into(),
+ name: format!("has_{name}"),
+ });
+ }
+ "WebGLDataSpan"
+ } else if argument.is_pointer() {
+ return Err(self.unhandled_pointer(argument));
+ } else {
+ &argument.cpp_type
+ };
+ fields.push(FieldSpec {
+ cpp_type: cpp_type.to_string(),
+ name,
+ });
+ }
+ Ok(fields)
+ }
+
+ pub fn sync_request_fields(&self) -> Result<Vec<FieldSpec>, String> {
+ if let Some(fields) = &self.wire_request {
+ return Ok(fields.clone());
+ }
+ let mut fields = Vec::new();
+ for argument in &self.arguments {
+ if argument.is_out {
+ continue;
+ }
+ let cpp_type = if argument.is_object && !argument.is_pointer() {
+ "WebGLObjectId"
+ } else if argument.is_string || argument.payload.is_some() {
+ "WebGLDataSpan"
+ } else if argument.is_pointer() {
+ return Err(self.unhandled_pointer(argument));
+ } else {
+ &argument.cpp_type
+ };
+ fields.push(FieldSpec {
+ cpp_type: cpp_type.to_string(),
+ name: title_case_to_snake_case(&argument.name),
+ });
+ }
+ Ok(fields)
+ }
+
+ /// The return value, then every output, a buffer as a span into the data that follows the struct.
+ pub fn sync_reply_fields(&self) -> Vec<FieldSpec> {
+ if let Some(fields) = &self.wire_reply {
+ return fields.clone();
+ }
+ let mut fields = Vec::new();
+ if let Some(return_type) = &self.return_type
+ && return_type != "void"
+ {
+ fields.push(FieldSpec {
+ cpp_type: return_type.clone(),
+ name: "return_value".into(),
+ });
+ }
+ for argument in &self.arguments {
+ if !argument.is_out {
+ continue;
+ }
+ let cpp_type = if argument.payload.is_some() {
+ "WebGLDataSpan".to_string()
+ } else {
+ argument.pointee_cpp_type()
+ };
+ fields.push(FieldSpec {
+ cpp_type,
+ name: title_case_to_snake_case(&argument.name),
+ });
+ }
+ fields
+ }
+}
+
+/// Mirrors title_case_to_snake_case() in Meta/Utils/utils.py.
+pub fn title_case_to_snake_case(value: &str) -> String {
+ let characters: Vec<char> = value.chars().collect();
+ let mut snake_case = String::new();
+ for (index, &character) in characters.iter().enumerate() {
+ if character.is_uppercase() && index > 0 {
+ let previous_is_lowercase = characters[index - 1].is_lowercase();
+ let next_is_lowercase = characters.get(index + 1).is_some_and(|next| next.is_lowercase());
+ if previous_is_lowercase || next_is_lowercase {
+ snake_case.push('_');
+ }
+ }
+ snake_case.extend(character.to_lowercase());
+ }
+ snake_case
+}
+
+/// The Rust identifier for a name of the JSON, which can be a keyword.
+pub fn rust_identifier(name: &str) -> String {
+ const KEYWORDS: [&str; 6] = ["type", "ref", "match", "move", "loop", "in"];
+ if KEYWORDS.contains(&name) {
+ format!("r#{name}")
+ } else {
+ name.to_string()
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum WireType {
+ U8,
+ Bool,
+ U32,
+ I32,
+ F32,
+ I64,
+ U64,
+ DataSpan,
+}
+
+impl WireType {
+ pub fn of(cpp_type: &str) -> Option<Self> {
+ Some(match cpp_type {
+ "GLboolean" => Self::U8,
+ "bool" => Self::Bool,
+ "GLenum" | "GLuint" | "GLbitfield" | "WebGLObjectId" | "u32" => Self::U32,
+ "GLint" | "GLsizei" | "int" => Self::I32,
+ "GLfloat" => Self::F32,
+ "GLintptr" | "GLsizeiptr" => Self::I64,
+ "GLuint64" => Self::U64,
+ "WebGLDataSpan" => Self::DataSpan,
+ _ => return None,
+ })
+ }
+
+ pub fn rust_type(self) -> &'static str {
+ match self {
+ Self::U8 => "u8",
+ Self::Bool => "bool",
+ Self::U32 => "u32",
+ Self::I32 => "i32",
+ Self::F32 => "f32",
+ Self::I64 => "i64",
+ Self::U64 => "u64",
+ Self::DataSpan => "DataSpan",
+ }
+ }
+
+ pub fn size(self) -> usize {
+ match self {
+ Self::U8 | Self::Bool => 1,
+ Self::U32 | Self::I32 | Self::F32 => 4,
+ Self::I64 | Self::U64 | Self::DataSpan => 8,
+ }
+ }
+
+ pub fn alignment(self) -> usize {
+ match self {
+ Self::U8 | Self::Bool => 1,
+ Self::U32 | Self::I32 | Self::F32 | Self::DataSpan => 4,
+ Self::I64 | Self::U64 => 8,
+ }
+ }
+
+ pub fn accepts_every_bit_pattern(self) -> bool {
+ self != Self::Bool
+ }
+}
+
+#[derive(Debug)]
+pub struct WireField {
+ pub spec: FieldSpec,
+ pub wire_type: WireType,
+ pub offset: usize,
+}
+
+#[derive(Debug)]
+pub struct WireStruct {
+ /// The name of the struct inside the C++ namespace Compositing::WebGL, which the table of layout words hashes.
+ pub cpp_name: String,
+ pub fields: Vec<WireField>,
+ pub size: usize,
+ pub alignment: usize,
+}
+
+pub fn wire_struct(cpp_name: String, field_specs: Vec<FieldSpec>) -> Result<WireStruct, String> {
+ let mut fields = Vec::new();
+ let mut end_of_fields: usize = 0;
+ let mut alignment: usize = 1;
+ for spec in field_specs {
+ let Some(wire_type) = WireType::of(&spec.cpp_type) else {
+ return Err(format!(
+ "{cpp_name}.{} has the type {}, which the model of the WebGL functions has no layout for",
+ spec.name, spec.cpp_type
+ ));
+ };
+ let offset = end_of_fields.next_multiple_of(wire_type.alignment());
+ end_of_fields = offset + wire_type.size();
+ alignment = alignment.max(wire_type.alignment());
+ fields.push(WireField {
+ spec,
+ wire_type,
+ offset,
+ });
+ }
+ // NB: A struct without fields has the size 1 in C++, and the replayer rejects a request that is shorter than
+ // its struct.
+ let size = end_of_fields.next_multiple_of(alignment).max(1);
+ Ok(WireStruct {
+ cpp_name,
+ fields,
+ size,
+ alignment,
+ })
+}
+
+pub struct CommandEntry<'a> {
+ pub function: &'a Function,
+ pub layout: WireStruct,
+}
+
+pub struct SyncCallEntry<'a> {
+ pub function: &'a Function,
+ pub request: WireStruct,
+ pub reply: WireStruct,
+}
+
+/// Everything that crosses the command stream, in the order of the command types and of the synchronous call types.
+pub struct Vocabulary<'a> {
+ pub commands: Vec<CommandEntry<'a>>,
+ pub sync_calls: Vec<SyncCallEntry<'a>>,
+}
+
+pub fn vocabulary(functions: &[Function]) -> Result<Vocabulary<'_>, String> {
+ let mut commands = Vec::new();
+ let mut sync_calls = Vec::new();
+ for function in functions {
+ let name = function.command_name();
+ if function.is_command_stream_entry() {
+ let layout = wire_struct(format!("Commands::{name}"), function.command_fields()?)?;
+ commands.push(CommandEntry { function, layout });
+ }
+ if function.is_sync_call() {
+ let request = wire_struct(format!("SyncCalls::{name}::Request"), function.sync_request_fields()?)?;
+ let reply = wire_struct(format!("SyncCalls::{name}::Reply"), function.sync_reply_fields())?;
+ if let Some(field) = reply
+ .fields
+ .iter()
+ .find(|field| !field.wire_type.accepts_every_bit_pattern())
+ {
+ return Err(format!(
+ "{}.{} is a {}, which cannot be read from the bytes of a reply",
+ reply.cpp_name, field.spec.name, field.spec.cpp_type
+ ));
+ }
+ sync_calls.push(SyncCallEntry {
+ function,
+ request,
+ reply,
+ });
+ }
+ }
+ Ok(Vocabulary { commands, sync_calls })
+}
+
+/// The 32-bit FNV-1a hash that stands for the name of a struct, a field or a type in the table of layout words.
+pub fn wire_layout_name_hash(name: &str) -> u32 {
+ name.bytes().fold(0x811C_9DC5, |hash, byte| {
+ (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193)
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn fields(types_and_names: &[(&str, &str)]) -> Vec<FieldSpec> {
+ types_and_names
+ .iter()
+ .map(|(cpp_type, name)| FieldSpec {
+ cpp_type: (*cpp_type).into(),
+ name: (*name).into(),
+ })
+ .collect()
+ }
+
+ #[test]
+ fn a_struct_is_laid_out_as_the_c_abi_does() {
+ let layout = wire_struct(
+ "Commands::Example".into(),
+ fields(&[
+ ("GLenum", "target"),
+ ("GLintptr", "offset"),
+ ("GLboolean", "flag"),
+ ("WebGLDataSpan", "data"),
+ ]),
+ )
+ .unwrap();
+ let offsets: Vec<usize> = layout.fields.iter().map(|field| field.offset).collect();
+ assert_eq!(offsets, [0, 8, 16, 20]);
+ assert_eq!((layout.size, layout.alignment), (32, 8));
+ }
+
+ #[test]
+ fn a_struct_without_fields_is_one_byte() {
+ let layout = wire_struct("SyncCalls::Finish::Request".into(), Vec::new()).unwrap();
+ assert_eq!((layout.size, layout.alignment), (1, 1));
+ }
+
+ #[test]
+ fn a_field_of_an_unknown_type_is_rejected() {
+ let error = wire_struct("Commands::Example".into(), fields(&[("GLdouble", "depth")])).unwrap_err();
+ assert!(
+ error.contains("Commands::Example.depth has the type GLdouble"),
+ "{error}"
+ );
+ }
+
+ #[test]
+ fn names_are_converted_as_the_cpp_generators_convert_them() {
+ for (name, snake_case) in [
+ ("ActiveTexture", "active_texture"),
+ ("TexImage3DRobustANGLE", "tex_image3d_robust_angle"),
+ ("GetInteger64vRobustANGLE", "get_integer64v_robust_angle"),
+ ("UniformMatrix4fv", "uniform_matrix4fv"),
+ ("bufSize", "buf_size"),
+ ("srcX0", "src_x0"),
+ ("uniformBlockName", "uniform_block_name"),
+ ] {
+ assert_eq!(title_case_to_snake_case(name), snake_case);
+ }
+ }
+
+ #[test]
+ fn the_structs_of_a_function_follow_from_its_signature() {
+ let functions = parse_functions(
+ r#"[
+ {"name": "glBufferData", "return": "void", "category": "command", "args": [
+ {"type": "GLenum", "name": "target"},
+ {"type": "GLsizeiptr", "name": "size"},
+ {"type": "void const*", "name": "data", "payload": "size", "nullable": true},
+ {"type": "GLenum", "name": "usage"}]},
+ {"name": "glGetActiveAttrib", "return": "void", "category": "sync", "args": [
+ {"type": "GLuint", "name": "program", "object": true},
+ {"type": "GLsizei", "name": "bufSize"},
+ {"type": "GLsizei*", "name": "length", "out": true},
+ {"type": "GLchar*", "name": "name", "out": true, "payload": "bufSize * sizeof(GLchar)"}]},
+ {"name": "glCreateShader", "return": "GLuint", "category": "gen", "args": [
+ {"type": "GLenum", "name": "type"}]}
+ ]"#,
+ )
+ .unwrap();
+ let vocabulary = vocabulary(&functions).unwrap();
+ let described = |layout: &WireStruct| -> Vec<String> {
+ layout
+ .fields
+ .iter()
+ .map(|field| format!("{} {} @{}", field.spec.cpp_type, field.spec.name, field.offset))
+ .collect()
+ };
+ assert_eq!(vocabulary.commands[0].layout.cpp_name, "Commands::BufferData");
+ assert_eq!(
+ described(&vocabulary.commands[0].layout),
+ [
+ "GLenum target @0",
+ "GLsizeiptr size @8",
+ "bool has_data @16",
+ "WebGLDataSpan data @20",
+ "GLenum usage @28"
+ ]
+ );
+ assert_eq!(
+ described(&vocabulary.commands[1].layout),
+ ["WebGLObjectId id @0", "GLenum type @4"]
+ );
+ assert_eq!(
+ vocabulary.sync_calls[0].request.cpp_name,
+ "SyncCalls::GetActiveAttrib::Request"
+ );
+ assert_eq!(
+ described(&vocabulary.sync_calls[0].request),
+ ["WebGLObjectId program @0", "GLsizei buf_size @4"]
+ );
+ assert_eq!(
+ described(&vocabulary.sync_calls[0].reply),
+ ["GLsizei length @0", "WebGLDataSpan name @4"]
+ );
+ }
+
+ #[test]
+ fn what_the_model_does_not_know_is_rejected() {
+ let unknown_function_key =
+ r#"[{"name": "glFlush", "return": "void", "category": "command", "args": [], "flushes": true}]"#;
+ assert!(
+ parse_functions(unknown_function_key)
+ .unwrap_err()
+ .contains("glFlush has the key \"flushes\"")
+ );
+ let unknown_argument_key = r#"[{"name": "glEnable", "return": "void", "category": "command", "args": [
+ {"type": "GLenum", "name": "cap", "validated": true}]}]"#;
+ assert!(
+ parse_functions(unknown_argument_key)
+ .unwrap_err()
+ .contains("has the key \"validated\"")
+ );
+ let unknown_category = r#"[{"name": "glFlush", "return": "void", "category": "deferred", "args": []}]"#;
+ assert!(
+ parse_functions(unknown_category)
+ .unwrap_err()
+ .contains("has the category \"deferred\"")
+ );
+ let unhandled_pointer = r#"[{"name": "glGetPointerv", "return": "void", "category": "command", "args": [
+ {"type": "void**", "name": "params"}]}]"#;
+ let functions = parse_functions(unhandled_pointer).unwrap();
+ assert!(
+ vocabulary(&functions)
+ .err()
+ .unwrap()
+ .contains("does not handle the pointer argument params")
+ );
+ }
+
+ #[test]
+ fn a_name_hash_is_fnv_1a() {
+ assert_eq!(wire_layout_name_hash(""), 0x811C_9DC5);
+ assert_eq!(wire_layout_name_hash("a"), 0xE40C_292C);
+ assert_eq!(wire_layout_name_hash("Commands::ActiveTexture"), 0x9B0F_0F7C);
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index 025156b13d5..6abb7aea750 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -48,6 +48,17 @@ pub(crate) mod streams;
allow(dead_code, reason = "only the generated bindings use the interfaces")
)]
pub(crate) mod url_pattern;
+#[allow(dead_code, reason = "no interface is implemented with it yet")]
+pub(crate) mod web_gl;
+
+// The generators of the build script, whose tests run with those of the crate.
+#[cfg(test)]
+#[path = "../generate/webgl_constants.rs"]
+mod webgl_constants;
+#[cfg(test)]
+#[allow(dead_code, reason = "the tests do not run the writers that the model is for")]
+#[path = "../generate/webgl_wire_model.rs"]
+mod webgl_wire_model;
// NB: Only C++ calls into libweb_rust, so nothing in this crate names it. Linking it keeps its extern "C" functions in
// the static library.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/constants.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/constants.rs
new file mode 100644
index 00000000000..189d2971188
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/constants.rs
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The build script writes the constants that the WebGL interfaces define from their IDL.
+
+#![allow(
+ non_upper_case_globals,
+ reason = "GL has lower case letters in the names of some constants"
+)]
+
+include!(concat!(env!("OUT_DIR"), "/webgl_constants.rs"));
+
+// The constants that no WebGL interface defines.
+pub(crate) const GL_FALSE: u32 = 0;
+pub(crate) const GL_TRUE: u32 = 1;
+pub(crate) const GL_INFO_LOG_LENGTH: u32 = 0x8B84;
+pub(crate) const GL_SHADER_SOURCE_LENGTH: u32 = 0x8B88;
+pub(crate) const GL_UNIFORM_BLOCK_NAME_LENGTH: u32 = 0x8A41;
+pub(crate) const GL_NUM_SAMPLE_COUNTS: u32 = 0x9380;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rs
new file mode 100644
index 00000000000..4dff7a36b15
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rs
@@ -0,0 +1,11 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The WebContent half of WebGL, which validates what script asks for, keeps track of the state that it can read
+//! back, and records everything else as commands for the Compositor, which runs GL.
+
+pub(crate) mod constants;
+pub(crate) mod proxy;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/mod.rs
new file mode 100644
index 00000000000..19846881369
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/mod.rs
@@ -0,0 +1,11 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The recording side of the WebGL command stream. Libraries/LibCompositing/WebGL is the replaying side, and
+//! GLFunctions.json there defines what crosses the stream for both.
+
+pub(crate) mod vocabulary;
+pub(crate) mod wire;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/vocabulary.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/vocabulary.rs
new file mode 100644
index 00000000000..a17e438bb11
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/vocabulary.rs
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The vocabulary of the command stream: the command types, the synchronous call types and the struct that each
+//! serializes to. The build script writes it from GLFunctions.json (generate/webgl_wire.rs).
+
+include!(concat!(env!("OUT_DIR"), "/webgl_wire.rs"));
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::web_gl::proxy::wire::{DataSpan, WireStruct};
+
+ #[test]
+ fn a_struct_is_its_fields_in_the_byte_order_of_the_machine() {
+ let command = commands::Viewport {
+ x: 1,
+ y: -2,
+ width: 3,
+ height: 4,
+ };
+ let mut expected = Vec::new();
+ for field in [1i32, -2, 3, 4] {
+ expected.extend_from_slice(&field.to_ne_bytes());
+ }
+ assert_eq!(command.as_bytes(), expected);
+ }
+
+ #[test]
+ fn the_bytes_between_the_fields_of_a_struct_are_zero() {
+ let command = commands::BufferData {
+ target: u32::MAX,
+ size: -1,
+ has_data: true,
+ data: DataSpan {
+ offset: u32::MAX,
+ size: u32::MAX,
+ },
+ usage: u32::MAX,
+ ..commands::BufferData::ZEROED
+ };
+ let bytes = command.as_bytes();
+ assert_eq!(bytes.len(), 32);
+ assert_eq!(bytes[4..8], [0; 4]);
+ assert_eq!(bytes[16], 1);
+ assert_eq!(bytes[17..20], [0; 3]);
+ assert!(bytes[20..32].iter().all(|&byte| byte == 0xFF));
+ assert!(commands::BufferData::ZEROED.as_bytes().iter().all(|&byte| byte == 0));
+ }
+
+ #[test]
+ fn a_struct_without_fields_is_one_byte() {
+ assert_eq!(sync_calls::GetErrorRequest::ZEROED.as_bytes(), [0]);
+ assert_eq!(commands::Flush::ZEROED.as_bytes(), [0]);
+ }
+
+ #[test]
+ fn the_types_are_numbered_in_the_order_of_their_definition() {
+ assert_eq!(CommandType::ActiveTexture as u16, 0);
+ assert_eq!(CommandType::AttachShader as u16, 1);
+ assert_eq!(SyncCallType::CheckFramebufferStatus as u16, 0);
+ assert!((CommandType::Viewport as u16) < COMMAND_TYPE_COUNT);
+ assert!((SyncCallType::GetError as u16) < SYNC_CALL_TYPE_COUNT);
+ }
+
+ #[test]
+ fn the_table_of_layout_words_describes_every_struct() {
+ let mut struct_count = 0;
+ let mut words = WIRE_STRUCT_LAYOUTS;
+ while let [_name_hash, size, alignment, field_count, rest @ ..] = words {
+ assert!(*size >= 1 && size % alignment == 0);
+ let mut end_of_previous_field = 0;
+ let (fields, rest) = rest.split_at(*field_count as usize * 4);
+ for [_name_hash, _type_hash, offset, field_size] in fields.as_chunks::<4>().0 {
+ assert!(*offset >= end_of_previous_field && offset + field_size <= *size);
+ end_of_previous_field = offset + field_size;
+ }
+ struct_count += 1;
+ words = rest;
+ }
+ assert!(words.is_empty());
+ assert_eq!(
+ struct_count,
+ usize::from(COMMAND_TYPE_COUNT) + 2 * usize::from(SYNC_CALL_TYPE_COUNT)
+ );
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/wire.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/wire.rs
new file mode 100644
index 00000000000..264aad52d4a
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/wire.rs
@@ -0,0 +1,409 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The framing of the WebGL command stream: how a struct and the data that belongs to it become the bytes of a record
+//! or of a synchronous call. Libraries/LibCompositing/WebGL/WebGLCommandList.{h,cpp} is the C++ side of the same
+//! format, which reads what this writes.
+
+use core::mem::size_of;
+use core::{ptr, slice};
+
+use super::vocabulary::{CommandType, SyncCallType};
+
+/// Records start at multiples of this many bytes, and so does the data that follows a struct, counted from the start
+/// of the struct.
+pub(crate) const RECORD_ALIGNMENT: usize = 16;
+
+/// What precedes the struct of a record and of a request: its type as a `u16`, two unused bytes, and the number of
+/// bytes that follow the header as a `u32`.
+pub(crate) const HEADER_SIZE: usize = 8;
+
+/// The data that a field of a struct stands for: `size` bytes that start `offset` bytes after the start of the
+/// struct.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[repr(C)]
+pub(crate) struct DataSpan {
+ pub(crate) offset: u32,
+ pub(crate) size: u32,
+}
+
+impl DataSpan {
+ pub(crate) const EMPTY: Self = Self { offset: 0, size: 0 };
+
+ /// The span of the data that follows a struct `S`.
+ pub(crate) fn following<S: WireStruct>(data: InlineData<'_>) -> Self {
+ Self {
+ offset: wire_u32(size_of::<S>().next_multiple_of(RECORD_ALIGNMENT)),
+ size: wire_u32(data.len()),
+ }
+ }
+}
+
+/// A size or an offset as the stream carries it. The stream cannot carry a record of 4 GiB, which is far more than a
+/// buffer that script can allocate holds.
+fn wire_u32(size: usize) -> u32 {
+ u32::try_from(size).expect("a WebGL command and its data are smaller than 4 GiB")
+}
+
+/// A struct that crosses the command stream as its bytes.
+///
+/// # Safety
+///
+/// The type is `repr(C)`, made of numbers, booleans and [`DataSpan`]s, and has no byte that is not part of a field.
+pub(crate) unsafe trait WireStruct: Copy + 'static {
+ /// The struct with every field zero. A struct is built from it, so that the bytes that the C ABI leaves unused
+ /// between its fields, which are fields of their own here, do not have to be named.
+ const ZEROED: Self;
+
+ fn as_bytes(&self) -> &[u8] {
+ // SAFETY: Per the contract of the trait every byte of the struct is initialized.
+ unsafe { slice::from_raw_parts(ptr::from_ref(self).cast::<u8>(), size_of::<Self>()) }
+ }
+}
+
+pub(crate) trait Command: WireStruct {
+ const TYPE: CommandType;
+}
+
+pub(crate) trait SyncRequest: WireStruct {
+ const TYPE: SyncCallType;
+ type Reply: SyncReply;
+}
+
+/// # Safety
+///
+/// Every bit pattern is a value of the type.
+pub(crate) unsafe trait SyncReply: WireStruct {
+ fn from_reply_bytes(reply: &[u8]) -> Self {
+ assert!(
+ reply.len() >= size_of::<Self>(),
+ "the reply to a WebGL call is shorter than its struct"
+ );
+ // SAFETY: The bytes are as many as the struct has, and per the contract of the trait any bytes are a value
+ // of it.
+ unsafe { ptr::read_unaligned(reply.as_ptr().cast::<Self>()) }
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+pub(crate) enum InlineData<'a> {
+ /// No bytes take no room at all, not even for the alignment of what would follow.
+ Bytes(&'a [u8]),
+ /// The stream has a NUL after the bytes.
+ NulTerminated(&'a [u8]),
+}
+
+impl InlineData<'_> {
+ pub(crate) const NONE: Self = Self::Bytes(&[]);
+
+ pub(crate) fn len(self) -> usize {
+ match self {
+ Self::Bytes(bytes) => bytes.len(),
+ Self::NulTerminated(bytes) => bytes.len() + 1,
+ }
+ }
+
+ /// # Safety
+ ///
+ /// `destination` is valid for writes of `self.len()` bytes that do not overlap the data.
+ unsafe fn write_to(self, destination: *mut u8) {
+ let (Self::Bytes(bytes) | Self::NulTerminated(bytes)) = self;
+ // SAFETY: The caller provides room for the bytes, and for the terminator after them.
+ unsafe {
+ ptr::copy_nonoverlapping(bytes.as_ptr(), destination, bytes.len());
+ if matches!(self, Self::NulTerminated(_)) {
+ destination.add(bytes.len()).write(0);
+ }
+ }
+ }
+}
+
+/// The number of bytes that a struct and its data take together.
+fn payload_layout_size(struct_size: usize, inline_data: InlineData<'_>) -> usize {
+ match inline_data.len() {
+ 0 => struct_size,
+ inline_data_size => struct_size.next_multiple_of(RECORD_ALIGNMENT) + inline_data_size,
+ }
+}
+
+/// The number of bytes that a record takes in the command stream.
+pub(crate) fn padded_record_size(struct_size: usize, inline_data: InlineData<'_>) -> usize {
+ (HEADER_SIZE + payload_layout_size(struct_size, inline_data)).next_multiple_of(RECORD_ALIGNMENT)
+}
+
+/// Writes a header, a struct and its data, and zeroes what is left of `size` bytes, so that no byte of the stream is
+/// one that happened to be in memory.
+///
+/// # Safety
+///
+/// `destination` is valid for writes of `size` bytes, which are at least as many as the header, the struct and the
+/// data take, and which overlap neither the struct nor the data.
+unsafe fn write_framed(
+ destination: *mut u8,
+ size: usize,
+ type_number: u16,
+ payload: &[u8],
+ inline_data: InlineData<'_>,
+) {
+ let payload_size = wire_u32(size - HEADER_SIZE);
+ let mut header = [0; HEADER_SIZE];
+ header[..2].copy_from_slice(&type_number.to_ne_bytes());
+ header[4..].copy_from_slice(&payload_size.to_ne_bytes());
+
+ let mut written = HEADER_SIZE + payload.len();
+ // SAFETY: The caller provides `size` bytes, and every write below stays inside the layout that
+ // payload_layout_size() computes, which `size` covers.
+ unsafe {
+ ptr::copy_nonoverlapping(header.as_ptr(), destination, HEADER_SIZE);
+ ptr::copy_nonoverlapping(payload.as_ptr(), destination.add(HEADER_SIZE), payload.len());
+ if inline_data.len() > 0 {
+ let inline_data_offset = HEADER_SIZE + payload.len().next_multiple_of(RECORD_ALIGNMENT);
+ ptr::write_bytes(destination.add(written), 0, inline_data_offset - written);
+ inline_data.write_to(destination.add(inline_data_offset));
+ written = inline_data_offset + inline_data.len();
+ }
+ ptr::write_bytes(destination.add(written), 0, size - written);
+ }
+}
+
+/// Writes a record of the command stream.
+///
+/// # Safety
+///
+/// `destination` is valid for writes of `padded_record_size(payload.len(), inline_data)` bytes that overlap neither
+/// the payload nor the data.
+pub(crate) unsafe fn write_record(
+ destination: *mut u8,
+ command_type: CommandType,
+ payload: &[u8],
+ inline_data: InlineData<'_>,
+) {
+ let record_size = padded_record_size(payload.len(), inline_data);
+ // SAFETY: The caller provides the bytes of the record.
+ unsafe { write_framed(destination, record_size, command_type as u16, payload, inline_data) };
+}
+
+/// Appends a record to commands that are kept outside the shared command buffer.
+pub(crate) fn append_record(
+ commands: &mut Vec<u8>,
+ command_type: CommandType,
+ payload: &[u8],
+ inline_data: InlineData<'_>,
+) {
+ let record_offset = commands.len();
+ assert!(record_offset.is_multiple_of(RECORD_ALIGNMENT));
+ commands.resize(record_offset + padded_record_size(payload.len(), inline_data), 0);
+ // SAFETY: The vector was just grown by the size of the record, and it owns its bytes.
+ unsafe {
+ write_record(
+ commands.as_mut_ptr().add(record_offset),
+ command_type,
+ payload,
+ inline_data,
+ );
+ }
+}
+
+/// Replaces the contents of `request_bytes` with the request of a synchronous call.
+pub(crate) fn encode_sync_request<R: SyncRequest>(
+ request_bytes: &mut Vec<u8>,
+ request: &R,
+ inline_data: InlineData<'_>,
+) {
+ let payload_size = payload_layout_size(size_of::<R>(), inline_data).next_multiple_of(RECORD_ALIGNMENT);
+ request_bytes.clear();
+ request_bytes.resize(HEADER_SIZE + payload_size, 0);
+ // SAFETY: The vector has the size of the header and the padded payload, and it owns its bytes.
+ unsafe {
+ write_framed(
+ request_bytes.as_mut_ptr(),
+ request_bytes.len(),
+ R::TYPE as u16,
+ request.as_bytes(),
+ inline_data,
+ );
+ }
+}
+
+/// The data that a span of the struct of a reply stands for.
+pub(crate) fn resolve_data_span(reply: &[u8], span: DataSpan) -> &[u8] {
+ let start = span.offset as usize;
+ start
+ .checked_add(span.size as usize)
+ .and_then(|end| reply.get(start..end))
+ .expect("a span of the reply to a WebGL call lies inside the reply")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::vocabulary::{commands, sync_calls};
+ use super::*;
+
+ fn record(command_type: CommandType, payload: &[u8], inline_data: InlineData<'_>) -> Vec<u8> {
+ // NB: The bytes that a record is written over are not zero, as those of a reused buffer are not.
+ let mut bytes = vec![0xAA; padded_record_size(payload.len(), inline_data)];
+ // SAFETY: The vector has the size of the record.
+ unsafe { write_record(bytes.as_mut_ptr(), command_type, payload, inline_data) };
+ bytes
+ }
+
+ fn header(type_number: u16, payload_size: u32) -> Vec<u8> {
+ let mut header = Vec::new();
+ header.extend_from_slice(&type_number.to_ne_bytes());
+ header.extend_from_slice(&[0, 0]);
+ header.extend_from_slice(&payload_size.to_ne_bytes());
+ header
+ }
+
+ #[test]
+ fn a_record_is_a_header_and_a_struct_padded_to_the_alignment() {
+ let command = commands::Viewport {
+ x: 1,
+ y: 2,
+ width: 3,
+ height: 4,
+ };
+ let bytes = record(CommandType::Viewport, command.as_bytes(), InlineData::NONE);
+ assert_eq!(bytes.len(), 32);
+ assert_eq!(bytes[..8], header(CommandType::Viewport as u16, 24));
+ assert_eq!(bytes[8..24], *command.as_bytes());
+ assert_eq!(bytes[24..], [0; 8]);
+ }
+
+ #[test]
+ fn the_data_of_a_record_follows_its_struct_at_the_alignment() {
+ let data = [7u8; 5];
+ let command = commands::Uniform1fv {
+ location: 9,
+ count: 1,
+ value: DataSpan::following::<commands::Uniform1fv>(InlineData::Bytes(&data)),
+ };
+ assert_eq!(command.value, DataSpan { offset: 16, size: 5 });
+ let bytes = record(CommandType::Uniform1fv, command.as_bytes(), InlineData::Bytes(&data));
+ assert_eq!(bytes.len(), 32);
+ assert_eq!(bytes[..8], header(CommandType::Uniform1fv as u16, 24));
+ assert_eq!(bytes[8..24], *command.as_bytes());
+ assert_eq!(bytes[24..29], data);
+ assert_eq!(bytes[29..], [0; 3]);
+ }
+
+ #[test]
+ fn the_bytes_between_a_struct_and_its_data_are_zero() {
+ let command = commands::Enable { cap: u32::MAX };
+ let bytes = record(CommandType::Enable, command.as_bytes(), InlineData::Bytes(&[1]));
+ assert_eq!(bytes.len(), 32);
+ assert_eq!(bytes[8..12], [0xFF; 4]);
+ assert_eq!(bytes[12..24], [0; 12]);
+ assert_eq!(bytes[24], 1);
+ assert_eq!(bytes[25..], [0; 7]);
+ }
+
+ #[test]
+ fn no_data_takes_no_room() {
+ let command = commands::Uniform1fv {
+ location: 9,
+ count: 0,
+ value: DataSpan { offset: 16, size: 0 },
+ };
+ let bytes = record(CommandType::Uniform1fv, command.as_bytes(), InlineData::Bytes(&[]));
+ assert_eq!(bytes.len(), 32);
+ assert_eq!(bytes[..8], header(CommandType::Uniform1fv as u16, 24));
+ assert_eq!(bytes[24..], [0; 8]);
+ }
+
+ #[test]
+ fn a_string_is_followed_by_a_nul() {
+ let name = InlineData::NulTerminated(b"position");
+ assert_eq!(name.len(), 9);
+ let command = commands::RequestExtensionANGLE {
+ name: DataSpan::following::<commands::RequestExtensionANGLE>(name),
+ };
+ assert_eq!(command.name, DataSpan { offset: 16, size: 9 });
+ let bytes = record(CommandType::RequestExtensionANGLE, command.as_bytes(), name);
+ assert_eq!(bytes.len(), 48);
+ assert_eq!(bytes[24..33], *b"position\0");
+ assert_eq!(bytes[33..], [0; 15]);
+
+ let empty_name = InlineData::NulTerminated(b"");
+ let bytes = record(CommandType::RequestExtensionANGLE, command.as_bytes(), empty_name);
+ assert_eq!(bytes.len(), 32);
+ assert_eq!(bytes[24..], [0; 8]);
+ }
+
+ #[test]
+ fn records_are_appended_one_after_the_other() {
+ let mut commands = Vec::new();
+ let enable = commands::Enable { cap: 1 };
+ let viewport = commands::Viewport {
+ x: 1,
+ y: 2,
+ width: 3,
+ height: 4,
+ };
+ append_record(&mut commands, CommandType::Enable, enable.as_bytes(), InlineData::NONE);
+ append_record(
+ &mut commands,
+ CommandType::Viewport,
+ viewport.as_bytes(),
+ InlineData::NONE,
+ );
+ assert_eq!(commands.len(), 16 + 32);
+ assert_eq!(commands[..8], header(CommandType::Enable as u16, 8));
+ assert_eq!(commands[16..24], header(CommandType::Viewport as u16, 24));
+ }
+
+ #[test]
+ fn a_request_is_a_header_and_a_payload_padded_to_the_alignment() {
+ // NB: The replayer rejects a request whose payload is shorter than its struct, and the struct of a request
+ // without arguments is one byte in C++.
+ let mut request_bytes = vec![0xAA; 64];
+ encode_sync_request(
+ &mut request_bytes,
+ &sync_calls::GetErrorRequest::ZEROED,
+ InlineData::NONE,
+ );
+ assert_eq!(request_bytes.len(), 24);
+ assert_eq!(request_bytes[..8], header(SyncCallType::GetError as u16, 16));
+ assert_eq!(request_bytes[8..], [0; 16]);
+
+ let name = InlineData::NulTerminated(b"color");
+ let request = sync_calls::GetAttribLocationRequest {
+ program: 3,
+ name: DataSpan::following::<sync_calls::GetAttribLocationRequest>(name),
+ };
+ encode_sync_request(&mut request_bytes, &request, name);
+ assert_eq!(request_bytes.len(), 8 + 32);
+ assert_eq!(request_bytes[..8], header(SyncCallType::GetAttribLocation as u16, 32));
+ assert_eq!(request_bytes[8..20], *request.as_bytes());
+ assert_eq!(request_bytes[24..30], *b"color\0");
+ assert_eq!(request_bytes[30..], [0; 10]);
+ }
+
+ #[test]
+ fn a_reply_starts_with_its_struct() {
+ let mut reply = Vec::new();
+ reply.extend_from_slice(&5i32.to_ne_bytes());
+ reply.extend_from_slice(&[16, 0, 0, 0, 3, 0, 0, 0]);
+ reply.extend_from_slice(&[0; 4]);
+ reply.extend_from_slice(b"abc");
+ let decoded = sync_calls::GetShaderInfoLogReply::from_reply_bytes(&reply);
+ assert_eq!(decoded.length, 5);
+ assert_eq!(resolve_data_span(&reply, decoded.info_log), b"abc");
+ assert_eq!(resolve_data_span(&reply, DataSpan { offset: 19, size: 0 }), b"");
+ }
+
+ #[test]
+ #[should_panic(expected = "shorter than its struct")]
+ fn a_reply_that_is_shorter_than_its_struct_is_not_read() {
+ sync_calls::GetShaderInfoLogReply::from_reply_bytes(&[0; 11]);
+ }
+
+ #[test]
+ #[should_panic(expected = "lies inside the reply")]
+ fn a_span_that_leaves_the_reply_is_not_resolved() {
+ resolve_data_span(&[0; 16], DataSpan { offset: 12, size: 5 });
+ }
+}