Truly independent web browser
/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
use std::env;
use std::error::Error;
use std::fmt::Write;
use std::path::{Path, PathBuf};
// Mirrors title_casify() in Meta/Utils/utils.py.
fn title_casify(dashy_name: &str) -> String {
dashy_name
.split('-')
.filter(|part| !part.is_empty())
.map(|part| {
let mut chars = part.chars();
let first = chars.next().unwrap().to_ascii_uppercase();
format!("{first}{}", chars.as_str())
})
.collect()
}
fn generate_math_functions(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {
let math_functions_path = manifest_dir.parent().unwrap().join("CSS/MathFunctions.json");
println!("cargo:rerun-if-changed={}", math_functions_path.display());
let value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&math_functions_path)?)?;
let functions = value
.as_object()
.ok_or("MathFunctions.json does not contain a JSON object")?;
let mut output = String::from(
"// This file is generated from CSS/MathFunctions.json.\n\n\
#[derive(Clone, Copy, Debug, PartialEq, Eq)]\n\
pub(crate) enum MathFunction {\n\
Calc,\n",
);
for name in functions.keys() {
writeln!(output, " {},", title_casify(name))?;
}
output.push_str("}\n\npub(crate) fn math_function_from_name(name: &[u16]) -> Option<MathFunction> {\n");
output.push_str(" let equals = |expected: &[u8]| {\n");
output.push_str(" name.len() == expected.len() && name.iter().zip(expected).all(|(&left, &right)| {\n");
output.push_str(" u8::try_from(left).is_ok_and(|left| left.eq_ignore_ascii_case(&right))\n");
output.push_str(" })\n };\n");
output.push_str(" if equals(b\"calc\") { return Some(MathFunction::Calc); }\n");
for name in functions.keys() {
writeln!(
output,
" if equals(b\"{name}\") {{ return Some(MathFunction::{}); }}",
title_casify(name)
)?;
}
output.push_str(" None\n}\n");
std::fs::write(out_dir.join("math_functions_generated.rs"), output)?;
Ok(())
}
fn generate_media_features(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {
let media_features_path = manifest_dir.parent().unwrap().join("CSS/MediaFeatures.json");
println!("cargo:rerun-if-changed={}", media_features_path.display());
let value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&media_features_path)?)?;
let features = value
.as_object()
.ok_or("MediaFeatures.json does not contain a JSON object")?;
let mut output = String::from(
"// This file is generated from CSS/MediaFeatures.json.\n\n\
pub(crate) const MEDIA_FEATURE_VALUE_BOOLEAN: u8 = 1 << 0;\n\
pub(crate) const MEDIA_FEATURE_VALUE_INTEGER: u8 = 1 << 1;\n\
pub(crate) const MEDIA_FEATURE_VALUE_LENGTH: u8 = 1 << 2;\n\
pub(crate) const MEDIA_FEATURE_VALUE_RATIO: u8 = 1 << 3;\n\
pub(crate) const MEDIA_FEATURE_VALUE_RESOLUTION: u8 = 1 << 4;\n\
pub(crate) const MEDIA_FEATURE_VALUE_NUMBER: u8 = 1 << 5;\n\n\
pub(crate) struct MediaFeatureMetadata {\n\
pub name: &'static str,\n\
pub allows_range: bool,\n\
pub accepted_value_types: u8,\n\
pub accepted_keywords: &'static [u16],\n\
pub false_keywords: &'static [u16],\n\
pub implied_keywords: &'static [(u16, u16)],\n\
}\n\n\
pub(crate) const MEDIA_FEATURES: &[MediaFeatureMetadata] = &[\n",
);
for (name, feature) in features {
let allows_range = match feature["type"].as_str() {
Some("discrete") => false,
Some("range") => true,
_ => return Err(format!("unknown media feature type for {name}").into()),
};
let values = feature["values"]
.as_array()
.ok_or("media feature values is not an array")?;
let mut value_types = Vec::new();
let mut keywords = Vec::new();
for value in values {
let value = value.as_str().ok_or("media feature value is not a string")?;
match value {
"<mq-boolean>" => value_types.push("MEDIA_FEATURE_VALUE_BOOLEAN"),
"<integer>" => value_types.push("MEDIA_FEATURE_VALUE_INTEGER"),
"<number>" => value_types.push("MEDIA_FEATURE_VALUE_NUMBER"),
"<length>" => value_types.push("MEDIA_FEATURE_VALUE_LENGTH"),
"<ratio>" => value_types.push("MEDIA_FEATURE_VALUE_RATIO"),
"<resolution>" => value_types.push("MEDIA_FEATURE_VALUE_RESOLUTION"),
value if !value.starts_with('<') => keywords.push(value),
value => return Err(format!("unknown media feature value {value}").into()),
}
}
let value_types = if value_types.is_empty() {
"0".to_string()
} else {
value_types.join(" | ")
};
let keyword_constant = |keyword: &str| keyword.replace('-', "_").to_ascii_uppercase();
let accepted_keywords = keywords
.iter()
.map(|keyword| format!("crate::css::css_enums::keyword::{}", keyword_constant(keyword)))
.collect::<Vec<_>>()
.join(", ");
let false_keywords = feature
.get("false-keywords")
.and_then(serde_json::Value::as_array)
.map(|keywords| {
keywords
.iter()
.map(|keyword| {
let keyword = keyword.as_str().ok_or("false keyword is not a string")?;
Ok(format!("crate::css::css_enums::keyword::{}", keyword_constant(keyword)))
})
.collect::<Result<Vec<_>, Box<dyn Error>>>()
})
.transpose()?
.unwrap_or_default()
.join(", ");
// Each environment keyword maps to the queried keywords that it matches as well as itself.
let mut implied_keywords = Vec::new();
if let Some(implications) = feature.get("implied-keywords") {
let implications = implications.as_object().ok_or("implied keywords are not an object")?;
for (environment_keyword, queried_keywords) in implications {
let queried_keywords = queried_keywords
.as_array()
.ok_or("implied keywords of a keyword are not an array")?;
for queried_keyword in queried_keywords {
let queried_keyword = queried_keyword.as_str().ok_or("implied keyword is not a string")?;
implied_keywords.push(format!(
"(crate::css::css_enums::keyword::{}, crate::css::css_enums::keyword::{})",
keyword_constant(environment_keyword),
keyword_constant(queried_keyword)
));
}
}
}
let implied_keywords = implied_keywords.join(", ");
writeln!(
output,
" MediaFeatureMetadata {{ name: \"{name}\", allows_range: {allows_range}, accepted_value_types: {value_types}, accepted_keywords: &[{accepted_keywords}], false_keywords: &[{false_keywords}], implied_keywords: &[{implied_keywords}] }},"
)?;
}
output.push_str("];\n");
std::fs::write(out_dir.join("media_features_generated.rs"), output)?;
Ok(())
}
fn generate_named_colors(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {
let colors_path = manifest_dir
.parent()
.unwrap()
.parent()
.unwrap()
.join("LibGfx/Color.cpp");
println!("cargo:rerun-if-changed={}", colors_path.display());
let source = std::fs::read_to_string(&colors_path)?;
let table = source
.split_once("constexpr Array web_colors {")
.ok_or("Color.cpp has no web_colors table")?
.1
.split_once(" };")
.ok_or("Color.cpp has no end of web_colors table")?
.0;
let mut colors = Vec::new();
for line in table.lines().map(str::trim) {
let Some(entry) = line.strip_prefix("WebColor { 0x") else {
continue;
};
let (rgb, name) = entry.split_once(", \"").ok_or("malformed web_colors entry")?;
let name = name.strip_suffix("\"sv },").ok_or("malformed web_colors name")?;
let rgb = u32::from_str_radix(rgb, 16)?;
colors.push((name, rgb));
}
if colors.is_empty() {
return Err("Color.cpp web_colors table is empty".into());
}
let mut output = String::from(
"// Generated by build.rs from LibGfx/Color.cpp. Do not edit.\n\n\
#[allow(dead_code)]\n\
pub(crate) fn named_color_from_name(name: crate::css::css_tokenizer::TokenizerInput<'_>) -> Option<[u8; 4]> {\n\
let equals = |expected: &[u8]| {\n\
name.len() == expected.len() && (0..name.len()).zip(expected).all(|(index, &right)| {\n\
let left = name.code_unit_at(index);\n\
u8::try_from(left).is_ok_and(|left| left.eq_ignore_ascii_case(&right))\n\
})\n\
};\n",
);
for (name, rgb) in colors {
writeln!(
output,
" if equals(b\"{name}\") {{ return Some([0x{:02x}, 0x{:02x}, 0x{:02x}, 0xff]); }}",
rgb >> 16,
(rgb >> 8) & 0xff,
rgb & 0xff
)?;
}
output.push_str(" None\n}\n");
std::fs::write(out_dir.join("named_colors_generated.rs"), output)?;
Ok(())
}
fn generate_descriptor_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {
let descriptors_path = manifest_dir.parent().unwrap().join("CSS/Descriptors.json");
let properties_path = manifest_dir.parent().unwrap().join("CSS/Properties.json");
println!("cargo:rerun-if-changed={}", descriptors_path.display());
println!("cargo:rerun-if-changed={}", properties_path.display());
let value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&descriptors_path)?)?;
let properties: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&properties_path)?)?;
let at_rules = value
.as_object()
.ok_or("Descriptors.json does not contain a JSON object")?;
let properties = properties
.as_object()
.ok_or("Properties.json does not contain a JSON object")?;
let mut descriptor_names = at_rules
.values()
.flat_map(|at_rule| at_rule["descriptors"].as_object().unwrap())
.filter(|(_, descriptor)| descriptor.get("legacy-alias-for").is_none())
.map(|(name, _)| name.as_str())
.collect::<Vec<_>>();
descriptor_names.sort_unstable();
descriptor_names.dedup();
if descriptor_names.len() >= usize::from(u8::MAX) {
return Err("too many descriptors for u8 identifiers".into());
}
let descriptor_id = |name: &str| {
descriptor_names
.binary_search(&name)
.map(|id| id as u8)
.map_err(|_| format!("missing descriptor ID for {name}"))
};
let mut output = String::from(
"// Generated by build.rs from CSS/Descriptors.json. Do not edit.\n\n\
use crate::css::property_metadata::property_id;\n\n\
#[derive(Clone, Copy, Debug, PartialEq, Eq)]\n\
pub(crate) enum DescriptorSyntax { Keyword(&'static str), Property(u16), ValueType(DescriptorValueType) }\n\n\
#[derive(Clone, Copy, Debug, PartialEq, Eq)]\n\
pub(crate) enum DescriptorValueType { CounterStyleSystem, CounterStyleAdditiveSymbols, CounterStyleName, CounterStyleNegative, CounterStylePad, CounterStyleRange, CropOrCross, FamilyName, FontSrcList, FontWeightAbsolutePair, Length, OptionalDeclarationValue, PageSize, PositivePercentage, String, Symbol, Symbols, UnicodeRangeTokens }\n\n\
pub(crate) struct DescriptorMetadata { pub id: u8, pub syntax: &'static [DescriptorSyntax], pub allow_arbitrary_substitution_functions: bool, pub allow_css_wide_keywords: bool }\n\n\
#[derive(Clone, Copy, Debug, PartialEq, Eq)]\n\
pub(crate) struct DescriptorLonghand { pub descriptor_id: u8, pub property_id: u16, pub name: &'static str }\n\n\
fn equals(value: &[u16], expected: &[u8]) -> bool { value.len() == expected.len() && value.iter().zip(expected).all(|(&left, &right)| u8::try_from(left).is_ok_and(|left| left.eq_ignore_ascii_case(&right))) }\n\n\
pub(crate) fn descriptor_metadata(at_rule: u8, name: &[u16]) -> Option<DescriptorMetadata> {\n match at_rule {\n",
);
for (at_rule_index, (_at_rule_name, at_rule)) in at_rules.iter().enumerate() {
writeln!(output, " {at_rule_index} => {{")?;
let descriptors = at_rule["descriptors"].as_object().unwrap();
for (name, descriptor) in descriptors {
if let Some(alias) = descriptor.get("legacy-alias-for").and_then(serde_json::Value::as_str) {
writeln!(
output,
" if equals(name, b\"{name}\") {{ return descriptor_metadata(at_rule, &\"{alias}\".encode_utf16().collect::<Vec<_>>()); }}"
)?;
continue;
}
write!(
output,
" if equals(name, b\"{name}\") {{ return Some(DescriptorMetadata {{ id: {}, syntax: &[",
descriptor_id(name)?
)?;
for syntax in descriptor["syntax"]
.as_array()
.ok_or("descriptor syntax is not an array")?
{
let syntax = syntax.as_str().ok_or("descriptor syntax is not a string")?;
if let Some(property) = syntax.strip_prefix("<'").and_then(|value| value.strip_suffix("'>")) {
let constant = property.replace('-', "_").to_ascii_uppercase();
write!(output, "DescriptorSyntax::Property(property_id::{constant}),")?;
} else if syntax.starts_with('<') {
let value_type = match syntax {
"<family-name>" => "FamilyName",
"<font-src-list>" => "FontSrcList",
"<font-weight-absolute>{1,2}" => "FontWeightAbsolutePair",
"<declaration-value>?" => "OptionalDeclarationValue",
"<length>" => "Length",
"<page-size>" => "PageSize",
"<percentage [0,∞]>" => "PositivePercentage",
"<string>" => "String",
"<unicode-range-token>#" => "UnicodeRangeTokens",
"<counter-style-system>" => "CounterStyleSystem",
"<counter-style-negative>" => "CounterStyleNegative",
"<symbol>" => "Symbol",
"<symbol>+" => "Symbols",
"<counter-style-range>" => "CounterStyleRange",
"<counter-style-pad>" => "CounterStylePad",
"<counter-style-name>" => "CounterStyleName",
"<counter-style-additive-symbols>" => "CounterStyleAdditiveSymbols",
other => return Err(format!("unknown descriptor syntax {other}").into()),
};
write!(
output,
"DescriptorSyntax::ValueType(DescriptorValueType::{value_type}),"
)?;
} else if syntax == "crop || cross" {
write!(output, "DescriptorSyntax::ValueType(DescriptorValueType::CropOrCross),")?;
} else {
write!(output, "DescriptorSyntax::Keyword(\"{syntax}\"),")?;
}
}
writeln!(
output,
"], allow_arbitrary_substitution_functions: {}, allow_css_wide_keywords: {} }}); }}",
descriptor
.get("allow-arbitrary-substitution-functions")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false),
descriptor
.get("allow-css-wide-keywords")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false)
)?;
}
if let Some(custom) = at_rule.get("custom-descriptors") {
write!(
output,
" if name.starts_with(&[u16::from(b'-'), u16::from(b'-')]) && name.len() > 2 {{ return Some(DescriptorMetadata {{ id: {}, syntax: &[",
descriptor_names.len()
)?;
for syntax in custom["syntax"].as_array().unwrap() {
let property = syntax.as_str().unwrap().trim_start_matches("<'").trim_end_matches("'>");
let constant = property.replace('-', "_").to_ascii_uppercase();
write!(output, "DescriptorSyntax::Property(property_id::{constant}),")?;
}
writeln!(
output,
"], allow_arbitrary_substitution_functions: true, allow_css_wide_keywords: true }}); }}"
)?;
}
output.push_str(" None\n }\n");
}
output.push_str(" _ => None,\n }\n}\n");
writeln!(
output,
"\npub(crate) const CUSTOM_DESCRIPTOR_ID: u8 = {};",
descriptor_names.len()
)?;
output.push_str("\npub(crate) fn descriptor_longhands(at_rule: u8, descriptor_id: u8) -> &'static [DescriptorLonghand] {\n match (at_rule, descriptor_id) {\n");
for (at_rule_index, (_at_rule_name, at_rule)) in at_rules.iter().enumerate() {
let descriptors = at_rule["descriptors"].as_object().unwrap();
for (name, descriptor) in descriptors {
if descriptor.get("legacy-alias-for").is_some() {
continue;
}
let Some(property_name) = descriptor["syntax"]
.as_array()
.and_then(|syntax| (syntax.len() == 1).then(|| syntax[0].as_str()).flatten())
.and_then(|syntax| syntax.strip_prefix("<'"))
.and_then(|syntax| syntax.strip_suffix("'>"))
else {
continue;
};
let Some(longhands) = properties
.get(property_name)
.and_then(|property| property.get("longhands"))
.and_then(serde_json::Value::as_array)
else {
continue;
};
if longhands.is_empty() {
continue;
}
let mut generated_longhands = Vec::new();
for longhand in longhands {
let longhand = longhand.as_str().ok_or("property longhand is not a string")?;
if !descriptors.contains_key(longhand) {
generated_longhands.clear();
break;
}
generated_longhands.push((
descriptor_id(longhand)?,
longhand.replace('-', "_").to_ascii_uppercase(),
longhand,
));
}
if generated_longhands.is_empty() {
continue;
}
write!(output, " ({at_rule_index}, {}) => &[", descriptor_id(name)?)?;
for (longhand_id, property_constant, longhand_name) in generated_longhands {
write!(
output,
"DescriptorLonghand {{ descriptor_id: {longhand_id}, property_id: property_id::{property_constant}, name: \"{longhand_name}\" }},"
)?;
}
output.push_str("],\n");
}
}
output.push_str(" _ => &[],\n }\n}\n");
std::fs::write(out_dir.join("descriptor_metadata_generated.rs"), output)?;
Ok(())
}
fn ordered_pseudo_element_names(
pseudo_elements: &serde_json::Map<String, serde_json::Value>,
) -> Result<Vec<String>, Box<dyn Error>> {
let mut synthetic = Vec::new();
let mut element_reference = Vec::new();
let mut functional = Vec::new();
for (name, value) in pseudo_elements {
let object = value.as_object().unwrap();
if object.contains_key("alias-for") {
continue;
}
if object.get("type").and_then(|value| value.as_str()) == Some("function") {
functional.push(name.clone());
continue;
}
match object.get("implementation").and_then(|value| value.as_str()) {
Some("synthetic") => synthetic.push(name.clone()),
Some("element-reference") => element_reference.push(name.clone()),
other => return Err(format!("invalid or missing implementation type for ::{name}: {other:?}").into()),
}
}
synthetic.extend(element_reference);
synthetic.extend(functional);
Ok(synthetic)
}
fn load_property_groups(path: &Path) -> Result<std::collections::HashMap<String, Vec<String>>, Box<dyn Error>> {
let mut groups = std::collections::HashMap::new();
let mut current_group = None;
for raw_line in std::fs::read_to_string(path)?.lines() {
let line = raw_line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some(group) = line.strip_prefix('[').and_then(|line| line.strip_suffix(']')) {
groups.insert(format!("#{group}"), Vec::new());
current_group = Some(format!("#{group}"));
continue;
}
let Some(group) = current_group.as_ref() else {
return Err(format!("property outside a pseudo-element property group: {line}").into());
};
groups.get_mut(group).unwrap().push(line.to_string());
}
Ok(groups)
}
fn write_enum_and_from_ffi(output: &mut String, enum_name: &str, variants: &[String]) {
writeln!(output, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]").unwrap();
writeln!(output, "#[repr(u8)]").unwrap();
writeln!(output, "pub enum {enum_name} {{").unwrap();
for variant in variants {
writeln!(output, " {variant},").unwrap();
}
writeln!(output, "}}").unwrap();
writeln!(output).unwrap();
// The pseudo-classes cross the boundary as numbers, and parsed selectors hold both kinds as numbers.
let function_name = match enum_name {
"PseudoClassType" => "pseudo_class_from_ffi",
"PseudoElementType" => "pseudo_element_from_ffi",
_ => return,
};
writeln!(output, "pub(crate) fn {function_name}(value: u8) -> {enum_name} {{").unwrap();
writeln!(output, " match value {{").unwrap();
for (index, variant) in variants.iter().enumerate() {
writeln!(output, " {index} => {enum_name}::{variant},").unwrap();
}
writeln!(output, " _ => panic!(\"invalid {enum_name} {{value}}\"),").unwrap();
writeln!(output, " }}").unwrap();
writeln!(output, "}}").unwrap();
writeln!(output).unwrap();
}
// Generates the Rust twins of the C++ PseudoClass and PseudoElement enums from the same JSON
// sources as Meta/Generators/generate_libweb_css_pseudo_{class,element}.py, so the numeric
// values that cross the selector FFI cannot drift out of sync with the C++ side.
fn generate_selector_pseudo_types(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {
let css_dir = manifest_dir.parent().unwrap().join("CSS");
let pseudo_classes_path = css_dir.join("PseudoClasses.json");
let pseudo_elements_path = css_dir.join("PseudoElements.json");
println!("cargo:rerun-if-changed={}", pseudo_classes_path.display());
println!("cargo:rerun-if-changed={}", pseudo_elements_path.display());
let parse_object = |path: &Path| -> Result<serde_json::Map<String, serde_json::Value>, Box<dyn Error>> {
let value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(path)?)?;
match value {
serde_json::Value::Object(object) => Ok(object),
_ => Err(format!("{} does not contain a JSON object", path.display()).into()),
}
};
let pseudo_classes = parse_object(&pseudo_classes_path)?;
let pseudo_class_names = pseudo_classes
.iter()
.filter(|(_, value)| !value.as_object().unwrap().contains_key("legacy-alias-for"))
.map(|(name, _)| title_casify(name))
.collect::<Vec<_>>();
let state_fact_names = pseudo_classes
.iter()
.filter(|(_, value)| value["style-engine-state"].as_bool() == Some(true))
.map(|(name, _)| title_casify(name))
.collect::<Vec<_>>();
let pseudo_elements = parse_object(&pseudo_elements_path)?;
let mut pseudo_element_names = ordered_pseudo_element_names(&pseudo_elements)?
.iter()
.map(|name| title_casify(name))
.collect::<Vec<_>>();
// NB: The C++ generator emits UnknownWebKit after KnownPseudoElementCount, so its FFI value is
// the number of known pseudo-elements.
pseudo_element_names.push("UnknownWebKit".to_string());
let mut output = String::new();
writeln!(
output,
"// Generated by build.rs from CSS/PseudoClasses.json and CSS/PseudoElements.json."
)
.unwrap();
writeln!(output).unwrap();
write_enum_and_from_ffi(&mut output, "PseudoClassType", &pseudo_class_names);
write_enum_and_from_ffi(&mut output, "PseudoElementType", &pseudo_element_names);
writeln!(output, "#[allow(dead_code)]")?;
writeln!(output, "impl PseudoClassType {{")?;
writeln!(output, " pub(crate) fn from_name(name: &[u16]) -> Option<Self> {{")?;
for (name, value) in &pseudo_classes {
let target = value
.get("legacy-alias-for")
.and_then(serde_json::Value::as_str)
.unwrap_or(name);
writeln!(
output,
" if equals_ascii_case_insensitive(name, b\"{name}\") {{ return Some(Self::{}); }}",
title_casify(target)
)?;
}
writeln!(output, " None")?;
writeln!(output, " }}")?;
writeln!(output, " #[allow(dead_code)]")?;
writeln!(output, " pub(crate) fn name(self) -> &'static str {{")?;
writeln!(output, " match self {{")?;
for (name, value) in &pseudo_classes {
if value.as_object().unwrap().contains_key("legacy-alias-for") {
continue;
}
writeln!(output, " Self::{} => \"{name}\",", title_casify(name))?;
}
writeln!(output, " }}")?;
writeln!(output, " }}")?;
writeln!(output, " pub(crate) fn metadata(self) -> PseudoClassMetadata {{")?;
writeln!(output, " match self {{")?;
for (name, value) in &pseudo_classes {
let object = value.as_object().unwrap();
if object.contains_key("legacy-alias-for") {
continue;
}
let mut argument = object["argument"].as_str().unwrap();
let mut is_valid_as_identifier = argument.is_empty();
let is_valid_as_function = !argument.is_empty();
if argument.ends_with('?') {
is_valid_as_identifier = true;
argument = &argument[..argument.len() - 1];
}
let parameter_type = match argument {
"" => "None",
"<a-n-plus-b>" => "AnPlusB",
"<a-n-plus-b-of>" => "AnPlusBOf",
"<compound-selector>" => "CompoundSelector",
"<forgiving-selector-list>" => "ForgivingSelectorList",
"<forgiving-relative-selector-list>" => "ForgivingRelativeSelectorList",
"<ident>" => "Ident",
"<language-ranges>" => "LanguageRanges",
"<level>#" => "LevelList",
"<relative-selector-list>" => "RelativeSelectorList",
"<selector-list>" => "SelectorList",
_ => return Err(format!("unsupported pseudo-class parameter type {argument}").into()),
};
writeln!(
output,
" Self::{} => PseudoClassMetadata {{ parameter_type: PseudoClassParameterType::{parameter_type}, is_valid_as_function: {is_valid_as_function}, is_valid_as_identifier: {is_valid_as_identifier} }},",
title_casify(name)
)?;
}
writeln!(output, " }}")?;
writeln!(output, " }}")?;
writeln!(output, "}}")?;
writeln!(output, "#[allow(dead_code)]")?;
writeln!(output, "impl PseudoElementType {{")?;
writeln!(
output,
" pub(crate) fn from_name(name: &[u16]) -> Option<(Self, Option<&'static str>)> {{"
)?;
for (name, value) in &pseudo_elements {
let object = value.as_object().unwrap();
if object.get("is-internal").and_then(serde_json::Value::as_bool) == Some(true) {
continue;
}
let (target, serialized_alias) = match object.get("alias-for").and_then(serde_json::Value::as_str) {
Some(target) => (target, format!("Some(\"{name}\")")),
None => (name.as_str(), "None".to_string()),
};
writeln!(
output,
" if equals_ascii_case_insensitive(name, b\"{name}\") {{ return Some((Self::{}, {serialized_alias})); }}",
title_casify(target)
)?;
}
writeln!(output, " None")?;
writeln!(output, " }}")?;
writeln!(output, " #[allow(dead_code)]")?;
writeln!(output, " pub(crate) fn name(self) -> &'static str {{")?;
writeln!(output, " match self {{")?;
for (name, value) in &pseudo_elements {
if value.as_object().unwrap().contains_key("alias-for") {
continue;
}
writeln!(output, " Self::{} => \"{name}\",", title_casify(name))?;
}
writeln!(output, " Self::UnknownWebKit => unreachable!(),")?;
writeln!(output, " }}")?;
writeln!(output, " }}")?;
writeln!(output, " pub(crate) fn metadata(self) -> PseudoElementMetadata {{")?;
writeln!(output, " match self {{")?;
for (name, value) in &pseudo_elements {
let object = value.as_object().unwrap();
if object.contains_key("alias-for") {
continue;
}
let is_valid_as_function = object.get("type").and_then(serde_json::Value::as_str) == Some("function");
let is_valid_as_identifier = !is_valid_as_function;
let function_syntax = object.get("function-syntax").and_then(serde_json::Value::as_str);
if is_valid_as_function != function_syntax.is_some() {
return Err(format!("pseudo-element {name} has inconsistent type and function-syntax").into());
}
let parameter_type = match function_syntax {
None => "None",
Some("<compound-selector>") => "CompoundSelector",
Some("<highlight-name-selector>") => "HighlightNameSelector",
Some("<ident>+") => "IdentList",
Some("<pt-name-and-class-selector>") => "PTNameAndClassSelector",
Some(argument) => return Err(format!("unsupported pseudo-element parameter type {argument}").into()),
};
writeln!(
output,
" Self::{} => PseudoElementMetadata {{ parameter_type: PseudoElementParameterType::{parameter_type}, is_valid_as_function: {is_valid_as_function}, is_valid_as_identifier: {is_valid_as_identifier} }},",
title_casify(name)
)?;
}
writeln!(output, " Self::UnknownWebKit => unreachable!(),")?;
writeln!(output, " }}")?;
writeln!(output, " }}")?;
writeln!(output, "}}")?;
std::fs::write(out_dir.join("selector_pseudo_generated.rs"), output)?;
let mut state_facts = String::from(
"// Generated by build.rs from CSS/PseudoClasses.json.\n\n\
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]\n\
#[repr(u8)]\n\
pub enum StateFact {\n",
);
for name in &state_fact_names {
writeln!(state_facts, " {name},")?;
}
writeln!(state_facts, "}}\n\nimpl StateFact {{")?;
writeln!(state_facts, " pub const ALL: [Self; {}] = [", state_fact_names.len())?;
for name in &state_fact_names {
writeln!(state_facts, " Self::{name},")?;
}
state_facts.push_str(" ];\n}\n");
std::fs::write(out_dir.join("style_state_fact_generated.rs"), state_facts)?;
let mut compiler_mapping = String::from(
"// Generated by build.rs from CSS/PseudoClasses.json.\n\n\
pub(super) fn state_fact_for(pseudo_class: PseudoClassType) -> Option<StateFact> {\n\
\x20 match pseudo_class {\n",
);
for name in &state_fact_names {
writeln!(
compiler_mapping,
" PseudoClassType::{name} => Some(StateFact::{name}),"
)?;
}
compiler_mapping.push_str(" _ => None,\n }\n}\n");
std::fs::write(out_dir.join("style_state_fact_compiler_generated.rs"), compiler_mapping)?;
let mut ffi_state_facts = String::from(
"// Generated by build.rs from CSS/PseudoClasses.json.\n\n\
#[derive(Clone, Copy, PartialEq, Eq)]\n\
#[repr(u8)]\n\
#[expect(dead_code, reason = \"C++ constructs the variants\")]\n\
pub enum FfiStateFact {\n",
);
for (index, name) in state_fact_names.iter().enumerate() {
writeln!(ffi_state_facts, " {name} = {index},")?;
}
ffi_state_facts.push_str(
"}\n\n\
fn decode_state_fact(fact: FfiStateFact) -> StateFact {\n\
\x20 StateFact::ALL[fact as usize]\n\
}\n",
);
std::fs::write(out_dir.join("ffi_state_fact_generated.rs"), ffi_state_facts)?;
let mut cpp_mapping = String::from(
"// Generated by Rust/build.rs from CSS/PseudoClasses.json.\n\n\
static Optional<StyleEngineFFI::FfiStateFact> state_fact_for(PseudoClass pseudo_class)\n\
{\n\
\x20 switch (pseudo_class) {\n",
);
for name in &state_fact_names {
writeln!(
cpp_mapping,
" case PseudoClass::{name}:\n return StyleEngineFFI::FfiStateFact::{name};"
)?;
}
cpp_mapping.push_str(" default:\n return {};\n }\n}\n");
std::fs::write(out_dir.join("StyleEngineStateFactsGenerated.inc"), cpp_mapping)?;
let mut selector_mapping = String::from(
"// Generated by Rust/build.rs from CSS/PseudoClasses.json.\n\n\
// The pseudo-class of each state fact, by the fact's value.\n\
static constexpr Array pseudo_classes_by_state_fact {\n",
);
for name in &state_fact_names {
writeln!(selector_mapping, " CSS::PseudoClass::{name},")?;
}
selector_mapping.push_str("};\n");
std::fs::write(out_dir.join("SelectorStateFactsGenerated.inc"), selector_mapping)?;
Ok(())
}
// Generates the property metadata tables for the Rust style computation core from
// Properties.json, replicating the C++ generator's identifier assignment exactly:
// Custom is 0, then shorthands, inherited longhands and non-inherited longhands in
// JSON order, skipping legacy aliases. A C++ unit test compares the tables against
// the C++-generated equivalents so the two generators cannot drift.
fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {
let properties_path = manifest_dir.parent().unwrap().join("CSS/Properties.json");
println!("cargo:rerun-if-changed={}", properties_path.display());
let value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&properties_path)?)?;
let serde_json::Value::Object(properties) = value else {
return Err("Properties.json does not contain a JSON object".into());
};
let enums_path = manifest_dir.parent().unwrap().join("CSS/Enums.json");
let keywords_path = manifest_dir.parent().unwrap().join("CSS/Keywords.json");
println!("cargo:rerun-if-changed={}", enums_path.display());
println!("cargo:rerun-if-changed={}", keywords_path.display());
let enums_value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&enums_path)?)?;
let enums = enums_value
.as_object()
.ok_or("Enums.json does not contain a JSON object")?;
let keywords_value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&keywords_path)?)?;
let keywords = keywords_value.as_array().ok_or("Keywords.json is not an array")?;
let keyword_codes = keywords
.iter()
.enumerate()
.map(|(index, keyword)| (keyword.as_str().unwrap(), (index + 1) as u16))
.collect::<std::collections::HashMap<_, _>>();
// Logical alias properties take their metadata from the first physical property of
// their logical group, with local overrides, mirroring the C++ generator.
let groups_path = manifest_dir.parent().unwrap().join("CSS/LogicalPropertyGroups.json");
println!("cargo:rerun-if-changed={}", groups_path.display());
let groups_value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&groups_path)?)?;
let serde_json::Value::Object(groups) = groups_value else {
return Err("LogicalPropertyGroups.json does not contain a JSON object".into());
};
let first_physical_in_group =
|group_name: &str| -> Option<&str> { groups[group_name]["physical"].as_object()?.values().next()?.as_str() };
let property_field = |name: &str, field: &str| -> Option<serde_json::Value> {
let object = properties[name].as_object().unwrap();
if let Some(value) = object.get(field) {
return Some(value.clone());
}
let group = object.get("logical-alias-for")?.as_object()?.get("group")?.as_str()?;
let physical = first_physical_in_group(group)?;
properties[physical].as_object().unwrap().get(field).cloned()
};
let mut shorthands = Vec::new();
let mut inherited_longhands = Vec::new();
let mut noninherited_longhands = Vec::new();
for (name, value) in &properties {
let object = value.as_object().unwrap();
if object.contains_key("legacy-alias-for") {
continue;
}
// NB: The C++ generator populates the "all" shorthand's longhand list
// programmatically, so it has no explicit "longhands" key.
if object.contains_key("longhands") || name == "all" {
shorthands.push(name.clone());
} else if property_field(name, "inherited").unwrap().as_bool().unwrap() {
inherited_longhands.push(name.clone());
} else {
noninherited_longhands.push(name.clone());
}
}
// Identifier assignment: Custom = 0, then the three runs in order.
let mut ids = std::collections::HashMap::new();
for (index, name) in shorthands
.iter()
.chain(&inherited_longhands)
.chain(&noninherited_longhands)
.enumerate()
{
ids.insert(name.clone(), (index + 1) as u16);
}
let first_longhand = ids[&inherited_longhands[0]];
let last_longhand = ids[noninherited_longhands.last().unwrap()];
let first_inherited = ids[&inherited_longhands[0]];
let last_inherited = ids[inherited_longhands.last().unwrap()];
let pseudo_elements_path = manifest_dir.parent().unwrap().join("CSS/PseudoElements.json");
let property_groups_path = manifest_dir
.parent()
.unwrap()
.join("CSS/PseudoElementPropertyGroups.txt");
println!("cargo:rerun-if-changed={}", pseudo_elements_path.display());
println!("cargo:rerun-if-changed={}", property_groups_path.display());
let pseudo_elements_value: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&pseudo_elements_path)?)?;
let serde_json::Value::Object(pseudo_elements) = pseudo_elements_value else {
return Err("PseudoElements.json does not contain a JSON object".into());
};
let property_groups = load_property_groups(&property_groups_path)?;
let property_id = |name: &str| -> Result<u16, Box<dyn Error>> {
if name == "custom" {
return Ok(0);
}
ids.get(name)
.copied()
.ok_or_else(|| format!("unknown pseudo-element property '{name}'").into())
};
let property_ids = |entries: &[String]| -> Result<Vec<u16>, Box<dyn Error>> {
let mut result = std::collections::BTreeSet::new();
for entry in entries {
if entry.starts_with("FIXME:") {
continue;
}
if let Some(properties) = property_groups.get(entry) {
for property in properties {
result.insert(property_id(property)?);
}
} else if entry.starts_with('#') {
return Err(format!("unknown pseudo-element property group '{entry}'").into());
} else {
result.insert(property_id(entry)?);
}
}
Ok(result.into_iter().collect())
};
let transition_and_animation_pseudo_properties = property_ids(
property_groups
.get("#transition-and-animation-properties")
.ok_or("missing transition and animation pseudo-element property group")?,
)?;
let mut pseudo_property_whitelist_rows = Vec::new();
let mut pseudo_accepts_animations_rows = Vec::new();
for name in ordered_pseudo_element_names(&pseudo_elements)? {
let object = pseudo_elements[&name].as_object().unwrap();
pseudo_accepts_animations_rows.push(
object
.get("accepts-animations")
.and_then(serde_json::Value::as_bool)
.unwrap_or(true),
);
let Some(whitelist) = object.get("property-whitelist") else {
pseudo_property_whitelist_rows.push(" None,".to_string());
continue;
};
let entries = whitelist
.as_array()
.unwrap()
.iter()
.map(|entry| entry.as_str().unwrap().to_string())
.collect::<Vec<_>>();
let whitelist = property_ids(&entries)?;
pseudo_property_whitelist_rows.push(format!(" Some(&{whitelist:?}),"));
}
// UnknownWebKit follows the known pseudo-elements and accepts all properties.
pseudo_property_whitelist_rows.push(" None,".to_string());
pseudo_accepts_animations_rows.push(true);
// The longhands other longhands' computation reads, which are computed first.
let manual_order = [
// zoom is required to compute every length, including font-size.
"zoom",
// math-depth is required to compute font-size.
"math-depth",
// Font properties are required to absolutize font-relative units used in other properties, including line-height.
"font-family",
"font-feature-settings",
"font-kerning",
"font-optical-sizing",
"font-size",
"font-size-adjust",
"font-style",
"font-synthesis-style",
"font-synthesis-weight",
"font-variant-alternates",
"font-variant-caps",
"font-variant-east-asian",
"font-variant-emoji",
"font-variant-ligatures",
"font-variant-numeric",
"font-variant-position",
"font-variation-settings",
"font-weight",
"font-width",
"text-rendering",
// line-height is required to absolutize `lh` units used in other properties.
"line-height",
// color-scheme is required to compute light-dark() colors.
"color-scheme",
// background-image is required to compute the other background-* properties.
"background-image",
// direction and writing-mode are required to map logical properties to their physical counterparts.
"direction",
"writing-mode",
];
let mut order = Vec::new();
for name in manual_order {
order.push(ids[name]);
}
// NB: The remainder follows Properties.json iteration order across all longhands,
// matching the C++ generator, not grouped by inheritance.
for (name, value) in &properties {
let object = value.as_object().unwrap();
if object.contains_key("legacy-alias-for") || object.contains_key("longhands") || name == "all" {
continue;
}
if !manual_order.contains(&name.as_str()) {
order.push(ids[name]);
}
}
let mut levels = vec![0u8; (last_longhand - first_longhand + 1) as usize];
let mut animation_types = vec![0u8; levels.len()];
let mut layout_geometry_effects = vec![false; levels.len()];
let mut affects_layout = vec![false; levels.len()];
let mut affects_stacking_context = vec![false; levels.len()];
let mut affects_scrollable_overflow = vec![false; levels.len()];
let mut affects_accumulated_visual_contexts = vec![false; levels.len()];
let mut affects_hit_testing = vec![false; levels.len()];
let mut style_group_indices = vec![u8::MAX; levels.len()];
let mut initial_values = vec![String::new(); levels.len()];
let value_types = [
"anchor",
"anchor-size",
"angle",
"angle-percentage",
"background-position",
"basic-shape",
"color",
"corner-shape",
"counter",
"counter-style",
"custom-ident",
"dashed-ident",
"easing-function",
"filter-value-list",
"fit-content",
"flex",
"font-style",
"font-variant-alternates",
"font-variant-east-asian",
"font-variant-ligatures",
"font-variant-numeric",
"frequency",
"frequency-percentage",
"image",
"integer",
"length",
"length-percentage",
"number",
"opacity-value",
"opentype-tag",
"paint",
"percentage",
"position",
"ratio",
"rect",
"resolution",
"scroll-function",
"string",
"time",
"time-percentage",
"transform-function",
"transform-list",
"url",
"view-function",
"view-timeline-inset",
];
for name in inherited_longhands.iter().chain(&noninherited_longhands) {
let index = (ids[name] - first_longhand) as usize;
let requires_computation = property_field(name, "requires-computation").unwrap();
let level = match requires_computation.as_str().unwrap() {
"never" => 0u8,
"cascaded-value" => 1,
"non-inherited-value" => 2,
"always" => 3,
other => return Err(format!("unknown requires-computation '{other}' for {name}").into()),
};
levels[index] = level;
animation_types[index] = match property_field(name, "animation-type").unwrap().as_str().unwrap() {
"discrete" => 0,
"by-computed-value" => 1,
"repeatable-list" => 2,
"custom" => 3,
"none" => 4,
other => return Err(format!("unknown animation-type '{other}' for {name}").into()),
};
let metadata_flag = |field: &str, default| {
property_field(name, field)
.and_then(|value| value.as_bool())
.unwrap_or(default)
};
// Animation controls can select or retime an animation of any property, so their own
// direct layout metadata cannot bound the geometry they expose. Likewise, container-name
// can change which descendant container queries apply without changing its own box,
// color can change SVG bounds when stroke resolves currentColor, and the scroll-snap
// properties can re-snap a scroll container, which moves every box inside it. A test in
// property_metadata.rs checks this against property_may_resnap_scroll_container().
let may_affect_layout_geometry_indirectly = property_field(name, "style-group")
.is_some_and(|value| value.as_str() == Some("AnimationValues"))
|| matches!(
name.as_str(),
"color" | "container-name" | "scroll-snap-align" | "scroll-snap-stop" | "scroll-snap-type"
);
layout_geometry_effects[index] = metadata_flag("affects-layout", true)
|| metadata_flag("affects-accumulated-visual-contexts", false)
|| metadata_flag("affects-scrollable-overflow", false)
|| metadata_flag("affects-stacking-context", false)
|| may_affect_layout_geometry_indirectly;
affects_layout[index] = metadata_flag("affects-layout", true);
affects_stacking_context[index] = metadata_flag("affects-stacking-context", false);
affects_scrollable_overflow[index] = metadata_flag("affects-scrollable-overflow", false);
affects_accumulated_visual_contexts[index] = metadata_flag("affects-accumulated-visual-contexts", false);
affects_hit_testing[index] = metadata_flag("affects-hit-testing", false);
let style_group = property_field(name, "style-group").and_then(|value| value.as_str().map(str::to_owned));
style_group_indices[index] = match style_group.as_deref() {
Some("InheritedListTableValues") => 0,
Some("InheritedUIValues") => 1,
Some("InheritedSVGValues") => 2,
Some("InheritedTextValues") => 3,
Some("FontValues") => 4,
Some("AnimationValues") => 5,
Some("SVGResetValues") => 6,
Some("GridValues") => 7,
Some("AnchorValues") => 8,
Some("ContentValues") => 9,
Some("AlignmentValues") => 10,
Some("MiscLayoutValues") => 11,
Some("MiscInteractionValues") => 12,
Some("EffectsValues") => 13,
Some("MaskValues") => 14,
Some("TextResetValues") => 15,
Some("TransformValues") => 16,
Some("BackgroundValues") => 17,
Some("BorderValues") => 18,
Some("SizingValues") => 19,
Some("SurroundValues") => 20,
Some("BoxValues") => 21,
Some(group) => return Err(format!("unknown style group '{group}' for {name}").into()),
None => u8::MAX,
};
initial_values[index] = property_field(name, "initial")
.and_then(|value| value.as_str().map(str::to_string))
.ok_or_else(|| format!("missing initial value for {name}"))?;
}
let mut output = String::new();
output.push_str("// Generated by build.rs from CSS metadata. Do not edit.\n\n");
// Shorthand expansion tables for the cascade. The "all" shorthand expands to every
// longhand except direction and unicode-bidi, mirroring the C++ generator.
let mut shorthand_rows = Vec::new();
let mut immediate_longhands = Vec::new();
for name in &shorthands {
let longhand_names: Vec<String> = if name == "all" {
properties
.iter()
.filter(|(name, value)| {
let object = value.as_object().unwrap();
!object.contains_key("longhands")
&& !object.contains_key("legacy-alias-for")
&& name.as_str() != "all"
&& name.as_str() != "direction"
&& name.as_str() != "unicode-bidi"
})
.map(|(name, _)| name.clone())
.collect()
} else {
properties[name]["longhands"]
.as_array()
.unwrap()
.iter()
.map(|longhand| longhand.as_str().unwrap().to_string())
.collect()
};
let ids_row: Vec<u16> = longhand_names.iter().map(|longhand| ids[longhand]).collect();
shorthand_rows.push(format!(" &{ids_row:?},"));
immediate_longhands.push(longhand_names);
}
output.push_str(&format!(
"pub(crate) static SHORTHAND_EXPANSIONS: [&[u16]; {}] = [\n{}\n];\n\n",
shorthand_rows.len(),
shorthand_rows.join("\n")
));
let property_names: Vec<&str> = shorthands
.iter()
.chain(&inherited_longhands)
.chain(&noninherited_longhands)
.map(String::as_str)
.collect();
// The C++ property-name generator accepts legacy aliases but maps them to
// their canonical IDs instead of assigning separate IDs.
let mut property_name_lookup: Vec<(&str, u16)> = properties
.iter()
.map(|(name, value)| {
let object = value.as_object().unwrap();
let target = object
.get("legacy-alias-for")
.and_then(serde_json::Value::as_str)
.unwrap_or(name);
(name.as_str(), ids[target])
})
.collect();
property_name_lookup.sort_unstable_by(|left, right| left.0.cmp(right.0));
let longhand_names: Vec<&str> = inherited_longhands
.iter()
.chain(&noninherited_longhands)
.map(String::as_str)
.collect();
const WRITING_MODE_COUNT: usize = 5;
const DIRECTION_COUNT: usize = 2;
const LOGICAL_CONTEXT_COUNT: usize = WRITING_MODE_COUNT * DIRECTION_COUNT;
let mut logical_alias_to_physical = vec![0u16; longhand_names.len() * LOGICAL_CONTEXT_COUNT];
for (longhand_index, name) in longhand_names.iter().enumerate() {
let Some(alias) = properties[*name]
.get("logical-alias-for")
.and_then(serde_json::Value::as_object)
else {
continue;
};
let group_name = alias["group"].as_str().unwrap();
let mapping = alias["mapping"].as_str().unwrap();
let physical = groups[group_name]["physical"].as_object().unwrap();
for writing_mode in 0..WRITING_MODE_COUNT {
for direction in 0..DIRECTION_COUNT {
let ltr = direction == 0;
let physical_name = match mapping {
"block-end" => match writing_mode {
0 => "bottom",
1 | 3 => "left",
_ => "right",
},
"block-size" => {
if writing_mode == 0 {
"height"
} else {
"width"
}
}
"block-start" => match writing_mode {
0 => "top",
1 | 3 => "right",
_ => "left",
},
"block-xy" => {
if writing_mode == 0 {
"y"
} else {
"x"
}
}
"end-end" => match writing_mode {
0 => {
if ltr {
"bottom-right"
} else {
"bottom-left"
}
}
1 | 3 => {
if ltr {
"bottom-left"
} else {
"top-left"
}
}
2 => {
if ltr {
"bottom-right"
} else {
"top-right"
}
}
_ => {
if ltr {
"top-right"
} else {
"bottom-right"
}
}
},
"end-start" => match writing_mode {
0 => {
if ltr {
"bottom-left"
} else {
"bottom-right"
}
}
1 | 3 => {
if ltr {
"top-left"
} else {
"bottom-left"
}
}
2 => {
if ltr {
"top-right"
} else {
"bottom-right"
}
}
_ => {
if ltr {
"bottom-right"
} else {
"top-right"
}
}
},
"inline-end" => match writing_mode {
0 => {
if ltr {
"right"
} else {
"left"
}
}
1..=3 => {
if ltr {
"bottom"
} else {
"top"
}
}
_ => {
if ltr {
"top"
} else {
"bottom"
}
}
},
"inline-size" => {
if writing_mode == 0 {
"width"
} else {
"height"
}
}
"inline-start" => match writing_mode {
0 => {
if ltr {
"left"
} else {
"right"
}
}
1..=3 => {
if ltr {
"top"
} else {
"bottom"
}
}
_ => {
if ltr {
"bottom"
} else {
"top"
}
}
},
"inline-xy" => {
if writing_mode == 0 {
"x"
} else {
"y"
}
}
"start-end" => match writing_mode {
0 => {
if ltr {
"top-right"
} else {
"top-left"
}
}
1 | 3 => {
if ltr {
"bottom-right"
} else {
"top-right"
}
}
2 => {
if ltr {
"bottom-left"
} else {
"top-left"
}
}
_ => {
if ltr {
"top-left"
} else {
"bottom-left"
}
}
},
"start-start" => match writing_mode {
0 => {
if ltr {
"top-left"
} else {
"top-right"
}
}
1 | 3 => {
if ltr {
"top-right"
} else {
"bottom-right"
}
}
2 => {
if ltr {
"top-left"
} else {
"bottom-left"
}
}
_ => {
if ltr {
"bottom-left"
} else {
"top-left"
}
}
},
_ => return Err(format!("unknown logical property mapping '{mapping}'").into()),
};
let property_name = physical[physical_name].as_str().unwrap();
let index = (longhand_index * WRITING_MODE_COUNT + writing_mode) * DIRECTION_COUNT + direction;
logical_alias_to_physical[index] = ids[property_name];
}
}
}
let mut physical_to_logical_alias = vec![0u16; logical_alias_to_physical.len()];
for (longhand_index, name) in longhand_names.iter().enumerate() {
let logical_property_id = ids[*name];
for writing_mode in 0..WRITING_MODE_COUNT {
for direction in 0..DIRECTION_COUNT {
let context_index = writing_mode * DIRECTION_COUNT + direction;
let physical_property_id =
logical_alias_to_physical[longhand_index * LOGICAL_CONTEXT_COUNT + context_index];
if physical_property_id == 0 {
continue;
}
let physical_index = usize::from(physical_property_id - first_longhand);
let reverse_index = physical_index * LOGICAL_CONTEXT_COUNT + context_index;
assert_eq!(physical_to_logical_alias[reverse_index], 0);
physical_to_logical_alias[reverse_index] = logical_property_id;
}
}
}
fn expanded_longhands(
name: &str,
properties: &serde_json::Map<String, serde_json::Value>,
all_longhands: &[String],
result: &mut Vec<String>,
) {
if name == "all" {
result.extend_from_slice(all_longhands);
return;
}
let Some(longhands) = properties[name].get("longhands").and_then(|value| value.as_array()) else {
result.push(name.to_string());
return;
};
for longhand in longhands {
expanded_longhands(longhand.as_str().unwrap(), properties, all_longhands, result);
}
}
let all_longhands: Vec<String> = inherited_longhands
.iter()
.chain(&noninherited_longhands)
.filter(|name| name.as_str() != "direction" && name.as_str() != "unicode-bidi")
.cloned()
.collect();
let expanded_shorthand_longhands: Vec<Vec<String>> = shorthands
.iter()
.map(|name| {
let mut result = Vec::new();
expanded_longhands(name, &properties, &all_longhands, &mut result);
result
})
.collect();
let camel_case_property_name = |name: &str| {
let mut parts = name.split('-').filter(|part| !part.is_empty());
let mut result = parts.next().unwrap_or_default().to_string();
for part in parts {
let mut characters = part.chars();
if let Some(first) = characters.next() {
result.extend(first.to_uppercase());
result.extend(characters);
}
}
result
};
let idl_names: Vec<String> = property_names
.iter()
.map(|name| camel_case_property_name(name))
.collect();
let logical_aliases: Vec<bool> = property_names
.iter()
.enumerate()
.map(|(index, name)| {
let name: &str = if index < shorthands.len() {
expanded_shorthand_longhands[index][0].as_str()
} else {
name
};
properties[name].as_object().unwrap().contains_key("logical-alias-for")
})
.collect();
if groups.len() >= u8::MAX as usize {
return Err("too many logical property groups".into());
}
let mut logical_group_by_property = std::collections::HashMap::new();
for (index, group) in groups.values().enumerate() {
let group_id = (index + 1) as u8;
for member_kind in ["physical", "logical"] {
for property_name in group[member_kind].as_object().unwrap().values() {
logical_group_by_property.insert(property_name.as_str().unwrap(), group_id);
}
}
}
let logical_groups: Vec<u8> = property_names
.iter()
.map(|name| logical_group_by_property.get(name).copied().unwrap_or(0))
.collect();
let expanded_longhand_counts: Vec<usize> = expanded_shorthand_longhands.iter().map(Vec::len).collect();
let expanded_longhand_rows: Vec<String> = expanded_shorthand_longhands
.iter()
.map(|longhands| {
let row: Vec<u16> = longhands.iter().map(|longhand| ids[longhand]).collect();
format!(" &{row:?},")
})
.collect();
// Each property's shorthands, in preferred order: the most longhands first, then those not starting with "-",
// then those starting with "-webkit-", then lexicographically.
// https://drafts.csswg.org/cssom/#concept-shorthands-preferred-order
let is_legacy_shorthand = |name: &str| {
properties[name]
.get("legacy-shorthand")
.and_then(|value| value.as_bool())
};
let mut immediate_shorthands = std::collections::HashMap::<&str, Vec<&str>>::new();
for (name, longhands) in shorthands.iter().zip(&immediate_longhands) {
if is_legacy_shorthand(name) == Some(true) {
continue;
}
for longhand in longhands {
immediate_shorthands.entry(longhand).or_default().push(name);
}
}
fn shorthands_of<'a>(
property: &str,
immediate_shorthands: &std::collections::HashMap<&str, Vec<&'a str>>,
result: &mut Vec<&'a str>,
) {
for shorthand in immediate_shorthands.get(property).into_iter().flatten() {
result.push(shorthand);
shorthands_of(shorthand, immediate_shorthands, result);
}
}
let expanded_longhand_count = |shorthand: &str| {
let index = shorthands.iter().position(|name| name == shorthand).unwrap();
expanded_longhand_counts[index]
};
let shorthands_for_longhand_rows: Vec<String> = property_names
.iter()
.map(|name| {
let mut result = Vec::new();
shorthands_of(name, &immediate_shorthands, &mut result);
result.sort_by_key(|shorthand| {
(
std::cmp::Reverse(expanded_longhand_count(shorthand)),
shorthand.starts_with('-'),
!shorthand.starts_with("-webkit-"),
*shorthand,
)
});
let row: Vec<u16> = result.iter().map(|shorthand| ids[*shorthand]).collect();
format!(" &{row:?},")
})
.collect();
let mut legacy_shorthands: Vec<u16> = shorthands
.iter()
.filter(|name| is_legacy_shorthand(name) == Some(true))
.map(|name| ids[name])
.collect();
legacy_shorthands.sort_unstable();
// Accepted property keywords are a property's valid identifiers and the
// keywords of the enums in its valid types.
let mut accepted_keyword_rows = Vec::new();
let mut accepted_value_type_rows = Vec::new();
let mut custom_ident_blacklist_rows = Vec::new();
let mut keyword_alias_rows = Vec::new();
let mut keyword_only_rows = Vec::new();
let mut coordinating_list_rows = Vec::new();
let mut maximum_value_count_rows = Vec::new();
let mut percentages_resolve_to_rows = Vec::new();
let mut numeric_range_rows = Vec::new();
let mut unitless_length_quirk_rows = Vec::new();
let mut hashless_hex_color_quirk_rows = Vec::new();
for name in &property_names {
let mut accepted_keywords = std::collections::BTreeSet::new();
let mut keyword_aliases = Vec::new();
if let Some(valid_identifiers) =
property_field(name, "valid-identifiers").and_then(|value| value.as_array().cloned())
{
for identifier in valid_identifiers {
let identifier = identifier.as_str().unwrap();
let (accepted, resolved) = identifier.split_once('>').unwrap_or((identifier, identifier));
accepted_keywords.insert(
*keyword_codes
.get(accepted)
.ok_or("property identifier is not a CSS keyword")?,
);
if accepted != resolved {
keyword_aliases.push((
*keyword_codes
.get(accepted)
.ok_or("property alias is not a CSS keyword")?,
*keyword_codes
.get(resolved)
.ok_or("property alias target is not a CSS keyword")?,
));
}
}
}
let valid_types = property_field(name, "valid-types")
.and_then(|value| value.as_array().cloned())
.unwrap_or_default();
let accepted_value_types = valid_types
.iter()
.filter_map(|valid_type| {
let type_name = valid_type.as_str().unwrap().split(' ').next().unwrap();
if enums.contains_key(type_name) {
return None;
}
Some(
value_types
.iter()
.position(|candidate| *candidate == type_name)
.ok_or_else(|| format!("unknown value type '{type_name}' for {name}")),
)
})
.collect::<Result<Vec<_>, _>>()?;
accepted_value_type_rows.push(format!(" &{accepted_value_types:?},"));
let custom_ident_blacklist = valid_types
.iter()
.filter_map(|valid_type| {
let valid_type = valid_type.as_str().unwrap();
let parameters = valid_type.strip_prefix("custom-ident ![")?.strip_suffix(']')?;
Some(parameters.split(','))
})
.flatten()
.collect::<Vec<_>>();
custom_ident_blacklist_rows.push(format!(" &{custom_ident_blacklist:?},"));
for valid_type in &valid_types {
let type_name = valid_type.as_str().unwrap().split(' ').next().unwrap();
let Some(values) = enums.get(type_name).and_then(serde_json::Value::as_array) else {
continue;
};
for value in values {
let value = value.as_str().unwrap();
let accepted = value.split_once('=').map_or(value, |(alias, _)| alias);
accepted_keywords.insert(*keyword_codes.get(accepted).ok_or("enum value is not a CSS keyword")?);
}
}
accepted_keyword_rows.push(format!(" &{:?},", accepted_keywords.into_iter().collect::<Vec<_>>()));
keyword_alias_rows.push(format!(" &{keyword_aliases:?},"));
keyword_only_rows.push(
(!valid_types.is_empty()
&& valid_types.iter().all(|valid_type| {
let type_name = valid_type.as_str().unwrap().split(' ').next().unwrap();
enums.contains_key(type_name)
}))
|| (valid_types.is_empty()
&& property_field(name, "valid-identifiers")
.and_then(|value| value.as_array().cloned())
.is_some_and(|identifiers| !identifiers.is_empty())),
);
coordinating_list_rows.push(
property_field(name, "multiplicity").and_then(|value| value.as_str().map(str::to_string))
== Some("coordinating-list".to_string()),
);
maximum_value_count_rows.push(
property_field(name, "max-values")
.and_then(|value| value.as_u64())
.unwrap_or(1),
);
percentages_resolve_to_rows.push(match property_field(name, "percentages-resolve-to") {
Some(value) => {
let type_name = value.as_str().unwrap();
let value_type = value_types
.iter()
.position(|candidate| *candidate == type_name)
.ok_or_else(|| format!("unknown percentage resolution type '{type_name}' for {name}"))?;
format!(" Some({value_type}),")
}
None => " None,".to_string(),
});
let mut ranges = Vec::new();
if let Some(valid_types) = property_field(name, "valid-types").and_then(|value| value.as_array().cloned()) {
for valid_type in valid_types {
let valid_type = valid_type.as_str().unwrap();
let Some((type_name, range)) = valid_type.split_once(' ') else {
continue;
};
if !range.starts_with('[') || !range.ends_with(']') || !range.contains(',') {
continue;
}
if type_name == "custom-ident" {
continue;
}
let value_type = value_types
.iter()
.position(|candidate| *candidate == type_name)
.ok_or_else(|| format!("unknown ranged value type '{type_name}' for {name}"))?;
let (min, max) = range[1..range.len() - 1]
.split_once(',')
.ok_or_else(|| format!("bad numeric range '{range}' for {name}"))?;
let format_bound = |bound: &str| match (type_name, bound) {
("integer", "-∞") => "i32::MIN as f64".to_string(),
("integer", "∞") => "i32::MAX as f64".to_string(),
(_, "-∞") => "f32::MIN as f64".to_string(),
(_, "∞") => "f32::MAX as f64".to_string(),
_ if bound.contains('.') => bound.to_string(),
_ => format!("{bound}.0"),
};
ranges.push(format!(
"FfiPropertyNumericRange {{ value_type: {value_type}, min: {}, max: {} }}",
format_bound(min),
format_bound(max)
));
}
}
numeric_range_rows.push(ranges.join(", "));
unitless_length_quirk_rows.push(
property_field(name, "quirks")
.and_then(|value| value.as_array().cloned())
.is_some_and(|quirks| quirks.iter().any(|quirk| quirk.as_str() == Some("unitless-length"))),
);
hashless_hex_color_quirk_rows.push(
property_field(name, "quirks")
.and_then(|value| value.as_array().cloned())
.is_some_and(|quirks| quirks.iter().any(|quirk| quirk.as_str() == Some("hashless-hex-color"))),
);
}
output.push_str(&format!(
"pub(crate) static PROPERTY_NAMES: [&str; {}] = {:?};\n",
property_names.len(),
property_names
));
output.push_str(&format!(
"pub(crate) static PROPERTY_NAME_LOOKUP: [(&str, u16); {}] = {:?};\n",
property_name_lookup.len(),
property_name_lookup
));
output.push_str(&format!(
"pub(crate) static PROPERTY_IDL_NAMES: [&str; {}] = {:?};\n",
idl_names.len(),
idl_names
));
// The IDL attribute names of the properties and of their legacy aliases, ASCII-lowercased and sorted, with the
// ids they name, as the C++ generator's case-insensitive table of them looks them up. A later name wins where two
// lowercase alike, as it does in that table.
let mut camel_case_lookup: Vec<(String, u16)> = Vec::new();
for (name, value) in &properties {
let object = value.as_object().unwrap();
let target = object
.get("legacy-alias-for")
.and_then(serde_json::Value::as_str)
.unwrap_or(name);
let key = camel_case_property_name(name).to_ascii_lowercase();
camel_case_lookup.retain(|(existing, _)| *existing != key);
camel_case_lookup.push((key, ids[target]));
}
camel_case_lookup.sort_unstable_by(|left, right| left.0.cmp(&right.0));
output.push_str(&format!(
"pub(crate) static PROPERTY_CAMEL_CASE_LOOKUP: [(&str, u16); {}] = {:?};\n",
camel_case_lookup.len(),
camel_case_lookup
));
output.push_str(&format!(
"pub(crate) const PROPERTY_IS_LOGICAL_ALIAS: [bool; {}] = {:?};\n\n",
logical_aliases.len(),
logical_aliases
));
output.push_str(&format!(
"pub(crate) static PROPERTY_LOGICAL_GROUPS: [u8; {}] = {:?};\n\n",
logical_groups.len(),
logical_groups
));
output.push_str(&format!(
"pub(crate) const LOGICAL_ALIAS_TO_PHYSICAL: [u16; {}] = {:?};\n\n",
logical_alias_to_physical.len(),
logical_alias_to_physical
));
output.push_str(&format!(
"pub(crate) static PHYSICAL_TO_LOGICAL_ALIAS: [u16; {}] = {:?};\n\n",
physical_to_logical_alias.len(),
physical_to_logical_alias
));
output.push_str(&format!(
"pub(crate) static EXPANDED_LONGHANDS_FOR_SHORTHAND: [&[u16]; {}] = [\n{}\n];\n\n",
expanded_longhand_rows.len(),
expanded_longhand_rows.join("\n")
));
output.push_str(&format!(
"pub(crate) static SHORTHANDS_FOR_LONGHAND: [&[u16]; {}] = [\n{}\n];\n\n",
shorthands_for_longhand_rows.len(),
shorthands_for_longhand_rows.join("\n")
));
output.push_str(&format!(
"pub(crate) static LEGACY_SHORTHANDS: &[u16] = &{legacy_shorthands:?};\n\n"
));
output.push_str(&format!(
"pub(crate) static SHORTHAND_EXPANDED_LONGHAND_COUNTS: [usize; {}] = {:?};\n\n",
expanded_longhand_counts.len(),
expanded_longhand_counts
));
output.push_str(&format!(
"pub(crate) static PROPERTY_ACCEPTED_KEYWORDS: [&[u16]; {}] = [\n{}\n];\n\n",
accepted_keyword_rows.len(),
accepted_keyword_rows.join("\n")
));
output.push_str(&format!(
"pub(crate) static PROPERTY_ACCEPTED_VALUE_TYPES: [&[u8]; {}] = [\n{}\n];\n\n",
accepted_value_type_rows.len(),
accepted_value_type_rows.join("\n")
));
output.push_str(&format!(
"pub(crate) static PROPERTY_CUSTOM_IDENT_BLACKLISTS: [&[&str]; {}] = [\n{}\n];\n\n",
custom_ident_blacklist_rows.len(),
custom_ident_blacklist_rows.join("\n")
));
output.push_str(&format!(
"pub(crate) static PROPERTY_KEYWORD_ALIASES: [&[(u16, u16)]; {}] = [\n{}\n];\n\n",
keyword_alias_rows.len(),
keyword_alias_rows.join("\n")
));
output.push_str(&format!(
"pub(crate) static PROPERTY_ACCEPTS_ONLY_KEYWORDS: [bool; {}] = {:?};\n",
keyword_only_rows.len(),
keyword_only_rows
));
output.push_str(&format!(
"pub(crate) static PROPERTY_HAS_COORDINATING_LIST_MULTIPLICITY: [bool; {}] = {:?};\n\n",
coordinating_list_rows.len(),
coordinating_list_rows
));
output.push_str(&format!(
"pub(crate) static PROPERTY_MAXIMUM_VALUE_COUNTS: [u64; {}] = {:?};\n\n",
maximum_value_count_rows.len(),
maximum_value_count_rows
));
output.push_str(&format!(
"pub(crate) static PROPERTY_PERCENTAGES_RESOLVE_TO: [Option<u8>; {}] = [\n{}\n];\n",
percentages_resolve_to_rows.len(),
percentages_resolve_to_rows.join("\n")
));
output.push_str(&format!(
"pub(crate) static PROPERTY_HAS_UNITLESS_LENGTH_QUIRK: [bool; {}] = {:?};\n\n",
unitless_length_quirk_rows.len(),
unitless_length_quirk_rows
));
output.push_str(&format!(
"pub(crate) static PROPERTY_HAS_HASHLESS_HEX_COLOR_QUIRK: [bool; {}] = {:?};\n\n",
hashless_hex_color_quirk_rows.len(),
hashless_hex_color_quirk_rows
));
output.push_str(&format!(
"pub const FIRST_SHORTHAND_PROPERTY_ID: u16 = {};\n",
ids[&shorthands[0]]
));
output.push_str(&format!(
"pub const LAST_SHORTHAND_PROPERTY_ID: u16 = {};\n\n",
ids[shorthands.last().unwrap()]
));
output.push_str("#[allow(dead_code)]\npub mod property_id {\n");
output.push_str(" pub const CUSTOM: u16 = 0;\n");
for name in shorthands
.iter()
.chain(&inherited_longhands)
.chain(&noninherited_longhands)
{
let constant = name.replace('-', "_").to_uppercase();
output.push_str(&format!(" pub const {constant}: u16 = {};\n", ids[name]));
}
output.push_str("}\n\n");
output.push_str(&format!(
"pub const FIRST_LONGHAND_PROPERTY_ID: u16 = {first_longhand};\n"
));
output.push_str(&format!(
"pub const LAST_LONGHAND_PROPERTY_ID: u16 = {last_longhand};\n"
));
output.push_str(&format!(
"pub const FIRST_INHERITED_PROPERTY_ID: u16 = {first_inherited};\n"
));
output.push_str(&format!(
"pub const LAST_INHERITED_PROPERTY_ID: u16 = {last_inherited};\n\n"
));
output.push_str(&format!(
"pub(crate) static PROPERTY_COMPUTATION_ORDER: [u16; {}] = {:?};\n\n",
order.len(),
order
));
output.push_str(&format!(
"pub(crate) static REQUIRES_COMPUTATION_LEVELS: [u8; {}] = {:?};\n",
levels.len(),
levels
));
output.push_str(&format!(
"pub(crate) static PROPERTY_ANIMATION_TYPES: [u8; {}] = {:?};\n",
animation_types.len(),
animation_types
));
output.push_str(&format!(
"pub(crate) static PROPERTY_MAY_AFFECT_LAYOUT_GEOMETRY: [bool; {}] = {:?};\n",
layout_geometry_effects.len(),
layout_geometry_effects
));
output.push_str(&format!(
"pub(crate) static PROPERTY_AFFECTS_LAYOUT: [bool; {}] = {:?};\n",
affects_layout.len(),
affects_layout
));
output.push_str(&format!(
"pub(crate) static PROPERTY_AFFECTS_STACKING_CONTEXT: [bool; {}] = {:?};\n",
affects_stacking_context.len(),
affects_stacking_context
));
output.push_str(&format!(
"pub(crate) static PROPERTY_AFFECTS_SCROLLABLE_OVERFLOW: [bool; {}] = {:?};\n",
affects_scrollable_overflow.len(),
affects_scrollable_overflow
));
output.push_str(&format!(
"pub(crate) static PROPERTY_AFFECTS_ACCUMULATED_VISUAL_CONTEXTS: [bool; {}] = {:?};\n",
affects_accumulated_visual_contexts.len(),
affects_accumulated_visual_contexts
));
output.push_str(&format!(
"pub(crate) static PROPERTY_AFFECTS_HIT_TESTING: [bool; {}] = {:?};\n",
affects_hit_testing.len(),
affects_hit_testing
));
output.push_str(&format!(
"pub(crate) const PROPERTY_STYLE_GROUP_INDICES: [u8; {}] = {:?};\n",
style_group_indices.len(),
style_group_indices
));
output.push_str(&format!(
"pub(crate) static PROPERTY_INITIAL_VALUES: [&str; {}] = {:?};\n",
initial_values.len(),
initial_values
));
output.push_str(&format!(
"pub(crate) static PROPERTY_NUMERIC_RANGES: [&[FfiPropertyNumericRange]; {}] = [\n{}\n];\n",
numeric_range_rows.len(),
numeric_range_rows
.iter()
.map(|ranges| format!(" &[{ranges}],"))
.collect::<Vec<_>>()
.join("\n")
));
output.push_str(&format!(
"\npub(crate) static PSEUDO_ELEMENT_TRANSITION_AND_ANIMATION_PROPERTIES: &[u16] = &{transition_and_animation_pseudo_properties:?};\n"
));
let positional_shorthands: Vec<u16> = properties
.iter()
.filter(|(_, value)| {
value.as_object().is_some_and(|object| {
object
.get("positional-value-list-shorthand")
.and_then(|flag| flag.as_bool())
== Some(true)
})
})
.map(|(name, _)| ids[name])
.collect();
output.push_str(&format!(
"\npub(crate) static POSITIONAL_VALUE_LIST_SHORTHANDS: &[u16] = &{positional_shorthands:?};\n"
));
output.push_str(&format!(
"pub(crate) static PSEUDO_ELEMENT_PROPERTY_WHITELISTS: [Option<&[u16]>; {}] = [\n{}\n];\n",
pseudo_property_whitelist_rows.len(),
pseudo_property_whitelist_rows.join("\n")
));
output.push_str(&format!(
"pub(crate) static PSEUDO_ELEMENT_ACCEPTS_ANIMATIONS: [bool; {}] = {pseudo_accepts_animations_rows:?};\n",
pseudo_accepts_animations_rows.len(),
));
std::fs::write(out_dir.join("property_metadata_generated.rs"), output)?;
Ok(())
}
// Generates the length unit table for the Rust style computation core from Units.json.
// Unit codes are the alphabetical index within the "length" object, matching the C++
// LengthUnit enum; absolute units carry their canonical px ratio.
fn generate_length_units(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {
let units_path = manifest_dir.parent().unwrap().join("CSS/Units.json");
println!("cargo:rerun-if-changed={}", units_path.display());
let value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&units_path)?)?;
let lengths = value["length"].as_object().ok_or("Units.json has no length object")?;
let mut names = Vec::new();
let mut ratios = Vec::new();
for (name, unit) in lengths {
names.push(name.clone());
let object = unit.as_object().unwrap();
if object
.get("is-canonical-unit")
.is_some_and(|canonical| canonical.as_bool() == Some(true))
{
ratios.push("1.0".to_string());
} else if let Some(ratio) = object.get("number-of-canonical-unit") {
ratios.push(format!("{:?}", ratio.as_f64().unwrap()));
} else {
ratios.push("f64::NAN".to_string());
}
}
let mut output = String::new();
output.push_str("// Generated by build.rs from Units.json. Do not edit.\n\n");
output.push_str(&format!(
"pub(crate) static LENGTH_UNIT_NAMES: [&str; {}] = {:?};\n\n",
names.len(),
names
));
output.push_str(&format!(
"pub(crate) static LENGTH_UNIT_CANONICAL_PX_RATIOS: [f64; {}] = [{}];\n",
ratios.len(),
ratios.join(", ")
));
std::fs::write(out_dir.join("length_units_generated.rs"), output)?;
// Canonical-unit ratios for the other dimensions, indexed by unit code in
// JSON order like the C++ unit enums. Relative units (none exist outside
// lengths) would be NaN.
let mut output = String::from("// Generated by build.rs from Units.json. Do not edit.\n");
for dimension in ["angle", "flex", "frequency", "resolution", "time"] {
let units = value[dimension]
.as_object()
.ok_or_else(|| format!("Units.json has no {dimension} object"))?;
let mut ratios = Vec::new();
for (_, unit) in units {
let object = unit.as_object().unwrap();
if object
.get("is-canonical-unit")
.is_some_and(|canonical| canonical.as_bool() == Some(true))
{
ratios.push("1.0".to_string());
} else if let Some(ratio) = object.get("number-of-canonical-unit") {
ratios.push(format!("{:?}", ratio.as_f64().unwrap()));
} else {
ratios.push("f64::NAN".to_string());
}
}
output.push_str(&format!(
"\npub(crate) static {}_UNIT_CANONICAL_RATIOS: [f64; {}] = [{}];\n",
dimension.to_uppercase(),
ratios.len(),
ratios.join(", ")
));
let names: Vec<&str> = units.keys().map(String::as_str).collect();
output.push_str(&format!(
"\npub(crate) static {}_UNIT_NAMES: [&str; {}] = {:?};\n",
dimension.to_uppercase(),
names.len(),
names
));
}
std::fs::write(out_dir.join("dimension_units_generated.rs"), output)?;
Ok(())
}
fn generate_environment_variables(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {
let path = manifest_dir.parent().unwrap().join("CSS/EnvironmentVariables.json");
println!("cargo:rerun-if-changed={}", path.display());
let source = std::fs::read_to_string(path)?;
let value: serde_json::Value = serde_json::from_str(&source)?;
let variables = value.as_object().ok_or("EnvironmentVariables.json is not an object")?;
let mut output = String::from("// Generated by build.rs from EnvironmentVariables.json. Do not edit.\n\n");
output.push_str("pub(crate) static ENVIRONMENT_VARIABLES: &[(&str, usize, &str)] = &[\n");
for (name, descriptor) in variables {
let dimensions = descriptor["dimensions"]
.as_u64()
.ok_or_else(|| format!("environment variable {name} has no dimensions"))?;
let value_type = descriptor["type"]
.as_str()
.ok_or_else(|| format!("environment variable {name} has no type"))?;
output.push_str(&format!(" ({name:?}, {dimensions}, {value_type:?}),\n"));
}
output.push_str("];\n");
std::fs::write(out_dir.join("environment_variables_generated.rs"), output)?;
Ok(())
}
// Generates transform function names for the Rust serializer from TransformFunctions.json,
// following the C++ generator's enum member order (the file's key order).
fn generate_transform_functions(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {
let path = manifest_dir.parent().unwrap().join("CSS/TransformFunctions.json");
println!("cargo:rerun-if-changed={}", path.display());
let value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path)?)?;
let functions = value.as_object().ok_or("TransformFunctions.json is not an object")?;
let mut output = String::new();
output.push_str("// Generated by build.rs from TransformFunctions.json. Do not edit.\n\n");
output.push_str(&format!(
"pub(crate) static TRANSFORM_FUNCTION_NAMES: [&str; {}] = [\n",
functions.len()
));
for name in functions.keys() {
output.push_str(&format!(" \"{name}\",\n"));
}
output.push_str("];\n\n");
// Function index constants mirroring the C++ TransformFunction enum, which
// the generator emits in the JSON object's order.
output.push_str("pub(crate) mod transform_function {\n");
for (index, name) in functions.keys().enumerate() {
let mut constant = String::new();
for character in name.chars() {
if character.is_ascii_uppercase() {
constant.push('_');
}
constant.push(character.to_ascii_uppercase());
}
output.push_str(&format!(" pub const {constant}: u8 = {index};\n"));
}
output.push_str("}\n\n");
// Parameter types per function, as codes: angle 0, length 1, length-none 2,
// length-percentage 3, number 4, number-percentage 5.
let parameter_type_code = |name: &str| -> Result<u8, Box<dyn Error>> {
Ok(match name {
"angle" => 0,
"length" => 1,
"length-none" => 2,
"length-percentage" => 3,
"number" => 4,
"number-percentage" => 5,
_ => return Err(format!("unknown transform function parameter type {name}").into()),
})
};
output.push_str(&format!(
"pub(crate) static TRANSFORM_FUNCTION_PARAMETER_TYPES: [&[u8]; {}] = [\n",
functions.len()
));
for (name, function) in functions {
let parameters = function
.get("parameters")
.and_then(serde_json::Value::as_array)
.ok_or_else(|| format!("transform function {name} has no parameters array"))?;
let mut codes = Vec::new();
for parameter in parameters {
let parameter_type = parameter
.get("type")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| format!("transform function {name} parameter has no type"))?;
codes.push(parameter_type_code(parameter_type.trim_matches(['<', '>']))?.to_string());
}
output.push_str(&format!(" &[{}],\n", codes.join(", ")));
}
output.push_str("];\n\n");
output.push_str(&format!(
"pub(crate) static TRANSFORM_FUNCTION_PARAMETER_REQUIRED: [&[bool]; {}] = [\n",
functions.len()
));
for (name, function) in functions {
let parameters = function
.get("parameters")
.and_then(serde_json::Value::as_array)
.ok_or_else(|| format!("transform function {name} has no parameters array"))?;
let required = parameters
.iter()
.map(|parameter| {
parameter
.get("required")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false)
.to_string()
})
.collect::<Vec<_>>();
output.push_str(&format!(" &[{}],\n", required.join(", ")));
}
output.push_str("];\n");
std::fs::write(out_dir.join("transform_functions_generated.rs"), output)?;
Ok(())
}
// Generates keyword codes for the Rust style computation core from Keywords.json.
// Invalid is 0 and the codes follow the array order, matching the C++ Keyword enum.
fn generate_keywords(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {
let keywords_path = manifest_dir.parent().unwrap().join("CSS/Keywords.json");
println!("cargo:rerun-if-changed={}", keywords_path.display());
let value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&keywords_path)?)?;
let keywords = value.as_array().ok_or("Keywords.json is not an array")?;
let mut output = String::new();
output.push_str("// Generated by build.rs from Keywords.json. Do not edit.\n\n");
output.push_str("#[allow(dead_code)]\npub mod keyword {\n");
output.push_str(" pub const INVALID: u16 = 0;\n");
for (index, keyword) in keywords.iter().enumerate() {
let name = keyword.as_str().unwrap();
let constant = name.replace('-', "_").to_uppercase();
output.push_str(&format!(" pub const {constant}: u16 = {};\n", index + 1));
}
// Keyword names indexed by code, for serialization; index 0 is the invalid keyword.
output.push_str(" pub static NAMES: [&str; ");
output.push_str(&format!("{}] = [\n \"\",\n", keywords.len() + 1));
for keyword in keywords {
let name = keyword.as_str().unwrap();
output.push_str(&format!(" \"{name}\",\n"));
}
output.push_str(" ];\n");
let mut lookup_groups = std::collections::BTreeMap::<(usize, u8), Vec<(&str, u16)>>::new();
for (index, keyword) in keywords.iter().enumerate() {
let name = keyword.as_str().unwrap();
lookup_groups
.entry((name.len(), name.as_bytes()[0]))
.or_default()
.push((name, (index + 1) as u16));
}
output.push_str(
" pub(crate) fn from_ascii_case_insensitive(identifier: &[u16]) -> Option<u16> {\n\
let equals = |expected: &[u8]| {\n\
identifier.iter().zip(expected).all(|(&left, &right)| {\n\
crate::css::ffi_support::ascii_lowercase(left) == u16::from(right)\n\
})\n\
};\n\
let first = crate::css::ffi_support::ascii_lowercase(*identifier.first()?);\n\
match (identifier.len(), first) {\n",
);
for ((length, first), candidates) in lookup_groups {
writeln!(output, " ({length}, {}) => {{", u16::from(first))?;
for (name, code) in candidates {
writeln!(output, " if equals(b\"{name}\") {{ return Some({code}); }}")?;
}
output.push_str(" None\n }\n");
}
output.push_str(" _ => None,\n }\n}\n");
output.push_str("}\n");
std::fs::write(out_dir.join("keywords_generated.rs"), output)?;
Ok(())
}
// Generates enum value codes for the Rust style computation core from Enums.json.
// Values follow the array order skipping aliases, matching the C++ enum generator.
fn generate_css_enums(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {
let enums_path = manifest_dir.parent().unwrap().join("CSS/Enums.json");
println!("cargo:rerun-if-changed={}", enums_path.display());
let value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&enums_path)?)?;
let enums = value.as_object().ok_or("Enums.json is not an object")?;
let mut output = String::new();
output.push_str("// Generated by build.rs from Enums.json. Do not edit.\n\n");
for (name, values) in enums {
let values = values.as_array().ok_or("enum values are not an array")?;
let module = name.replace('-', "_");
output.push_str(&format!("#[allow(dead_code)]\npub mod {module} {{\n"));
let mut code: u8 = 0;
for value in values {
let value = value.as_str().ok_or("enum value is not a string")?;
// Aliases are not included in the enum.
if value.contains('=') {
continue;
}
let constant = value.replace('-', "_").to_uppercase();
output.push_str(&format!(" pub const {constant}: u8 = {code};\n"));
code = code.checked_add(1).ok_or("enum has too many values for u8")?;
}
// Member names indexed by value code, for serialization; mirrors the C++
// string_from_<enum> generator (aliases are not members and have no name slot).
output.push_str(&format!(" pub static NAMES: [&str; {code}] = [\n"));
for value in values {
let value = value.as_str().ok_or("enum value is not a string")?;
if value.contains('=') {
continue;
}
output.push_str(&format!(" \"{value}\",\n"));
}
output.push_str(" ];\n");
// The keyword of each member, indexed by value code, as a style holding the code reads it.
output.push_str(&format!(" pub const KEYWORDS: [u16; {code}] = [\n"));
for value in values {
let value = value.as_str().ok_or("enum value is not a string")?;
if value.contains('=') {
continue;
}
let keyword_constant = value.replace('-', "_").to_uppercase();
output.push_str(&format!(" super::keyword::{keyword_constant},\n"));
}
output.push_str(" ];\n");
output.push_str("}\n\n");
// The keyword-to-enum-value mapping, mirroring the C++ keyword_to_<enum> generator,
// including its alias handling ("keyword=member" maps the keyword to member's value).
let mut member_codes = std::collections::HashMap::new();
let mut member_code: u8 = 0;
for value in values {
let value = value.as_str().ok_or("enum value is not a string")?;
if value.contains('=') {
continue;
}
member_codes.insert(value.to_string(), member_code);
member_code = member_code.checked_add(1).ok_or("enum has too many values for u8")?;
}
output.push_str(&format!(
"#[allow(dead_code)]\npub fn keyword_to_{module}(keyword: u16) -> Option<u8> {{\n match keyword {{\n"
));
for value in values {
let value = value.as_str().ok_or("enum value is not a string")?;
let (keyword_name, member_name) = match value.split_once('=') {
Some((keyword, member)) => (keyword, member),
None => (value, value),
};
let keyword_constant = keyword_name.replace('-', "_").to_uppercase();
let code = member_codes
.get(member_name)
.ok_or("enum alias targets an unknown member")?;
output.push_str(&format!(" keyword::{keyword_constant} => Some({code}),\n"));
}
output.push_str(" _ => None,\n }\n}\n\n");
}
std::fs::write(out_dir.join("css_enums_generated.rs"), output)?;
Ok(())
}
// AK::Optional is not trivial for calls under every C++ ABI: Apple clang returns it through memory, where Rust
// returns the matching #[repr(C)] struct in registers. Keep it out of extern "C" signatures; pass a plain
// #[repr(C)] struct and convert it to an Optional on the C++ side.
fn reject_optional_in_extern_c_signatures(header: &Path) {
let text = std::fs::read_to_string(header).unwrap_or_default();
for block in text.split("extern \"C\" {").skip(1) {
let (signatures, _) = block.split_once("} // extern \"C\"").unwrap_or((block, ""));
if let Some(line) = signatures.lines().find(|line| line.contains("Optional<")) {
panic!(
"{}: AK::Optional in an extern \"C\" signature: {line}",
header.display()
);
}
}
}
/// Whether a header's sources failing to parse fails the build here, or is left for rustc to report.
#[derive(Clone, Copy, PartialEq, Eq)]
enum SyntaxErrors {
LeaveToRustc,
Fail,
}
fn generate_ffi_header(config: cbindgen::Config, sources: &[PathBuf], out_dir: &Path, header: &Path) {
write_ffi_header(config, sources, out_dir, header, SyntaxErrors::LeaveToRustc);
}
fn generate_ffi_header_strict(config: cbindgen::Config, sources: &[PathBuf], out_dir: &Path, header: &Path) {
write_ffi_header(config, sources, out_dir, header, SyntaxErrors::Fail);
}
fn write_ffi_header(
config: cbindgen::Config,
sources: &[PathBuf],
out_dir: &Path,
header: &Path,
syntax_errors: SyntaxErrors,
) {
let builder = sources
.iter()
.fold(cbindgen::Builder::new().with_config(config), |builder, source| {
builder.with_src(source)
});
builder.generate().map_or_else(
|error| match error {
cbindgen::Error::ParseSyntaxError { .. } if syntax_errors == SyntaxErrors::LeaveToRustc => {
// Do nothing, the build will fail later with a nicer error message when compiling with rustc
}
other => panic!("{other:?}"),
},
|bindings| {
let output_header = out_dir.join(header);
std::fs::create_dir_all(output_header.parent().unwrap()).unwrap();
bindings.write_to_file(&output_header);
reject_optional_in_extern_c_signatures(&output_header);
},
);
}
fn expose_css_pixel_types_as_web_types(config: &mut cbindgen::Config) {
for (rust_name, cpp_name) in [
("CssPixels", "Web::CSSPixels"),
("FfiCssPixelPoint", "Web::CSSPixelPoint"),
("FfiCssPixelSize", "Web::CSSPixelSize"),
("FfiCssPixelRect", "Web::CSSPixelRect"),
] {
config.export.exclude.push(rust_name.to_string());
config.export.rename.insert(rust_name.to_string(), cpp_name.to_string());
}
config.includes.push("LibWebCommon/PixelUnits.h".to_string());
}
fn expose_shared_abi_types_as_cpp_types(config: &mut cbindgen::Config) {
config.export.exclude.extend(
[
"OptionalFloatRect",
"OptionalColor",
"OptionalU32",
"OptionalF32",
"OptionalAffineTransform",
"OptionalCssPixels",
"OptionalCssPixelRect",
"OptionalIntRect",
"ClipMode",
"FfiChromeMetrics",
"SpatialNodeIndex",
"ClipNodeIndex",
"EffectNodeIndex",
"ContextRef",
"ReplayClip",
"ReplayLayer",
"ReplayMask",
]
.map(String::from),
);
for (rust_name, cpp_name) in [
("IntPoint", "Gfx::IntPoint"),
("FloatPoint", "Gfx::FloatPoint"),
("IntSize", "Gfx::IntSize"),
("FloatSize", "Gfx::FloatSize"),
("FloatVector3", "Gfx::FloatVector3"),
("IntRect", "Gfx::IntRect"),
("FloatRect", "Gfx::FloatRect"),
("Color", "Gfx::Color"),
("AffineTransform", "Gfx::AffineTransform"),
("FloatMatrix4x4", "Gfx::FloatMatrix4x4"),
("CornerRadius", "Gfx::CornerRadius"),
("CornerRadii", "Gfx::CornerRadii"),
("GradientInterpolationMethod", "Gfx::GradientInterpolationMethod"),
("WindingRule", "Gfx::WindingRule"),
("MaskKind", "Gfx::MaskKind"),
("CompositingAndBlendingOperator", "Gfx::CompositingAndBlendingOperator"),
("ColorFilterType", "Gfx::ColorFilterType"),
("ScalingMode", "Gfx::ScalingMode"),
("InterpolationColorSpace", "Gfx::InterpolationColorSpace"),
("OptionalFloatRect", "Optional<Gfx::FloatRect>"),
("OptionalColor", "Optional<Gfx::Color>"),
("OptionalU32", "Optional<u32>"),
("OptionalF32", "Optional<float>"),
("OptionalAffineTransform", "Optional<Gfx::AffineTransform>"),
("OptionalCssPixels", "Optional<Web::CSSPixels>"),
("OptionalCssPixelRect", "Optional<Web::CSSPixelRect>"),
("OptionalIntRect", "Optional<Gfx::IntRect>"),
("ClipMode", "Compositing::ClipMode"),
("FfiChromeMetrics", "Web::ChromeMetrics"),
("SpatialNodeIndex", "Compositing::SpatialNodeIndex"),
("ClipNodeIndex", "Compositing::ClipNodeIndex"),
("EffectNodeIndex", "Compositing::EffectNodeIndex"),
("ContextRef", "Compositing::ContextRef"),
("ReplayClip", "Compositing::ReplayClip"),
("ReplayLayer", "Compositing::ReplayLayer"),
("ReplayMask", "Compositing::ReplayMask"),
] {
config.export.rename.insert(rust_name.to_string(), cpp_name.to_string());
}
config.includes.extend(
[
"AK/Optional.h",
"LibGfx/AffineTransform.h",
"LibGfx/Color.h",
"LibGfx/ColorFilterType.h",
"LibGfx/CompositingAndBlendingOperator.h",
"LibGfx/CornerRadii.h",
"LibGfx/GradientInterpolation.h",
"LibGfx/InterpolationColorSpace.h",
"LibGfx/Matrix4x4.h",
"LibGfx/Point.h",
"LibGfx/Rect.h",
"LibGfx/ScalingMode.h",
"LibGfx/Size.h",
"LibGfx/Vector3.h",
"LibGfx/WindingRule.h",
"LibWeb/Forward.h",
"LibCompositing/DisplayList/ContextRef.h",
"LibWeb/Painting/ChromeMetrics.h",
"LibCompositing/DisplayList/DisplayListCommandsGenerated.h",
]
.map(String::from),
);
}
// The types the compositing crate defines, which its own header declares.
fn expose_compositing_types_as_cpp_types(config: &mut cbindgen::Config) {
for name in [
"NodeSlotId",
"FfiFilterFunction",
"FfiFilterFunctionKind",
"FfiVisualContextTreeInputs",
"FfiVisualAnimationTargetKind",
"FfiVisualAnimationTransformOperationKind",
"FfiCompositorAnimationPublishOutcome",
"FfiVisualAnimationSummary",
"FfiDisplayListReplayCallbacks",
"FfiEasingDescriptor",
"FfiEasingKind",
"FfiLinearEasingPoint",
] {
config.export.exclude.push(name.to_string());
config
.export
.rename
.insert(name.to_string(), format!("Compositing::RustFFI::{name}"));
}
config.export.exclude.push("SnapSelectionStrategyType".to_string());
config.export.rename.insert(
"SnapSelectionStrategyType".to_string(),
"Compositing::SnapSelectionStrategy::Type".to_string(),
);
config.includes.push("LibCompositing/RustFFI.h".to_string());
config
.includes
.push("LibCompositing/Scrolling/ScrollSnapSelection.h".to_string());
}
/// Names an animation effect's identity as the animations header does, which declares it the same way.
fn declare_animation_effect_id_of_animations_header(config: &mut cbindgen::Config) {
config.export.exclude.push("AnimationEffectId".to_string());
config.export.rename.insert(
"AnimationEffectId".to_string(),
"Web::Animations::RustFFI::AnimationEffectId".to_string(),
);
config
.after_includes
.get_or_insert_with(String::new)
.push_str("\nnamespace Web::Animations::RustFFI { using AnimationEffectId = uint64_t; }");
}
/// Names the document host and the begun read as the layout header declares them, for a header whose entries take them.
fn declare_document_host_of_layout_header(config: &mut cbindgen::Config) {
for name in ["DocumentHost", "BegunRead"] {
config
.export
.rename
.insert(name.to_string(), format!("Web::Layout::RustFFI::{name}"));
}
config
.after_includes
.get_or_insert_with(String::new)
.push_str("\nnamespace Web::Layout::RustFFI { struct DocumentHost; struct BegunRead; }");
}
fn main() -> Result<(), Box<dyn Error>> {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);
let out_dir = PathBuf::from(env::var("OUT_DIR")?);
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=cbindgen.toml");
println!("cargo:rerun-if-changed=src");
generate_selector_pseudo_types(&manifest_dir, &out_dir)?;
generate_property_metadata(&manifest_dir, &out_dir)?;
generate_descriptor_metadata(&manifest_dir, &out_dir)?;
generate_math_functions(&manifest_dir, &out_dir)?;
generate_media_features(&manifest_dir, &out_dir)?;
generate_named_colors(&manifest_dir, &out_dir)?;
generate_length_units(&manifest_dir, &out_dir)?;
generate_environment_variables(&manifest_dir, &out_dir)?;
generate_keywords(&manifest_dir, &out_dir)?;
generate_css_enums(&manifest_dir, &out_dir)?;
generate_transform_functions(&manifest_dir, &out_dir)?;
let base_config = cbindgen::Config::from_file(manifest_dir.join("cbindgen.toml"))?;
let mut web_audio_config = base_config.clone();
web_audio_config.namespaces = Some(vec!["Web".into(), "WebAudio".into(), "RustFFI".into()]);
for name in ["NodeHandle", "ControlMessageQueue", "RealtimeAudioRenderer"] {
web_audio_config.export.rename.insert(name.into(), "void".into());
web_audio_config.export.exclude.push(name.into());
}
web_audio_config.export.include.push("AutomationRate".into());
web_audio_config.export.item_types = vec![
cbindgen::ItemType::Enums,
cbindgen::ItemType::Structs,
cbindgen::ItemType::Typedefs,
cbindgen::ItemType::OpaqueItems,
cbindgen::ItemType::Functions,
];
generate_ffi_header(
web_audio_config,
&[
manifest_dir.join("src/web_audio/rendering/render_node.rs"),
manifest_dir.join("src/web_audio/rendering/audio_frame_ring.rs"),
manifest_dir.join("src/web_audio/rendering/media_stream_destination_render_node.rs"),
manifest_dir.join("src/web_audio/rendering/pipe_callbacks.rs"),
manifest_dir.join("src/web_audio/rendering/realtime_audio_renderer.rs"),
manifest_dir.join("src/web_audio/control_message.rs"),
manifest_dir.join("src/web_audio/control_thread.rs"),
],
&out_dir,
Path::new("WebAudio/RustFFI.h"),
);
// CSS tokenizer header — namespace Web::CSS::Parser::FFI, CSS types only.
let mut css_config = base_config.clone();
css_config.namespaces = Some(vec![
"Web".to_string(),
"CSS".to_string(),
"Parser".to_string(),
"FFI".to_string(),
]);
css_config.export.include = vec![
"CssHashType".to_string(),
"CssNumberType".to_string(),
"CssSyntaxToken".to_string(),
"CssTokenType".to_string(),
"FfiUtf16View".to_string(),
];
generate_ffi_header(
css_config,
&[
manifest_dir.join("src/css/css_tokenizer.rs"),
manifest_dir.join("src/css/ffi_support.rs"),
],
&out_dir,
Path::new("RustFFI.h"),
);
// SVG parser header - namespace Web::SVG::RustFFI.
let mut svg_config = base_config.clone();
svg_config.namespaces = Some(vec!["Web".to_string(), "SVG".to_string(), "RustFFI".to_string()]);
svg_config.export.include = vec![
"FfiUtf16View".to_string(),
"FfiSvgPoint".to_string(),
"FfiSvgTransform".to_string(),
"TRANSFORM_MATRIX".to_string(),
"TRANSFORM_ROTATE".to_string(),
"TRANSFORM_SCALE".to_string(),
"TRANSFORM_SKEW_X".to_string(),
"TRANSFORM_SKEW_Y".to_string(),
"TRANSFORM_TRANSLATE".to_string(),
];
// A parsed path is opaque to C++, which holds it by pointer.
svg_config
.export
.rename
.insert("ParsedPath".to_string(), "void".to_string());
svg_config.export.exclude.push("ParsedPath".to_string());
generate_ffi_header_strict(
svg_config,
&[
manifest_dir.join("src/css/ffi_support.rs"),
manifest_dir.join("src/svg/attribute_parser.rs"),
manifest_dir.join("src/svg/path_parser.rs"),
],
&out_dir,
Path::new("SVG/ParserRustFFI.h"),
);
// Selector matching header - namespace Web::CSS::SelectorFFI. Generate both sides of this
// ABI from the Rust declarations so changes to layouts or signatures cannot drift silently.
let mut selector_config = base_config.clone();
selector_config.namespaces = Some(vec!["Web".to_string(), "CSS".to_string(), "SelectorFFI".to_string()]);
for (rust_name, cxx_name) in [
("FfiStringView", "StringView"),
("FfiParsedPseudoElement", "ParsedPseudoElement"),
("FfiElement", "Element"),
("FfiElementQualifiedName", "ElementQualifiedName"),
("FfiInternedStringList", "InternedStringList"),
("FfiDomStringView", "DomStringView"),
("FfiDomAttribute", "DomAttribute"),
("FfiResolvedNamespaceType", "ResolvedNamespaceType"),
("FfiResolvedNamespace", "ResolvedNamespace"),
("FfiElementAndShadowHost", "ElementAndShadowHost"),
] {
selector_config
.export
.rename
.insert(rust_name.to_string(), cxx_name.to_string());
}
// A selector parses against a namespace context as the value parser header declares it.
selector_config.export.rename.insert(
"NativeNamespaceContext".to_string(),
"Web::CSS::Parser::ValueParserFFI::NativeNamespaceContext".to_string(),
);
selector_config
.after_includes
.get_or_insert_with(String::new)
.push_str("\nnamespace Web::CSS::Parser::ValueParserFFI { struct NativeNamespaceContext; }");
generate_ffi_header(
selector_config,
&[
manifest_dir.join("src/css/selector.rs"),
manifest_dir.join("src/css/selector_parser.rs"),
manifest_dir.join("src/css/selector_operations.rs"),
manifest_dir.join("src/css/selector_serialization.rs"),
manifest_dir.join("src/css/dom_selector_matching.rs"),
manifest_dir.join("src/css/ffi_support.rs"),
],
&out_dir,
Path::new("SelectorRustFFI.h"),
);
// Style value header - namespace Web::CSS::StyleValueFFI. The StyleValueData layout is
// exposed so converted C++ StyleValue subclasses can read variant payloads inline without
// an FFI call.
let mut style_value_config = base_config.clone();
style_value_config.namespaces = Some(vec!["Web".to_string(), "CSS".to_string(), "StyleValueFFI".to_string()]);
// A transition step's inputs and decisions cross through the style engine's header, which names them here, and
// the style a color resolves against crosses the layout header behind an opaque pointer.
style_value_config.export.include = [
"StyleValueData",
"RetainedGridTrackEntry",
"FfiTransitionInput",
"FfiExistingTransition",
"FfiTransitionAction",
"FfiColorResolutionStyle",
"FfiLaneTransition",
"FfiCompositeOperation",
]
.map(String::from)
.to_vec();
expose_compositing_types_as_cpp_types(&mut style_value_config);
// A calculation's Typed OM reification is opaque to C++, which holds it by pointer.
style_value_config
.export
.rename
.insert("CalcReificationStorage".to_string(), "void".to_string());
style_value_config
.export
.exclude
.push("CalcReificationStorage".to_string());
// A style value list keeps its element count in the word before its first element.
style_value_config.export.body.insert(
"RetainedStyleValueDataList".to_string(),
" size_t length() const { return pointer ? reinterpret_cast<size_t const*>(pointer)[-1] : 0; }".to_string(),
);
// C++ reads a boxed variant payload through the box as through a pointer.
style_value_config.export.body.insert(
"StyleValueBox".to_string(),
" T const* operator->() const { return pointer; }\n T const& operator*() const { return *pointer; }"
.to_string(),
);
// A compositor keyframe value is substituted by the document's style engine, which the document host reaches.
declare_document_host_of_layout_header(&mut style_value_config);
// The effects whose descriptions and samples cross here are named by their identities.
declare_animation_effect_id_of_animations_header(&mut style_value_config);
generate_ffi_header(
style_value_config,
&[
manifest_dir.join("src/css/style_value.rs"),
manifest_dir.join("src/css/ffi_support.rs"),
manifest_dir.join("src/css/css_string.rs"),
manifest_dir.join("src/css/css_path.rs"),
manifest_dir.join("src/css/retained_fly_string.rs"),
manifest_dir.join("src/css/color_interpolation.rs"),
manifest_dir.join("src/css/animation.rs"),
manifest_dir.join("src/css/transition.rs"),
manifest_dir.join("src/css/calc.rs"),
manifest_dir.join("src/css/serialize.rs"),
manifest_dir.join("src/css/color_resolution.rs"),
manifest_dir.join("src/css/resolved_value.rs"),
manifest_dir.join("src/css/absolutize.rs"),
manifest_dir.join("src/css/ffi_stats.rs"),
],
&out_dir,
Path::new("StyleValueRustFFI.h"),
);
// CSS value parser header - namespace Web::CSS::Parser::ValueParserFFI.
let mut value_parser_config = base_config.clone();
value_parser_config.namespaces = Some(vec![
"Web".to_string(),
"CSS".to_string(),
"Parser".to_string(),
"ValueParserFFI".to_string(),
]);
value_parser_config.export.include = vec![
"NativeCompilationPurpose".to_string(),
"FfiParseStatus".to_string(),
"FontFeatureValuesRuleKind".to_string(),
"FfiValueParsingContext".to_string(),
"FfiValueParsingContextKind".to_string(),
"FfiUtf16View".to_string(),
"FfiQueryHandle".to_string(),
"FfiMediaEnvironment".to_string(),
"FfiMediaFeatureValue".to_string(),
"FfiMediaFeatureValueKind".to_string(),
"ParseContext".to_string(),
];
// A tree scope's counter styles are queued on the document host, which the layout header declares.
declare_document_host_of_layout_header(&mut value_parser_config);
// A parse context's random function counter is the `size_t` C++ lends.
value_parser_config
.export
.rename
.insert("RandomFunctionIndex".to_string(), "size_t".to_string());
value_parser_config
.export
.exclude
.push("RandomFunctionIndex".to_string());
// A parse context names the lengths it resolves against as the computed values header declares them.
value_parser_config.export.rename.insert(
"FfiLengthResolutionContext".to_string(),
"Web::CSS::ComputedValuesFFI::FfiLengthResolutionContext".to_string(),
);
value_parser_config
.after_includes
.get_or_insert_with(String::new)
.push_str("\nnamespace Web::CSS::ComputedValuesFFI { struct FfiLengthResolutionContext; }");
// A counter style's system is read as the style value header declares it.
value_parser_config.export.rename.insert(
"StyleValueData".to_string(),
"Web::CSS::StyleValueFFI::StyleValueData".to_string(),
);
value_parser_config
.after_includes
.get_or_insert_with(String::new)
.push_str("\nnamespace Web::CSS::StyleValueFFI { union StyleValueData; }");
generate_ffi_header(
value_parser_config,
&[
manifest_dir.join("src/css/parser/value_parser.rs"),
manifest_dir.join("src/css/parser/syntax.rs"),
manifest_dir.join("src/css/parser/syntax_parser.rs"),
manifest_dir.join("src/css/parser/descriptor_parser.rs"),
manifest_dir.join("src/css/parser/query_parser.rs"),
manifest_dir.join("src/css/declaration_block.rs"),
manifest_dir.join("src/css/descriptor_block.rs"),
manifest_dir.join("src/css/layer_names.rs"),
manifest_dir.join("src/css/container_conditions.rs"),
manifest_dir.join("src/css/font_feature_values.rs"),
manifest_dir.join("src/css/font_matching.rs"),
manifest_dir.join("src/css/keyframes.rs"),
manifest_dir.join("src/css/style_rule.rs"),
manifest_dir.join("src/css/scope_selectors.rs"),
manifest_dir.join("src/css/media_list.rs"),
manifest_dir.join("src/css/inline_style_blocks.rs"),
manifest_dir.join("src/css/counter_representation.rs"),
manifest_dir.join("src/css/counter_style.rs"),
manifest_dir.join("src/css/namespace_rule.rs"),
manifest_dir.join("src/css/property_rule.rs"),
manifest_dir.join("src/css/function_signature.rs"),
manifest_dir.join("src/css/import_rule.rs"),
manifest_dir.join("src/css/rule.rs"),
manifest_dir.join("src/css/rule/read.rs"),
manifest_dir.join("src/css/rule/function.rs"),
manifest_dir.join("src/css/rule/compilation.rs"),
manifest_dir.join("src/css/rule/compilation/publication.rs"),
manifest_dir.join("src/css/style_sheet.rs"),
manifest_dir.join("src/css/ffi_support.rs"),
],
&out_dir,
Path::new("ValueParserRustFFI.h"),
);
// StyleEngine header - namespace Web::CSS::StyleEngineFFI. The flat input transaction and the
// engine lifecycle entry points; no string or owning pointer appears in this ABI.
let mut style_engine_config = base_config.clone();
style_engine_config.namespaces = Some(vec!["Web".to_string(), "CSS".to_string(), "StyleEngineFFI".to_string()]);
style_engine_config.export.include = vec![
// Taken only by an entry of the boundary table, which cbindgen does not see.
"FfiFrameSetDimension".to_string(),
"FfiFrameSetBorder".to_string(),
// Named by no exported signature: a replaced content input crosses as its raw values.
"FfiReplacedContentInputKind".to_string(),
"FfiReplacedContentInputPresent".to_string(),
"FfiStyleInvalidationField".to_string(),
"FfiNodeRecordReads".to_string(),
"FfiStyleSheetResourceContextEntry".to_string(),
"FfiCustomFunctionEntry".to_string(),
// Only the host's font resolver, which the engine reaches by name, takes these.
"FfiFontResolutionRequest".to_string(),
"FfiResolvedFont".to_string(),
"FontResolutionFeatureInput".to_string(),
];
// A published effect's composite operation is the one the animation sampler composes with.
style_engine_config.export.rename.insert(
"FfiCompositeOperation".to_string(),
"Web::CSS::StyleValueFFI::FfiCompositeOperation".to_string(),
);
// A published effect's default easing is described as the compositing header describes one.
style_engine_config
.export
.exclude
.push("FfiEasingDescriptor".to_string());
style_engine_config.export.rename.insert(
"FfiEasingDescriptor".to_string(),
"Compositing::RustFFI::FfiEasingDescriptor".to_string(),
);
// A transition step's decision is asked of the engine in the style value header's terms.
for name in ["FfiTransitionInput", "FfiTransitionAction", "FfiLaneTransition"] {
style_engine_config
.export
.rename
.insert(name.to_string(), format!("Web::CSS::StyleValueFFI::{name}"));
}
style_engine_config.after_includes = Some(
"namespace Web::CSS::StyleValueFFI { enum class FfiCompositeOperation : uint8_t; enum class FfiTransitionActionKind : uint8_t; struct FfiTransitionInput; struct FfiTransitionAction; struct FfiLaneTransition; }"
.to_string(),
);
// The host queues the engine's changes on the document host, which the layout header declares.
declare_document_host_of_layout_header(&mut style_engine_config);
// A style update flies only where nothing blocks it, which the layout header names as it does for a recording.
style_engine_config.export.rename.insert(
"FfiFlightBlocker".to_string(),
"Web::Layout::RustFFI::FfiFlightBlocker".to_string(),
);
style_engine_config
.after_includes
.get_or_insert_with(String::new)
.push_str("\nnamespace Web::Layout::RustFFI { enum class FfiFlightBlocker : uint8_t; }");
// The host's objects a style reaction is applied through cross as the host's own types, except an element a struct
// holds, which crosses opaque. A box kind crosses as the byte of the host's own enum.
for (name, cpp_name) in [
("ElementBoxKind", "uint8_t"),
("HostElement", "Web::DOM::Element"),
("HostElementPtr", "void*"),
("HostStyleReactionApplication", "Web::CSS::StyleReactionApplication"),
] {
style_engine_config.export.exclude.push(name.to_string());
style_engine_config
.export
.rename
.insert(name.to_string(), cpp_name.to_string());
}
style_engine_config
.after_includes
.get_or_insert_with(String::new)
.push_str("\nnamespace Web::DOM { class Element; }\nnamespace Web::CSS { struct StyleReactionApplication; }");
// The native sheets, rules and declaration blocks the host publishes are named as the value parser header declares
// them.
for name in ["DeclarationBlock", "NativeRule", "NativeStyleSheet"] {
style_engine_config
.export
.rename
.insert(name.to_string(), format!("Web::CSS::Parser::ValueParserFFI::{name}"));
}
style_engine_config
.after_includes
.get_or_insert_with(String::new)
.push_str(
"\nnamespace Web::CSS::Parser::ValueParserFFI { struct DeclarationBlock; struct NativeRule; struct NativeStyleSheet; }",
);
// The effects whose descriptions and samples cross here are named by their identities.
declare_animation_effect_id_of_animations_header(&mut style_engine_config);
generate_ffi_header(
style_engine_config,
&[
manifest_dir.join("src/css/style/bridge.rs"),
manifest_dir.join("src/css/style/bridge/animations.rs"),
manifest_dir.join("src/css/style/bridge/container_effects.rs"),
manifest_dir.join("src/css/style/bridge/native_rules.rs"),
manifest_dir.join("src/css/style/bridge/records.rs"),
manifest_dir.join("src/css/style/identities.rs"),
manifest_dir.join("src/css/style/engine_calls.rs"),
manifest_dir.join("src/css/style/host_atoms.rs"),
manifest_dir.join("src/css/style/reaction_application.rs"),
manifest_dir.join("src/css/style/pipeline/install.rs"),
manifest_dir.join("src/css/style/pipeline/main_effects.rs"),
manifest_dir.join("src/css/style/pipeline/matched_rules.rs"),
manifest_dir.join("src/css/style/rule_writes.rs"),
manifest_dir.join("src/css/style/style_job.rs"),
manifest_dir.join("src/css/ffi_support.rs"),
manifest_dir.join("src/css/style/hover_lane.rs"),
out_dir.join("ffi_state_fact_generated.rs"),
],
&out_dir,
Path::new("StyleEngineRustFFI.h"),
);
// Computed values header - namespace Web::CSS::ComputedValuesFFI. Exposes the style group
// vtable and lifecycle functions; the reference count header layout is documented in
// computed_values.rs and mirrored by StyleStructRef.
let mut computed_values_config = base_config.clone();
computed_values_config.namespaces = Some(vec![
"Web".to_string(),
"CSS".to_string(),
"ComputedValuesFFI".to_string(),
]);
computed_values_config.export.include = vec![
"BoxValues".to_string(),
"ComputedVerticalAlign".to_string(),
"GridValues".to_string(),
"GENERATED_CONTENT_DEFINES_LIST_ITEM_COUNTER".to_string(),
"GENERATED_CONTENT_SHOWS_LIST_ITEM_COUNTER".to_string(),
"GRID_NO_INDEX".to_string(),
"ComputedGridTrackEntryKind".to_string(),
"ComputedGridPlacementKind".to_string(),
"CascadeOrigin".to_string(),
"TransformValues".to_string(),
"EffectsValues".to_string(),
"ComputedColorOrAuto".to_string(),
"ComputedCursor".to_string(),
"RetainedComputedCursorList".to_string(),
"ComputedScrollbarColor".to_string(),
"InheritedUIValues".to_string(),
"ComputedSvgPaint".to_string(),
"ComputedSvgDash".to_string(),
"RetainedComputedSvgDashList".to_string(),
"InheritedSVGValues".to_string(),
"ComputedTextIndent".to_string(),
"ComputedTextUnderlinePosition".to_string(),
"ComputedTextUnderlineOffset".to_string(),
"InheritedTextValues".to_string(),
"InheritedListTableValues".to_string(),
"InheritedBits".to_string(),
"ResetBits".to_string(),
"InheritedSetValues".to_string(),
"SizingValues".to_string(),
"AlignmentValues".to_string(),
"SVGResetValues".to_string(),
"SurroundValues".to_string(),
"BorderLayoutFacts".to_string(),
"AnimationValues".to_string(),
"MaskValues".to_string(),
"BackgroundValues".to_string(),
"BorderValues".to_string(),
"ContentValues".to_string(),
"ComputedOverflowClipMarginSide".to_string(),
"ComputedOverflowClipMargin".to_string(),
"MiscLayoutValues".to_string(),
"MiscInteractionValues".to_string(),
"FontValues".to_string(),
"FontCascadeListHandle".to_string(),
"FrozenFontListRef".to_string(),
"FfiFontGroupBuildInputs".to_string(),
"TextResetValues".to_string(),
"AnchorValues".to_string(),
"FfiEffectiveLonghandValue".to_string(),
"FfiUtf16View".to_string(),
"EFFECTIVE_LONGHAND_SOURCE_TABLE".to_string(),
"EFFECTIVE_LONGHAND_SOURCE_OVERLAY".to_string(),
"EFFECTIVE_LONGHAND_SOURCE_SPECIFIED".to_string(),
];
expose_css_pixel_types_as_web_types(&mut computed_values_config);
// An effect the host samples carries its easing as the compositing crate describes one.
expose_compositing_types_as_cpp_types(&mut computed_values_config);
// The custom property registry and stores and a sample's animated custom properties are opaque to C++, which holds
// each by pointer.
for name in [
"CustomPropertyRegistry",
"CustomPropertyStore",
"AnimatedCustomPropertyResults",
] {
computed_values_config
.export
.rename
.insert(name.to_string(), "void".to_string());
computed_values_config.export.exclude.push(name.to_string());
}
computed_values_config.export.rename.insert(
"DeclarationBlockHeader".to_string(),
"Web::CSS::Parser::ValueParserFFI::DeclarationBlockHeader".to_string(),
);
computed_values_config
.after_includes
.get_or_insert_with(String::new)
.push_str("\nnamespace Web::CSS::Parser::ValueParserFFI { struct DeclarationBlockHeader; }");
// The computations C++ hands a style value take the value as the style value header declares it.
computed_values_config.export.rename.insert(
"StyleValueData".to_string(),
"Web::CSS::StyleValueFFI::StyleValueData".to_string(),
);
computed_values_config
.after_includes
.get_or_insert_with(String::new)
.push_str("\nnamespace Web::CSS::StyleValueFFI { union StyleValueData; }");
// So do the names it hands out as CSS strings.
computed_values_config.export.rename.insert(
"CssString".to_string(),
"Web::CSS::StyleValueFFI::CssString".to_string(),
);
computed_values_config
.after_includes
.get_or_insert_with(String::new)
.push_str("\nnamespace Web::CSS::StyleValueFFI { struct CssString; }");
// An animation sample and plan read the document's style engine, which the document host reaches.
declare_document_host_of_layout_header(&mut computed_values_config);
// The effects the host samples, and the animations of the element they belong to, are as the animations header
// describes them.
for name in ["FfiSampledEffect", "ElementAnimations"] {
computed_values_config.export.exclude.push(name.to_string());
computed_values_config
.export
.rename
.insert(name.to_string(), format!("Web::Animations::RustFFI::{name}"));
}
computed_values_config
.includes
.push("LibWeb/Animations/RustFFI.h".to_string());
computed_values_config.export.rename.insert(
"FfiAnimationEffectDescriptions".to_string(),
"Web::CSS::StyleEngineFFI::FfiAnimationEffectDescriptions".to_string(),
);
computed_values_config
.after_includes
.get_or_insert_with(String::new)
.push_str("\nnamespace Web::CSS::StyleEngineFFI { struct FfiAnimationEffectDescriptions; }");
let libgfx_font_source = manifest_dir.join("../../LibGfx/Rust/src/font.rs");
println!("cargo:rerun-if-changed={}", libgfx_font_source.display());
// The effects whose descriptions and samples cross here are named by their identities.
declare_animation_effect_id_of_animations_header(&mut computed_values_config);
generate_ffi_header(
computed_values_config,
&[
libgfx_font_source,
manifest_dir.join("src/css/computed_values.rs"),
manifest_dir.join("src/css/property_metadata.rs"),
manifest_dir.join("src/css/style_compute.rs"),
manifest_dir.join("src/css/style_compute/adjustments.rs"),
manifest_dir.join("src/css/display.rs"),
manifest_dir.join("src/css/computed_value_types.rs"),
manifest_dir.join("src/css/retained_fly_string.rs"),
manifest_dir.join("src/css/animated_overlay.rs"),
manifest_dir.join("src/css/cascaded_properties.rs"),
manifest_dir.join("src/css/computed_longhand_table.rs"),
manifest_dir.join("src/css/custom_properties.rs"),
manifest_dir.join("src/css/ffi_support.rs"),
manifest_dir.join("src/css/table_group_builder.rs"),
],
&out_dir,
Path::new("ComputedValuesRustFFI.h"),
);
// Encoding-detection header - namespace Web::HTML::Parser, rust_detect_encoding only.
let mut html_config = base_config.clone();
html_config.namespaces = Some(vec!["Web".to_string(), "HTML".to_string(), "Parser".to_string()]);
html_config.export.include = vec!["rust_detect_encoding".to_string()];
generate_ffi_header(
html_config,
&[manifest_dir.join("src/encoding_detection.rs")],
&out_dir,
Path::new("HTML/Parser/RustFFI.h"),
);
// Layout tree-builder header - namespace Web::Layout::RustFFI. The C++ layout tree
// wrappers drive the node arena through slot ids.
let mut tree_builder_config = base_config.clone();
tree_builder_config.namespaces = Some(vec!["Web".to_string(), "Layout".to_string(), "RustFFI".to_string()]);
tree_builder_config.export.include = vec![
"DomPaintFact".to_string(),
"FfiDomTextRange".to_string(),
"FfiCodePointCategoryFacts".to_string(),
"FfiGeneratedImage".to_string(),
"FfiNodeIdentity".to_string(),
"FfiPseudoElement".to_string(),
"FfiRenderedTextView".to_string(),
"FfiRenderedTextOffset".to_string(),
"FfiRenderedTextWithOffsetsView".to_string(),
"FfiStylePayloads".to_string(),
"FfiUtf16View".to_string(),
// Lent and handed back through the layout header, which builds on this one.
"ArcRef".to_string(),
"OwnedArc".to_string(),
"OwnedBox".to_string(),
"NodeFlag".to_string(),
"NodeKind".to_string(),
];
tree_builder_config.export.exclude = vec![
"ladybird_layout_code_point_category_facts".to_string(),
"ladybird_layout_node_shell_destroy".to_string(),
"rust_calc_resolve".to_string(),
];
expose_css_pixel_types_as_web_types(&mut tree_builder_config);
expose_compositing_types_as_cpp_types(&mut tree_builder_config);
generate_ffi_header(
tree_builder_config,
&[
manifest_dir.join("src/layout/layout_node_arena.rs"),
manifest_dir.join("src/layout/layout_node_arena/main_thread_entries.rs"),
manifest_dir.join("src/layout/shell_reads.rs"),
manifest_dir.join("src/layout/trace.rs"),
manifest_dir.join("src/layout/rendered_text.rs"),
manifest_dir.join("src/layout/text_queries.rs"),
manifest_dir.join("src/css/ffi_support.rs"),
manifest_dir.join("src/layout/node_data.rs"),
manifest_dir.join("src/layout/partial_relayout.rs"),
manifest_dir.join("src/layout/tree_builder.rs"),
manifest_dir.join("src/layout/tree_update_marks.rs"),
manifest_dir.join("src/render_state.rs"),
manifest_dir.join("src/render_state/devtools.rs"),
manifest_dir.join("src/render_state/document_host.rs"),
manifest_dir.join("src/render_state/wait.rs"),
manifest_dir.join("src/stage_thread.rs"),
],
&out_dir,
Path::new("Layout/TreeBuilderRustFFI.h"),
);
// The Web Animations timing model - namespace Web::Animations::RustFFI. An easing descriptor is the compositing
// header's.
let mut animations_config = base_config.clone();
animations_config.namespaces = Some(vec!["Web".to_string(), "Animations".to_string(), "RustFFI".to_string()]);
animations_config.export.exclude.push("FfiEasingDescriptor".to_string());
animations_config.export.rename.insert(
"FfiEasingDescriptor".to_string(),
"Compositing::RustFFI::FfiEasingDescriptor".to_string(),
);
animations_config.includes.push("LibCompositing/RustFFI.h".to_string());
// A keyframe set notes the attributes its values read through the document's host, and a scroll timeline measures
// the boxes it follows there.
declare_document_host_of_layout_header(&mut animations_config);
animations_config.export.exclude.push("NodeSlotId".to_string());
animations_config
.export
.rename
.insert("NodeSlotId".to_string(), "Compositing::RustFFI::NodeSlotId".to_string());
// An effect's composite operation is the style value header's.
animations_config
.export
.exclude
.push("FfiCompositeOperation".to_string());
animations_config.export.rename.insert(
"FfiCompositeOperation".to_string(),
"Web::CSS::StyleValueFFI::FfiCompositeOperation".to_string(),
);
animations_config
.after_includes
.get_or_insert_with(String::new)
.push_str("\nnamespace Web::CSS::StyleValueFFI { enum class FfiCompositeOperation : uint8_t; }");
// The definition a style computation applies to a CSS animation is the computed values header's.
animations_config
.export
.exclude
.push("FfiComputedAnimation".to_string());
animations_config.export.rename.insert(
"FfiComputedAnimation".to_string(),
"Web::CSS::ComputedValuesFFI::FfiComputedAnimation".to_string(),
);
animations_config
.after_includes
.get_or_insert_with(String::new)
.push_str("\nnamespace Web::CSS::ComputedValuesFFI { struct FfiComputedAnimation; }");
// A transition the hover of a clock lane leaves running, and one a style change event reads, are the style value
// header's.
for name in ["FfiLaneTransition", "FfiExistingTransition"] {
animations_config.export.exclude.push(name.to_string());
animations_config
.export
.rename
.insert(name.to_string(), format!("Web::CSS::StyleValueFFI::{name}"));
animations_config
.after_includes
.get_or_insert_with(String::new)
.push_str(&format!("\nnamespace Web::CSS::StyleValueFFI {{ struct {name}; }}"));
}
// What an effect built for the compositor is opaque to C++, which hands it to the layout header's functions.
animations_config
.export
.exclude
.push("CompositorAnimationEffectState".to_string());
animations_config
.export
.rename
.insert("CompositorAnimationEffectState".to_string(), "void".to_string());
// The host defines what the timeline records ask of documents, which the tests stub.
animations_config
.export
.exclude
.push("ladybird_animations_document_is_active".to_string());
animations_config
.export
.exclude
.push("ladybird_animations_element_node_document".to_string());
animations_config
.export
.exclude
.push("web_animation_target_facts".to_string());
animations_config
.export
.exclude
.push("web_animation_note_rendering_trace_event".to_string());
animations_config
.export
.exclude
.push("web_animation_compute_css_keyframe_values".to_string());
animations_config
.export
.exclude
.push("web_animation_effective_zoom_of_target".to_string());
animations_config
.export
.exclude
.push("web_animation_set_needs_animated_style_update".to_string());
// The host defines what the timelines associated with a document ask of it.
for name in [
"web_animation_document_animations",
"web_animation_document_clock",
"web_animation_find_scroll_timeline_boxes",
"web_animation_scroll_timeline_source",
] {
animations_config.export.exclude.push(name.to_string());
}
// The timing the host publishes of an effect it samples, an effect it samples, and a timeline it creates through
// the bindings, which no function here takes.
animations_config.export.include.extend(
[
"EffectTimingSnapshot",
"FfiSampledEffect",
"FfiTargetFacts",
"FfiTimelineDescription",
"FfiDocumentClock",
"FfiScrollTimelineBoxes",
]
.map(String::from),
);
let animation_timing_dir = manifest_dir.join("../../LibCompositing/Rust/src/animation_timing");
println!("cargo:rerun-if-changed={}", animation_timing_dir.display());
generate_ffi_header(
animations_config,
&[
animation_timing_dir.join("time_value.rs"),
animation_timing_dir.join("effect_timing.rs"),
animation_timing_dir.join("playback.rs"),
manifest_dir.join("src/animations/animation.rs"),
manifest_dir.join("src/animations/effect.rs"),
manifest_dir.join("src/animations/compositor_update.rs"),
manifest_dir.join("src/animations/document_animations.rs"),
manifest_dir.join("src/animations/element_animations.rs"),
manifest_dir.join("src/animations/ffi.rs"),
manifest_dir.join("src/animations/host_effects.rs"),
manifest_dir.join("src/animations/host_timing.rs"),
manifest_dir.join("src/animations/css_events.rs"),
manifest_dir.join("src/animations/keyframes.rs"),
manifest_dir.join("src/animations/pending_animation_events.rs"),
manifest_dir.join("src/animations/rendering_update.rs"),
manifest_dir.join("src/animations/snapshot.rs"),
manifest_dir.join("src/animations/throttling.rs"),
manifest_dir.join("src/animations/timeline.rs"),
manifest_dir.join("src/animations/timeline_host.rs"),
manifest_dir.join("src/animations/transitions.rs"),
],
&out_dir,
Path::new("Animations/RustFFI.h"),
);
// The lanes of the render clock - namespace Web::Compositor::RustFFI, layered on the layout header for the ticks
// the lanes hand on.
let mut render_clock_config = base_config.clone();
render_clock_config.namespaces = Some(vec!["Web".to_string(), "Compositor".to_string(), "RustFFI".to_string()]);
for (rust_name, cpp_name) in [
("ArcRef", "Web::Layout::RustFFI::ArcRef"),
("ClockTicks", "Web::Layout::RustFFI::ClockTicks"),
("FfiThreadSafeMessagePoster", "IPC::FfiThreadSafeMessagePoster"),
("RawMessage", "IPC::FfiRawMessage"),
] {
render_clock_config
.export
.rename
.insert(rust_name.to_string(), cpp_name.to_string());
}
render_clock_config.includes.extend(
[
"LibIPC/RawMessage.h",
"LibIPC/ThreadSafeMessagePoster.h",
"LibWeb/Layout/LayoutRustFFI.h",
]
.map(String::from),
);
generate_ffi_header(
render_clock_config,
&[manifest_dir.join("src/render_state/clock/render_clock.rs")],
&out_dir,
Path::new("Compositor/RenderClockRustFFI.h"),
);
// Layout engine header - namespace Web::Layout::RustFFI, layered on the tree-builder
// header.
let mut layout_config = base_config;
layout_config.namespaces = Some(vec!["Web".to_string(), "Layout".to_string(), "RustFFI".to_string()]);
layout_config.export.exclude = vec![
"rust_calc_resolve".to_string(),
"rust_calc_root_from_calculated".to_string(),
"rust_calc_external_resolutions".to_string(),
"rust_calc_external_resolutions_release".to_string(),
];
expose_css_pixel_types_as_web_types(&mut layout_config);
expose_shared_abi_types_as_cpp_types(&mut layout_config);
expose_compositing_types_as_cpp_types(&mut layout_config);
layout_config
.includes
.push("LibWeb/Layout/TreeBuilderRustFFI.h".to_string());
// Rust posts to the compositor through a poster C++ made.
layout_config
.export
.exclude
.push("FfiThreadSafeMessagePoster".to_string());
layout_config.export.rename.insert(
"FfiThreadSafeMessagePoster".to_string(),
"IPC::FfiThreadSafeMessagePoster".to_string(),
);
layout_config
.includes
.push("LibIPC/ThreadSafeMessagePoster.h".to_string());
// Rust sends synchronous requests to the compositor through the connection C++ made.
layout_config.export.exclude.push("FfiConnection".to_string());
layout_config
.export
.rename
.insert("FfiConnection".to_string(), "IPC::FfiConnection".to_string());
layout_config.includes.push("LibIPC/FfiConnection.h".to_string());
// A compositor animation carries its effect's timing as the animations header describes it.
layout_config.export.exclude.push("AnimationEffectTiming".to_string());
layout_config.export.rename.insert(
"AnimationEffectTiming".to_string(),
"Web::Animations::RustFFI::AnimationEffectTiming".to_string(),
);
layout_config.includes.push("LibWeb/Animations/RustFFI.h".to_string());
// The render clock's plan takes the scroll timelines it follows as the animations header declares them.
layout_config.export.exclude.push("TimelineCell".to_string());
layout_config.export.rename.insert(
"TimelineCell".to_string(),
"Web::Animations::RustFFI::TimelineCell".to_string(),
);
// A compositor animation effect state is opaque to C++, which holds it by pointer, and so are the paint server an
// SVG paint resource callback fills and a parsed SVG path.
for name in [
"CompositorAnimationEffectState",
"PublishedSvgPaintServer",
"ParsedPath",
] {
layout_config.export.rename.insert(name.to_string(), "void".to_string());
layout_config.export.exclude.push(name.to_string());
}
// The host fills in a compositor animation request, and the host its keyframes resolve with, as the animation
// records ask it to, which no function here takes.
layout_config
.export
.include
.extend(["FfiCompositorAnimationRequest", "FfiCompositorAnimationHost"].map(String::from));
// The effects whose descriptions and samples cross here are named by their identities.
declare_animation_effect_id_of_animations_header(&mut layout_config);
generate_ffi_header(
layout_config,
&[
manifest_dir.join("src/layout/used_values.rs"),
manifest_dir.join("src/layout/commit.rs"),
manifest_dir.join("src/layout/geometry.rs"),
manifest_dir.join("src/layout/style_values.rs"),
manifest_dir.join("src/layout/node_facts.rs"),
manifest_dir.join("src/css/computed_value_types.rs"),
manifest_dir.join("src/css/display.rs"),
manifest_dir.join("src/layout/formatting_context.rs"),
manifest_dir.join("src/layout/layout_changes.rs"),
manifest_dir.join("src/layout/viewport_propagation.rs"),
manifest_dir.join("src/layout/update_layout.rs"),
manifest_dir.join("src/layout/update_layout/main_thread_entries.rs"),
manifest_dir.join("src/layout/flex_formatting_context.rs"),
manifest_dir.join("src/layout/grid_formatting_context.rs"),
manifest_dir.join("src/layout/svg_formatting_context.rs"),
manifest_dir.join("src/layout/math_formatting_context.rs"),
manifest_dir.join("src/layout/table_formatting_context.rs"),
manifest_dir.join("src/layout/inline_formatting_context.rs"),
manifest_dir.join("src/layout/inline_level_iterator.rs"),
manifest_dir.join("src/layout/line_builder.rs"),
manifest_dir.join("src/layout/line_box.rs"),
manifest_dir.join("src/layout/line_box_fragment.rs"),
manifest_dir.join("src/painting/paintable_data.rs"),
manifest_dir.join("src/painting/host/mod.rs"),
manifest_dir.join("src/painting/host/visual_context.rs"),
manifest_dir.join("src/painting/host/hit_test.rs"),
manifest_dir.join("src/painting/host/paint.rs"),
manifest_dir.join("src/painting/display_list/dump.rs"),
manifest_dir.join("src/painting/stacking_context/dump.rs"),
manifest_dir.join("src/painting/layout_tree_dump.rs"),
manifest_dir.join("src/painting/ffi.rs"),
manifest_dir.join("src/painting/viewport_mapping.rs"),
manifest_dir.join("src/render_state/clock.rs"),
manifest_dir.join("src/render_state/clock/hover.rs"),
manifest_dir.join("src/layout/script_entries.rs"),
manifest_dir.join("src/layout/query/inline_cursor.rs"),
manifest_dir.join("src/painting/paint_changes.rs"),
manifest_dir.join("src/painting/ffi/main_thread_entries.rs"),
manifest_dir.join("src/painting/paint_passes.rs"),
manifest_dir.join("src/painting/presentation.rs"),
manifest_dir.join("src/painting/vector_image_cache.rs"),
manifest_dir.join("src/painting/recorded_scrolling.rs"),
manifest_dir.join("src/painting/rasterize.rs"),
],
&out_dir,
Path::new("Layout/LayoutRustFFI.h"),
);
Ok(())
}