dymokomi/luce-browser-engine
Source of release 0.6.1
0.6.1 / tools / gen_css_values / emit_property_values.lucb
#==============================================================================================
#
# emit_property_values - the value-dependent functions of PropertyID, DescriptorID and
# EnvironmentVariable
#
# DESCRIPTION:
# Port of the parts of Meta/Generators/generate_libweb_css_property_id.py,
# generate_libweb_css_descriptors.py and generate_libweb_css_environment_variables.py
# that build or test style values (css_data has the rest, from luce-browser-css's
# tools/gen_css; DESIGN.md §4.1.3):
#
# property_id.lucb property_initial_value, property_accepts_type,
# property_accepted_ranges_by_value_type,
# property_resolves_percentages_relative_to and the
# Angle/Flex/Frequency/Length/Percentage/Resolution/Time
# range checks (Build/.../CSS/PropertyID.cpp)
# descriptor_id.lucb descriptor_initial_value (Build/.../CSS/DescriptorID.cpp)
# environment_variable.lucb environment_variable_type
# (Build/.../CSS/EnvironmentVariable.cpp)
#
# The property data is prepared as the Python prepares it: logical aliases replaced by
# their group's first physical property (overridden by their own members, without
# quirks), and `all` given every longhand.
#
#==============================================================================================
# mark: Property data (generate_libweb_css_property_id.py) ======================================
## Ported from generate_libweb_css_property_id.py is_legacy_alias.
func is_legacy_alias(property: const Json*) -> bool:
return property.has("legacy-alias-for")
## Ported from generate_libweb_css_property_id.py verify_alphabetical.
func verify_alphabetical(data: const Json*, path: str):
var most_recent_name = ""
for index in 0..<data.count:
let name = data.key(index)
if string_less(name, most_recent_name):
trap(f"`{name}` is in the wrong position in `{path}`. Please keep this list alphabetical!")
most_recent_name = name
## Ported from generate_libweb_css_property_id.py replace_logical_aliases: each logical alias
## becomes a copy of the first physical property of its group, overridden by its own members,
## without quirks.
func replace_logical_aliases(properties: Json*, logical_property_groups: const Json*) -> !:
# Grab the first physical property in each logical group, to use as the template
var group_names = try StrList.create()
var first_physical = try StrList.create()
for index in 0..<logical_property_groups.count:
let group_name = logical_property_groups.key(index)
let physical = logical_property_groups.at(index).get("physical") else trap(f"No physical properties in group {group_name}")
if physical.count == 0:
trap(f"No physical properties in group {group_name}")
try group_names.append(group_name)
try first_physical.append(physical.at(0).string())
var alias_names = try StrList.create()
var alias_targets = try StrList.create()
for index in 0..<properties.count:
let name = properties.key(index)
let logical_alias_for = properties.at(index).get("logical-alias-for") else continue
let group = logical_alias_for.get("group") else trap(f"Logical alias '{name}' is missing its group")
var physical_property_name: str? = none
for group_index in 0..<group_names.count:
if group_names.at(group_index) == group.string():
physical_property_name = first_physical.at(group_index)
let target = physical_property_name else trap(f"Logical property group '{group.string()}' not found! (Property: '{name}')")
try alias_names.append(name)
try alias_targets.append(target)
for index in 0..<alias_names.count:
let name = alias_names.at(index)
let alias = alias_targets.at(index)
let template = properties.get(alias) else trap(f"No property '{alias}' found for logical alias '{name}'")
let alias_object = try json_clone(template)
# Copy over anything the logical property overrides
let logical = properties.get(name) else trap("a logical alias that vanished")
for member in 0..<logical.count:
try json_set(alias_object, logical.key(member), logical.at(member))
# Quirks don't carry across to logical aliases
json_remove(alias_object, "quirks")
try json_set(properties, name, alias_object)
## Ported from generate_libweb_css_property_id.py populate_all_property_longhands: `all` is the
## shorthand of every longhand except direction and unicode-bidi.
func populate_all_property_longhands(properties: Json*) -> !:
let all_entry = properties.get("all") else trap("Missing 'all' property")
let longhands = all_entry.get("longhands") else trap("'all' has no longhands")
for index in 0..<properties.count:
let name = properties.key(index)
let value = properties.at(index)
if value.has("longhands") or value.has("legacy-alias-for") or name == "direction" or name == "unicode-bidi":
continue
try json_append(longhands, "", try json_new(.string, name))
## `.x` for the property `name`, as a match pattern.
func property_case(name: str) -> str!:
return try cat([".", try luce_case(try title_casify(name))])
## `css_data.PropertyId.x` for the property `name`.
func property_id_value(name: str) -> str!:
return try cat(["css_data.PropertyId.", try luce_case(try title_casify(name))])
## `CssValueType.x` for the value type `name` (`length-percentage`).
func value_type_value(name: str) -> str!:
return try cat(["CssValueType.", try luce_case(try title_casify(name))])
## The type word of a valid-types entry (`length` of `length [0,∞]`).
func valid_type_name(valid_type: str) -> str:
if let parts = strings.split_once(valid_type, " "):
return parts.0
return valid_type
## A range bound of Properties.json as a double literal: the C++ compares a double with the
## integer literal, which Luce spells as a float literal.
func double_literal(text: str) -> str!:
if contains(text, ".") or contains(text, "e"):
return text
return try cat([text, ".0"])
## Ported from generate_libweb_css_property_id.py format_numeric_range: the bounds of a
## NumericRange, as double literals (`AK::NumericLimits<i32>::min()` is -2147483648,
## `AK::NumericLimits<float>::lowest()` is the most negative float, widened).
func format_numeric_range(type_name: str, min_val: str, max_val: str) -> (str, str)!:
var min_str: str
var max_str: str
if type_name == "integer":
min_str = "-2147483648.0" if min_val == "-∞" else try double_literal(min_val)
max_str = "2147483647.0" if max_val == "∞" else try double_literal(max_val)
else:
min_str = "-3.4028234663852886e38" if min_val == "-∞" else try double_literal(min_val)
max_str = "3.4028234663852886e38" if max_val == "∞" else try double_literal(max_val)
return (min_str, max_str)
# mark: property_id.lucb ========================================================================
## Emit generated/property_id.lucb from Properties.json, Enums.json and LogicalPropertyGroups.json.
func emit_property_id_values(properties: Json*, enums: const Json*, logical_property_groups: const Json*) -> str!:
verify_alphabetical(properties, "Properties.json")
verify_alphabetical(logical_property_groups, "LogicalPropertyGroups.json")
verify_alphabetical(enums, "Enums.json")
var enum_names = try StrList.create()
for index in 0..<enums.count:
try enum_names.append(enums.key(index))
try replace_logical_aliases(properties, logical_property_groups)
try populate_all_property_longhands(properties)
var out = try Out.create()
try put_header(&out, "property_id", "the CSS properties: initial values, accepted types and ranges", [
"Generated by tools/gen_css_values from data/css/Properties.json, Enums.json and",
"LogicalPropertyGroups.json; do not edit. The C++ it stands for, at Ladybird 47c82b38d0, is",
"the value-dependent part of Build/Libraries/LibWeb/CSS/PropertyID.cpp, written by",
"Meta/Generators/generate_libweb_css_property_id.py; the rest of that file is css_data's.",
"",
"property_initial_value's static array of parsed values lives as long as the program: the",
"values are made in the C heap, their strings included (the atomic allocator view is cleared",
"while they are parsed), so that the collector neither frees nor scans them.",
"",
"Copyright (c) 2018-2020, Andreas Kling <andreas@ladybird.org>",
"Copyright (c) 2021-2026, Sam Atkins <sam@ladybird.org>",
"Copyright (c) 2026-present, the Ladybird developers.",
"Copyright (c) 2026 the luce-browser authors.",
"SPDX-License-Identifier: BSD-2-Clause (see data/css/LICENSE)",
])
try put_mark(&out, "property_initial_value")
# to_underlying(last_property_id) + 1: Custom and every property that is not a legacy alias.
var property_id_count: usize = 1
for index in 0..<properties.count:
if not is_legacy_alias(properties.at(index)):
property_id_count += 1
try out.line("# The `static Array<RefPtr<StyleValue const>, to_underlying(last_property_id) + 1> initial_values` of")
try out.line("# property_initial_value.")
try out.line(f"var css_property_initial_values: (CssStyleValue*?)[{property_id_count}]")
try out.blank()
try out.line("## One case of property_initial_value: `parse_css_value(parsing_params, text, property_id)`, which must")
try out.line("## succeed, kept in the static array. Everything the parse allocates is made in the C heap.")
try out.line("func css_parse_property_initial_value(property_id: css_data.PropertyId, text: str) -> CssStyleValue*:")
try out.line(" let saved_atomic_allocator = ak.atomic_allocator")
try out.line(" ak.atomic_allocator = none")
try out.line(" defer ak.atomic_allocator = saved_atomic_allocator")
try out.line(" with memory.heap:")
try out.line(" var parsing_params: CssParsingParams = ---")
try out.line(" css_parsing_params_construct_css_parsing_mode(&parsing_params)")
try out.line(" let parsed_value = parse_css_value(parsing_params, ak.sv(text), property_id)")
try out.line(" let initial_value = parsed_value else trap(\"VERIFY: !parsed_value.is_null()\")")
try out.line(" css_property_initial_values[(usize)property_id] = initial_value")
try out.line(" return initial_value")
try out.blank()
try out.line("## Ported from Build/Libraries/LibWeb/CSS/PropertyID.cpp Web::CSS::property_initial_value.")
try out.line("pub func css_property_initial_value(property_id: css_data.PropertyId) -> CssStyleValue*:")
try out.line(" if let initial_value = css_property_initial_values[(usize)property_id]:")
try out.line(" return initial_value")
try out.blank()
try out.line(" # Lazily parse initial values as needed.")
try out.line(" # This ensures the shorthands will always be able to get the initial values of their longhands.")
try out.line(" # This also now allows a longhand have its own longhand (like background-position-x).")
try out.blank()
try out.line(" match property_id:")
for index in 0..<properties.count:
let name = properties.key(index)
let value = properties.at(index)
if is_legacy_alias(value):
continue
let initial = value.get("initial") else trap(f"No initial value specified for property '{name}'")
try out.line(f" {try property_case(name)}:")
try out.line(f" return css_parse_property_initial_value({try property_id_value(name)}, {try literal(initial.string())})")
try out.line(" _:")
try out.line(" trap(\"VERIFY_NOT_REACHED\")")
try put_mark(&out, "property_accepts_type")
try out.line("## Ported from Build/Libraries/LibWeb/CSS/PropertyID.cpp Web::CSS::property_accepts_type.")
try out.line("pub func css_property_accepts_type(property_id: css_data.PropertyId, value_type: CssValueType) -> bool:")
try out.line(" match property_id:")
for index in 0..<properties.count:
let value = properties.at(index)
if is_legacy_alias(value):
continue
let valid_types = value.get("valid-types") else continue
if not valid_types.truthy():
continue
var accepted: collections.Buffer
for type_index in 0..<valid_types.count:
let type_name = valid_type_name(valid_types.at(type_index).string())
if enum_names.contains(type_name):
continue
if accepted.length() > 0:
try accepted.put_text(", ")
try accepted.put_text(".")
try accepted.put_text(try luce_case(try title_casify(type_name)))
try out.line(f" {try property_case(properties.key(index))}:")
if accepted.length() == 0:
try out.line(" return false")
continue
try out.line(" match value_type:")
try out.line(f" {accepted.text()}:")
try out.line(" return true")
try out.line(" _:")
try out.line(" return false")
try out.line(" _:")
try out.line(" return false")
try put_mark(&out, "property_accepted_ranges_by_value_type")
try out.line("## Ported from Build/Libraries/LibWeb/CSS/PropertyID.cpp Web::CSS::property_accepted_ranges_by_value_type.")
try out.line("pub func css_property_accepted_ranges_by_value_type(property_id: css_data.PropertyId) -> ak.HashMap[CssValueType, CssNumericRange, CssValueTypeTraits]:")
try out.line(" var ranges = ak.HashMap[CssValueType, CssNumericRange, CssValueTypeTraits]()")
try out.line(" match property_id:")
for index in 0..<properties.count:
let value = properties.at(index)
if is_legacy_alias(value):
continue
let valid_types = value.get("valid-types") else continue
if not valid_types.truthy():
continue
try out.line(f" {try property_case(properties.key(index))}:")
for type_index in 0..<valid_types.count:
let type_entry = valid_types.at(type_index).string()
let type_parts = strings.split_once(type_entry, " ") else continue
let type_name = type_parts.0
if type_name == "custom-ident":
continue
# Drop brackets: "[-∞,∞]" -> "-∞,∞"
let type_range = slice(type_parts.1, 1, type_parts.1.length - 1)
let limits = strings.split_once(type_range, ",") else trap(f"Bad range: {type_parts.1}")
if contains(limits.1, ","):
trap(f"Bad range: {type_parts.1}")
let bounds = try format_numeric_range(type_name, limits.0, limits.1)
try out.line(f" _ = ak.hash_map_set(&ranges, {try value_type_value(type_name)}, CssNumericRange(min = {bounds.0}, max = {bounds.1}))")
try out.line(" return ranges")
try out.line(" _:")
try out.line(" return ranges")
try put_mark(&out, "property_resolves_percentages_relative_to")
try out.line("## Ported from Build/Libraries/LibWeb/CSS/PropertyID.cpp Web::CSS::property_resolves_percentages_relative_to.")
try out.line("pub func css_property_resolves_percentages_relative_to(property_id: css_data.PropertyId) -> CssValueType?:")
try out.line(" match property_id:")
for index in 0..<properties.count:
let value = properties.at(index)
if is_legacy_alias(value):
continue
let resolved_type = value.get("percentages-resolve-to") else continue
try out.line(f" {try property_case(properties.key(index))}:")
try out.line(f" return {try value_type_value(resolved_type.string())}")
try out.line(" _:")
try out.line(" return none")
try put_mark(&out, "The range checks")
try generate_bounds_checking_function(&out, properties, "angle", "CssAngle", "css_angle_raw_value(&value)", first = true)
try generate_bounds_checking_function(&out, properties, "flex", "CssFlex", "css_flex_raw_value(&value)")
try generate_bounds_checking_function(&out, properties, "frequency", "CssFrequency", "css_frequency_raw_value(&value)")
try generate_bounds_checking_function(&out, properties, "length", "CssLength", "css_length_raw_value(&value)")
try generate_bounds_checking_function(&out, properties, "percentage", "CssPercentage", "css_percentage_value(&value)")
try generate_bounds_checking_function(&out, properties, "resolution", "CssResolution", "css_resolution_raw_value(&value)")
try generate_bounds_checking_function(&out, properties, "time", "CssTime", "css_time_raw_value(&value)")
return out.text()
## Ported from generate_libweb_css_property_id.py generate_bounds_checking_function, for the value
## types whose C++ types are the engine's (Angle, Flex, Frequency, Length, Percentage, Resolution,
## Time; css_data has `integer` and `number`).
func generate_bounds_checking_function(out: Out*, properties: const Json*, css_type_name: str, type_name: str, value_getter: str, first: bool = false) -> !:
if not first:
try out.blank()
try out.line(f"## Ported from Build/Libraries/LibWeb/CSS/PropertyID.cpp Web::CSS::property_accepts_{css_type_name}.")
try out.line(f"pub func css_property_accepts_{css_type_name}(property_id: css_data.PropertyId, value: {type_name}) -> bool:")
try out.line(" match property_id:")
for index in 0..<properties.count:
let value = properties.at(index)
if is_legacy_alias(value):
continue
let valid_types = value.get("valid-types") else continue
if not valid_types.truthy():
continue
for type_index in 0..<valid_types.count:
let valid_type = valid_types.at(type_index).string()
var type_word = valid_type
var range: str? = none
if let parts = strings.split_once(valid_type, " "):
type_word = parts.0
range = parts.1
if type_word != css_type_name:
continue
let case_text = try property_case(properties.key(index))
if range == none:
try out.line(f" {case_text}: return true")
break
let range_str = range else trap("unreachable")
if not (starts_with(range_str, "[") and ends_with(range_str, "]") and contains(range_str, ",")):
trap(f"Bad range: {range_str}")
let limits = strings.split_once(slice(range_str, 1, range_str.length - 1), ",") else trap("Bad range")
var min_value_string = limits.0
var max_value_string = limits.1
if min_value_string == "-∞":
min_value_string = ""
if max_value_string == "∞":
max_value_string = ""
if min_value_string.length == 0 and max_value_string.length == 0:
try out.line(f" {case_text}: return true")
break
var condition: collections.Buffer
if min_value_string.length > 0:
try condition.put_text(value_getter)
try condition.put_text(" >= ")
try condition.put_text(try double_literal(min_value_string))
if max_value_string.length > 0:
if min_value_string.length > 0:
try condition.put_text(" and ")
try condition.put_text(value_getter)
try condition.put_text(" <= ")
try condition.put_text(try double_literal(max_value_string))
try out.line(f" {case_text}: return {condition.text()}")
break
try out.line(" _: return false")
# mark: descriptor_id.lucb ======================================================================
## Ported from generate_libweb_css_descriptors.py is_legacy_alias.
func is_descriptor_legacy_alias(descriptor: const Json*) -> bool:
return descriptor.has("legacy-alias-for")
## The `descriptors` object of an at-rule, or an empty one (Python's `.get("descriptors", {})`).
func at_rule_descriptors(at_rule: const Json*) -> const Json*!:
if let descriptors = at_rule.get("descriptors"):
return descriptors
return try json_new(.object, "")
## Ported from generate_libweb_css_descriptors.py collect_all_descriptors: every descriptor
## name that is not a legacy alias, once, in code point order.
func collect_all_descriptors(at_rules_data: const Json*) -> StrList!:
var names = try StrList.create()
for at_rule_index in 0..<at_rules_data.count:
let descriptors = try at_rule_descriptors(at_rules_data.at(at_rule_index))
for index in 0..<descriptors.count:
if is_descriptor_legacy_alias(descriptors.at(index)):
continue
let name = descriptors.key(index)
if not names.contains(name):
try names.append(name)
sort_strings(&names)
return names
## Emit generated/descriptor_id.lucb from Descriptors.json.
func emit_descriptor_id_values(at_rules_data: const Json*) -> str!:
let all_descriptors = try collect_all_descriptors(at_rules_data)
var out = try Out.create()
try put_header(&out, "descriptor_id", "the initial values of the CSS descriptors", [
"Generated by tools/gen_css_values from data/css/Descriptors.json; do not edit. The C++ it",
"stands for, at Ladybird 47c82b38d0, is descriptor_initial_value() of",
"Build/Libraries/LibWeb/CSS/DescriptorID.cpp, written by",
"Meta/Generators/generate_libweb_css_descriptors.py; the rest of that file is css_data's.",
"As property_initial_value's, the cached values are made in the C heap.",
"",
"Copyright (c) 2022-2026, Sam Atkins <sam@ladybird.org>",
"Copyright (c) 2024, Luke Wilde <luke@ladybird.org>",
"Copyright (c) 2026-present, the Ladybird developers.",
"Copyright (c) 2026 the luce-browser authors.",
"SPDX-License-Identifier: BSD-2-Clause (see data/css/LICENSE)",
])
try out.blank()
try out.line(f"# The `static Array<Array<RefPtr<StyleValue const>, {all_descriptors.count}>, {at_rules_data.count}> initial_values` of descriptor_initial_value.")
try out.line(f"var css_descriptor_initial_values: ((CssStyleValue*?)[{all_descriptors.count}])[{at_rules_data.count}]")
try out.blank()
try out.line("## One case of descriptor_initial_value: `parse_css_descriptor(parsing_params, at_rule_id,")
try out.line("## DescriptorNameAndID::from_id(descriptor_id), text)`, which must succeed, kept in the static array.")
try out.line("## Everything the parse allocates is made in the C heap.")
try out.line("func css_parse_descriptor_initial_value(at_rule_id: css_data.AtRuleId, descriptor_id: css_data.DescriptorId, text: str) -> CssStyleValue*:")
try out.line(" let saved_atomic_allocator = ak.atomic_allocator")
try out.line(" ak.atomic_allocator = none")
try out.line(" defer ak.atomic_allocator = saved_atomic_allocator")
try out.line(" with memory.heap:")
try out.line(" var parsing_params: CssParsingParams = ---")
try out.line(" css_parsing_params_construct_css_parsing_mode(&parsing_params)")
try out.line(" let parsed_value = parse_css_descriptor(parsing_params, at_rule_id, css_descriptor_name_and_id_from_id(descriptor_id), ak.sv(text))")
try out.line(" let initial_value = parsed_value else trap(\"VERIFY: !parsed_value.is_null()\")")
try out.line(" css_descriptor_initial_values[(usize)at_rule_id][(usize)descriptor_id] = initial_value")
try out.line(" return initial_value")
try out.blank()
try out.line("## Ported from Build/Libraries/LibWeb/CSS/DescriptorID.cpp Web::CSS::descriptor_initial_value.")
try out.line("pub func css_descriptor_initial_value(at_rule_id: css_data.AtRuleId, descriptor_id: css_data.DescriptorId) -> CssStyleValue*?:")
try out.line(" if not css_data.at_rule_supports_descriptor(at_rule_id, descriptor_id):")
try out.line(" return none")
try out.blank()
try out.line(" if let initial_value = css_descriptor_initial_values[(usize)at_rule_id][(usize)descriptor_id]:")
try out.line(" return initial_value")
try out.blank()
try out.line(" # Lazily parse initial values as needed.")
try out.blank()
try out.line(" match at_rule_id:")
for at_rule_index in 0..<at_rules_data.count:
let at_rule_name = at_rules_data.key(at_rule_index)
let at_rule_case = try luce_case(try title_casify(at_rule_name))
try out.line(f" .{at_rule_case}:")
try out.line(" match descriptor_id:")
let descriptors = try at_rule_descriptors(at_rules_data.at(at_rule_index))
for index in 0..<descriptors.count:
let descriptor = descriptors.at(index)
if is_descriptor_legacy_alias(descriptor):
continue
let descriptor_case = try luce_case(try title_casify(descriptors.key(index)))
if let initial_value = descriptor.get("initial"):
try out.line(f" .{descriptor_case}:")
try out.line(f" return css_parse_descriptor_initial_value(css_data.AtRuleId.{at_rule_case}, css_data.DescriptorId.{descriptor_case}, {try literal(initial_value.string())})")
else:
try out.line(f" .{descriptor_case}:")
try out.line(" return none")
try out.line(" _:")
try out.line(" trap(\"VERIFY_NOT_REACHED\")")
try out.line(" _:")
try out.line(" trap(\"VERIFY_NOT_REACHED\")")
return out.text()
# mark: environment_variable.lucb ===============================================================
## Emit generated/environment_variable.lucb from EnvironmentVariables.json.
func emit_environment_variable_values(environment_variables: const Json*) -> str!:
var out = try Out.create()
try put_header(&out, "environment_variable", "the value types of the CSS environment variables", [
"Generated by tools/gen_css_values from data/css/EnvironmentVariables.json; do not edit.",
"The C++ it stands for, at Ladybird 47c82b38d0, is environment_variable_type() of",
"Build/Libraries/LibWeb/CSS/EnvironmentVariable.cpp, written by",
"Meta/Generators/generate_libweb_css_environment_variables.py; the rest of that file is",
"css_data's.",
"",
"Copyright (c) 2025-2026, Sam Atkins <sam@ladybird.org>",
"Copyright (c) 2026-present, the Ladybird developers.",
"Copyright (c) 2026 the luce-browser authors.",
"SPDX-License-Identifier: BSD-2-Clause (see data/css/LICENSE)",
])
try out.blank()
try out.line("## Ported from Build/Libraries/LibWeb/CSS/EnvironmentVariable.cpp Web::CSS::environment_variable_type.")
try out.line("pub func css_environment_variable_type(environment_variable: css_data.EnvironmentVariable) -> CssValueType:")
try out.line(" match environment_variable:")
for index in 0..<environment_variables.count:
let name = environment_variables.key(index)
let variable = environment_variables.at(index)
let type_text = (variable.get("type") else trap(f"no type for {name}")).string()
# Python's `.strip("<>")`.
var start: usize = 0
var end = type_text.length
while start < end and (type_text.bytes[start] == '<' or type_text.bytes[start] == '>'):
start += 1
while end > start and (type_text.bytes[end - 1] == '<' or type_text.bytes[end - 1] == '>'):
end -= 1
try out.line(f" .{try luce_case(try title_casify(name))}:")
try out.line(f" return {try value_type_value(slice(type_text, start, end))}")
try out.line(" _:")
try out.line(" trap(\"VERIFY_NOT_REACHED\")")
return out.text()