Meta: Replace GenerateCSSStyleProperties with a python generator

This commit is contained in:
Sam Atkins
2026-04-24 15:33:49 +01:00
committed by Shannon Booth
parent d3d124b1d8
commit 3580e2506c
Notes: github-actions[bot] 2026-04-25 10:03:52 +00:00
4 changed files with 162 additions and 193 deletions

View File

@@ -115,10 +115,10 @@ function (generate_css_implementation)
arguments -j "${LIBWEB_INPUT_FOLDER}/CSS/Units.json"
)
invoke_idl_generator(
invoke_py_idl_generator(
"GeneratedCSSStyleProperties.cpp"
"GeneratedCSSStyleProperties.idl"
Lagom::GenerateCSSStyleProperties
"generate_libweb_css_style_properties.py"
"${LIBWEB_INPUT_FOLDER}/CSS/Properties.json"
"CSS/GeneratedCSSStyleProperties.h"
"CSS/GeneratedCSSStyleProperties.cpp"

View File

@@ -0,0 +1,160 @@
#!/usr/bin/env python3
# Copyright (c) 2024, Luke Wilde <luke@ladybird.org>
# Copyright (c) 2026-present, the Ladybird developers.
#
# SPDX-License-Identifier: BSD-2-Clause
import argparse
import json
import sys
from pathlib import Path
from typing import TextIO
sys.path.append(str(Path(__file__).resolve().parent.parent))
from Utils.utils import make_name_acceptable_cpp
from Utils.utils import snake_casify
def css_property_to_idl_attribute(property_name: str, lowercase_first: bool = False) -> str:
# https://drafts.csswg.org/cssom/#css-property-to-idl-attribute
actual_property_name = property_name[1:] if lowercase_first else property_name
output = []
uppercase_next = False
for c in actual_property_name:
if c == "-":
uppercase_next = True
elif uppercase_next:
uppercase_next = False
output.append(c.upper())
else:
output.append(c)
return "".join(output)
def write_header_file(out: TextIO, properties: dict) -> None:
out.write("""
#pragma once
#include <AK/String.h>
#include <LibWeb/Forward.h>
namespace Web::Bindings {
class GeneratedCSSStyleProperties {
public:
""")
for name in properties:
name_acceptable_cpp = make_name_acceptable_cpp(snake_casify(name, trim_leading_underscores=True))
out.write(f"""
WebIDL::ExceptionOr<void> set_{name_acceptable_cpp}(StringView value);
String {name_acceptable_cpp}() const;
""")
out.write("""
protected:
GeneratedCSSStyleProperties() = default;
virtual ~GeneratedCSSStyleProperties() = default;
virtual CSS::CSSStyleProperties& generated_style_properties_to_css_style_properties() = 0;
CSS::CSSStyleProperties const& generated_style_properties_to_css_style_properties() const { return const_cast<GeneratedCSSStyleProperties&>(*this).generated_style_properties_to_css_style_properties(); }
}; // class GeneratedCSSStyleProperties
} // namespace Web::Bindings
""")
def write_implementation_file(out: TextIO, properties: dict) -> None:
out.write("""
#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/GeneratedCSSStyleProperties.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::Bindings {
""")
for name in properties:
name_acceptable_cpp = make_name_acceptable_cpp(snake_casify(name, trim_leading_underscores=True))
out.write(f"""
WebIDL::ExceptionOr<void> GeneratedCSSStyleProperties::set_{name_acceptable_cpp}(StringView value)
{{
return generated_style_properties_to_css_style_properties().set_property("{name}"_fly_string, value, ""sv);
}}
String GeneratedCSSStyleProperties::{name_acceptable_cpp}() const
{{
return generated_style_properties_to_css_style_properties().get_property_value("{name}"_fly_string);
}}
""")
out.write("""
} // namespace Web::Bindings
""")
def write_idl_file(out: TextIO, properties: dict) -> None:
out.write("""
interface mixin GeneratedCSSStyleProperties {
""")
for name in properties:
snake_case_name = snake_casify(name, trim_leading_underscores=True)
name_acceptable_cpp = make_name_acceptable_cpp(snake_case_name)
# https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-camel-cased-attribute
name_camelcase = css_property_to_idl_attribute(name)
out.write(f"""
[CEReactions, LegacyNullToEmptyString, AttributeCallbackName={snake_case_name}_regular, ImplementedAs={name_acceptable_cpp}] attribute CSSOMString {name_camelcase};
""")
# For each CSS property property that is a supported CSS property and that begins with the string -webkit-,
# the following partial interface applies where webkit-cased attribute is obtained by running the CSS property
# to IDL attribute algorithm for property, with the lowercase first flag set.
if name.startswith("-webkit-"):
name_webkit = css_property_to_idl_attribute(name, lowercase_first=True)
out.write(f"""
[CEReactions, LegacyNullToEmptyString, AttributeCallbackName={snake_case_name}_webkit, ImplementedAs={name_acceptable_cpp}] attribute CSSOMString {name_webkit};
""")
# For each CSS property property that is a supported CSS property, except for properties that have no
# "-" (U+002D) in the property name, the following partial interface applies where dashed attribute is
# property.
if "-" in name:
out.write(f"""
[CEReactions, LegacyNullToEmptyString, AttributeCallbackName={snake_case_name}_dashed, ImplementedAs={name_acceptable_cpp}] attribute CSSOMString {name};
""")
out.write("""
};
""")
def main():
parser = argparse.ArgumentParser(description="Generate CSS StyleProperties", add_help=False)
parser.add_argument("--help", action="help", help="Show this help message and exit")
parser.add_argument("-h", "--header", required=True, help="Path to the CSSStyleProperties header file to generate")
parser.add_argument(
"-c", "--implementation", required=True, help="Path to the CSSStyleProperties implementation file to generate"
)
parser.add_argument("-i", "--idl", required=True, help="Path to the CSSStyleProperties IDL file to generate")
parser.add_argument("-j", "--json", required=True, help="Path to the JSON file to read from")
args = parser.parse_args()
with open(args.json, "r", encoding="utf-8") as input_file:
properties = json.load(input_file)
with open(args.header, "w", encoding="utf-8") as output_file:
write_header_file(output_file, properties)
with open(args.implementation, "w", encoding="utf-8") as output_file:
write_implementation_file(output_file, properties)
with open(args.idl, "w", encoding="utf-8") as output_file:
write_idl_file(output_file, properties)
if __name__ == "__main__":
main()

View File

@@ -1,7 +1,6 @@
set(SOURCES "") # avoid pulling SOURCES from parent scope
lagom_tool(GenerateCSSPropertyID SOURCES GenerateCSSPropertyID.cpp LIBS LibMain)
lagom_tool(GenerateCSSStyleProperties SOURCES GenerateCSSStyleProperties.cpp LIBS LibMain)
lagom_tool(GenerateWindowOrWorkerInterfaces SOURCES GenerateWindowOrWorkerInterfaces.cpp LIBS LibMain LibIDL)
lagom_tool(GenerateAriaRoles SOURCES GenerateAriaRoles.cpp LIBS LibMain)
lagom_tool(GenerateNamedCharacterReferences SOURCES GenerateNamedCharacterReferences.cpp LIBS LibMain)

View File

@@ -1,190 +0,0 @@
/*
* Copyright (c) 2024, Luke Wilde <luke@ladybird.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "GeneratorUtil.h"
#include <AK/SourceGenerator.h>
#include <AK/StringBuilder.h>
#include <LibCore/ArgsParser.h>
#include <LibMain/Main.h>
ErrorOr<void> generate_header_file(JsonObject& properties, Core::File& file);
ErrorOr<void> generate_implementation_file(JsonObject& properties, Core::File& file);
ErrorOr<void> generate_idl_file(JsonObject& properties, Core::File& file);
ErrorOr<int> ladybird_main(Main::Arguments arguments)
{
StringView generated_header_path;
StringView generated_implementation_path;
StringView generated_idl_path;
StringView properties_json_path;
Core::ArgsParser args_parser;
args_parser.add_option(generated_header_path, "Path to the CSSStyleProperties header file to generate", "generated-header-path", 'h', "generated-header-path");
args_parser.add_option(generated_implementation_path, "Path to the CSSStyleProperties implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
args_parser.add_option(generated_idl_path, "Path to the CSSStyleProperties IDL file to generate", "generated-idl-path", 'i', "generated-idl-path");
args_parser.add_option(properties_json_path, "Path to the JSON file to read from", "json-path", 'j', "json-path");
args_parser.parse(arguments);
auto json = TRY(read_entire_file_as_json(properties_json_path));
VERIFY(json.is_object());
auto properties = json.as_object();
auto generated_header_file = TRY(Core::File::open(generated_header_path, Core::File::OpenMode::Write));
auto generated_implementation_file = TRY(Core::File::open(generated_implementation_path, Core::File::OpenMode::Write));
auto generated_idl_file = TRY(Core::File::open(generated_idl_path, Core::File::OpenMode::Write));
TRY(generate_header_file(properties, *generated_header_file));
TRY(generate_implementation_file(properties, *generated_implementation_file));
TRY(generate_idl_file(properties, *generated_idl_file));
return 0;
}
ErrorOr<void> generate_header_file(JsonObject& properties, Core::File& file)
{
StringBuilder builder;
SourceGenerator generator { builder };
generator.append(R"~~~(
#pragma once
#include <AK/String.h>
#include <LibWeb/Forward.h>
namespace Web::Bindings {
class GeneratedCSSStyleProperties {
public:
)~~~");
properties.for_each_member([&](auto& name, auto&) {
auto declaration_generator = generator.fork();
auto snake_case_name = snake_casify(name, TrimLeadingUnderscores::Yes);
declaration_generator.set("name:acceptable_cpp", make_name_acceptable_cpp(snake_case_name));
declaration_generator.append(R"~~~(
WebIDL::ExceptionOr<void> set_@name:acceptable_cpp@(StringView value);
String @name:acceptable_cpp@() const;
)~~~");
});
generator.append(R"~~~(
protected:
GeneratedCSSStyleProperties() = default;
virtual ~GeneratedCSSStyleProperties() = default;
virtual CSS::CSSStyleProperties& generated_style_properties_to_css_style_properties() = 0;
CSS::CSSStyleProperties const& generated_style_properties_to_css_style_properties() const { return const_cast<GeneratedCSSStyleProperties&>(*this).generated_style_properties_to_css_style_properties(); }
}; // class GeneratedCSSStyleProperties
} // namespace Web::Bindings
)~~~");
TRY(file.write_until_depleted(generator.as_string_view().bytes()));
return {};
}
ErrorOr<void> generate_implementation_file(JsonObject& properties, Core::File& file)
{
StringBuilder builder;
SourceGenerator generator { builder };
generator.append(R"~~~(
#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/GeneratedCSSStyleProperties.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::Bindings {
)~~~");
properties.for_each_member([&](auto& name, auto&) {
auto definition_generator = generator.fork();
definition_generator.set("name", name);
auto snake_case_name = snake_casify(name, TrimLeadingUnderscores::Yes);
definition_generator.set("name:acceptable_cpp", make_name_acceptable_cpp(snake_case_name));
definition_generator.append(R"~~~(
WebIDL::ExceptionOr<void> GeneratedCSSStyleProperties::set_@name:acceptable_cpp@(StringView value)
{
return generated_style_properties_to_css_style_properties().set_property("@name@"_fly_string, value, ""sv);
}
String GeneratedCSSStyleProperties::@name:acceptable_cpp@() const
{
return generated_style_properties_to_css_style_properties().get_property_value("@name@"_fly_string);
}
)~~~");
});
generator.append(R"~~~(
} // namespace Web::Bindings
)~~~");
TRY(file.write_until_depleted(generator.as_string_view().bytes()));
return {};
}
ErrorOr<void> generate_idl_file(JsonObject& properties, Core::File& file)
{
StringBuilder builder;
SourceGenerator generator { builder };
generator.append(R"~~~(
interface mixin GeneratedCSSStyleProperties {
)~~~");
properties.for_each_member([&](auto& name, auto&) {
auto member_generator = generator.fork();
member_generator.set("name", name);
auto snake_case_name = snake_casify(name, TrimLeadingUnderscores::Yes);
member_generator.set("name:snakecase", snake_case_name);
member_generator.set("name:acceptable_cpp", make_name_acceptable_cpp(snake_case_name));
// https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-camel-cased-attribute
// For each CSS property property that is a supported CSS property, the following partial interface applies
// where camel-cased attribute is obtained by running the CSS property to IDL attribute algorithm for property.
// partial interface CSSStyleProperties {
// [CEReactions] attribute [LegacyNullToEmptyString] CSSOMString _camel_cased_attribute;
// };
member_generator.set("name:camelcase", css_property_to_idl_attribute(name));
member_generator.append(R"~~~(
[CEReactions, LegacyNullToEmptyString, AttributeCallbackName=@name:snakecase@_regular, ImplementedAs=@name:acceptable_cpp@] attribute CSSOMString @name:camelcase@;
)~~~");
// For each CSS property property that is a supported CSS property and that begins with the string -webkit-,
// the following partial interface applies where webkit-cased attribute is obtained by running the CSS property
// to IDL attribute algorithm for property, with the lowercase first flag set.
if (name.starts_with_bytes("-webkit-"sv)) {
member_generator.set("name:webkit", css_property_to_idl_attribute(name, /* lowercase_first= */ true));
member_generator.append(R"~~~(
[CEReactions, LegacyNullToEmptyString, AttributeCallbackName=@name:snakecase@_webkit, ImplementedAs=@name:acceptable_cpp@] attribute CSSOMString @name:webkit@;
)~~~");
}
// For each CSS property property that is a supported CSS property, except for properties that have no
// "-" (U+002D) in the property name, the following partial interface applies where dashed attribute is
// property.
// partial interface CSSStyleProperties {
// [CEReactions] attribute [LegacyNullToEmptyString] CSSOMString _dashed_attribute;
// };
if (name.contains('-')) {
member_generator.append(R"~~~(
[CEReactions, LegacyNullToEmptyString, AttributeCallbackName=@name:snakecase@_dashed, ImplementedAs=@name:acceptable_cpp@] attribute CSSOMString @name@;
)~~~");
}
});
generator.append(R"~~~(
};
)~~~");
TRY(file.write_until_depleted(generator.as_string_view().bytes()));
return {};
}