Skip to content

Truly independent web browser

LibWeb: Build CSS Typed OM style values in Rust

Andreas Klingb0927a97190d
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/style_property_map.rs b/Libraries/LibWeb/Bindings/Rust/src/css/style_property_map.rs
index 046b5881fe4..ab2b78a7091 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/style_property_map.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/style_property_map.rs
@@ -23,7 +23,6 @@ use crate::bindings::{CallContext, Exception, WebIdlResult};
use crate::css::css_style_value::PerformTypeCheck;
unsafe extern "C" {
- fn web_css_style_map_property_is_list_valued(property_id: u16) -> bool;
fn web_css_style_map_parse(declaration: *mut c_void, property_id: u16, css_text: usize) -> *const c_void;
fn web_css_style_map_declared_value(declaration: *mut c_void, name: usize) -> *const c_void;
fn web_css_style_map_set_value(
@@ -92,8 +91,7 @@ fn is_custom_property(property: &Property) -> bool {
}
fn is_list_valued(property: &Property) -> bool {
- // SAFETY: This only reads the tables of the properties.
- unsafe { web_css_style_map_property_is_list_valued(property.id) }
+ super::typed_om::property_is_list_valued(property.id)
}
// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/typed_om.rs b/Libraries/LibWeb/Bindings/Rust/src/css/typed_om.rs
index 55ccf3bcfbd..799ce5f4046 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/typed_om.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/typed_om.rs
@@ -4,8 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! What the interfaces of the CSS Typed OM share: reification, and what they ask of LibWeb's C++ code, where the tables
-//! of the properties and the parser's entry points are.
+//! What the interfaces of the CSS Typed OM share: reification, and how values reach the property tables and the parser.
//! https://drafts.css-houdini.org/css-typed-om-1/
use core::ffi::c_void;
@@ -14,9 +13,10 @@ use std::sync::Arc;
use ak::Utf16String;
use libjs_rust::api::{MarkedVec, Vm};
use libweb_rust::typed_om::{
- CalcNode, CalcReificationNode, DimensionType, FfiNumericType, NumericType, NumericValue, Reification,
+ self, CalcNode, CalcReificationNode, DimensionType, NumericType, NumericValue, Reification,
ReifiedUnresolvedSegment, RetainedStyleValue, calculation_nodes, reification_of,
};
+pub(crate) use libweb_rust::typed_om::{TypedOmValueType, property_accepts_type};
use super::css_image_value::CSSImageValue;
use super::css_keyword_value::CSSKeywordValue;
@@ -39,58 +39,31 @@ use crate::bindings::conversions::UsvString;
use crate::bindings::interface::Ref;
use crate::bindings::{CallContext, Exception, WebIdlResult};
-/// The value types that the Typed OM asks about, which C++ maps to its enum class ValueType.
-#[derive(Clone, Copy)]
-#[repr(u8)]
-pub(crate) enum TypedOmValueType {
- Image,
- TransformFunction,
- TransformList,
+/// The string as a Rust string, for what is ASCII or only goes into a message.
+pub(crate) fn to_rust_string(string: &Utf16String) -> String {
+ String::from_utf16_lossy(&string.to_utf16())
}
unsafe extern "C" {
- fn web_css_typed_om_property_accepts_type(property_id: u16, value_type: TypedOmValueType) -> bool;
- fn web_css_typed_om_numeric_style_value(
- property_id: u16,
- value: *const c_void,
- calculation: *const c_void,
- numeric_type: FfiNumericType,
- ) -> *const c_void;
- fn web_css_typed_om_calculated_style_value(
- property_id: u16,
- calculation: *const c_void,
- numeric_type: FfiNumericType,
- perform_type_check: bool,
- ) -> *const c_void;
- fn web_css_typed_om_keyword_style_value(property_id: u16, value: usize, perform_type_check: bool) -> *const c_void;
- fn web_css_typed_om_style_value_list(values: *const *const c_void, count: usize, comma: bool) -> *const c_void;
- fn web_css_typed_om_parse_numeric_value(css_text: usize) -> *const c_void;
- fn web_css_typed_om_parse_value(
- property: usize,
- css_text: usize,
- values: *mut c_void,
- append: unsafe extern "C" fn(*mut c_void, *const c_void),
- out_name_or_error: *mut usize,
- ) -> bool;
- fn web_css_typed_om_zero_is_a_length(property: usize, is_integer: bool) -> bool;
+ fn web_css_style_map_property_is_list_valued(property_id: u16) -> bool;
}
-fn optional_style_value(pointer: *const c_void) -> Option<RetainedStyleValue> {
- if pointer.is_null() {
- return None;
- }
- // SAFETY: C++ hands over a strong reference to a style value.
- Some(unsafe { RetainedStyleValue::from_raw(pointer) })
-}
-
-/// The string as a Rust string, for what is ASCII or only goes into a message.
-pub(crate) fn to_rust_string(string: &Utf16String) -> String {
- String::from_utf16_lossy(&string.to_utf16())
+pub(crate) fn property_is_list_valued(property_id: u16) -> bool {
+ // SAFETY: The call has no preconditions.
+ unsafe { web_css_style_map_property_is_list_valued(property_id) }
}
-pub(crate) fn property_accepts_type(property_id: u16, value_type: TypedOmValueType) -> bool {
- // SAFETY: The call has no preconditions.
- unsafe { web_css_typed_om_property_accepts_type(property_id, value_type) }
+/// https://drafts.css-houdini.org/css-typed-om-1/#subdivide-into-iterations
+fn subdivide_into_iterations(value: RetainedStyleValue, property_id: u16) -> Vec<RetainedStyleValue> {
+ // 1. If property is a single-valued property, return a list containing whole value.
+ // 2. Otherwise, divide whole value into individual iterations, as appropriate for property, and return a list
+ // containing the iterations in order.
+ if property_is_list_valued(property_id)
+ && let Some(iterations) = value.value_list_items()
+ {
+ return iterations;
+ }
+ vec![value]
}
pub(crate) fn property_accepts_transform_function(property_id: u16) -> bool {
@@ -108,17 +81,8 @@ pub(crate) fn numeric_style_value_for_property(
value: NumericValue,
numeric_type: NumericType,
) -> Option<RetainedStyleValue> {
- let style_value = value.style_value().into_raw();
- let calculation = Arc::into_raw(Arc::new(CalcNode::Sum(vec![value.calculation_node()]))).cast();
- // SAFETY: This hands over one strong reference to the style value and to the calculation.
- optional_style_value(unsafe {
- web_css_typed_om_numeric_style_value(
- property_id,
- style_value,
- calculation,
- FfiNumericType::from_calc(Some(numeric_type)),
- )
- })
+ let calculation = Arc::new(CalcNode::Sum(vec![value.calculation_node()]));
+ typed_om::numeric_style_value(property_id, value.style_value(), calculation, numeric_type)
}
/// The calculated value of the property for a CSSMathValue, if the property takes values of its type.
@@ -128,15 +92,12 @@ pub(crate) fn calculated_style_value(
numeric_type: NumericType,
perform_type_check: PerformTypeCheck,
) -> Option<RetainedStyleValue> {
- // SAFETY: This hands over one strong reference to the calculation.
- optional_style_value(unsafe {
- web_css_typed_om_calculated_style_value(
- property_id,
- Arc::into_raw(calculation).cast(),
- FfiNumericType::from_calc(Some(numeric_type)),
- perform_type_check == PerformTypeCheck::Yes,
- )
- })
+ typed_om::calculated_style_value(
+ property_id,
+ calculation,
+ numeric_type,
+ perform_type_check == PerformTypeCheck::Yes,
+ )
}
/// The value of the property for a CSSKeywordValue, if the keyword matches the grammar of the property.
@@ -145,36 +106,25 @@ pub(crate) fn keyword_style_value_for_property(
value: &Utf16String,
perform_type_check: PerformTypeCheck,
) -> Option<RetainedStyleValue> {
- // SAFETY: This hands over a reference to the string.
- optional_style_value(unsafe {
- web_css_typed_om_keyword_style_value(
- property_id,
- value.clone().into_raw(),
- perform_type_check == PerformTypeCheck::Yes,
- )
- })
-}
-
-/// A list of the values, separated by spaces.
-fn create_style_value_list(values: Vec<RetainedStyleValue>, comma: bool) -> RetainedStyleValue {
- let values: Vec<_> = values.into_iter().map(RetainedStyleValue::into_raw).collect();
- // SAFETY: This hands over one strong reference to each of the values.
- optional_style_value(unsafe { web_css_typed_om_style_value_list(values.as_ptr(), values.len(), comma) })
- .expect("a list is a style value")
+ typed_om::keyword_style_value(
+ property_id,
+ value,
+ perform_type_check == PerformTypeCheck::Yes,
+ property_is_list_valued(property_id),
+ )
}
pub(crate) fn style_value_list(values: Vec<RetainedStyleValue>) -> RetainedStyleValue {
- create_style_value_list(values, false)
+ typed_om::style_value_list(values, false)
}
pub(crate) fn comma_separated_style_value_list(values: Vec<RetainedStyleValue>) -> RetainedStyleValue {
- create_style_value_list(values, true)
+ typed_om::style_value_list(values, true)
}
/// The first of the numeric types that the text parses as, https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-parse
pub(crate) fn parse_a_numeric_value(css_text: &Utf16String) -> Option<RetainedStyleValue> {
- // SAFETY: This hands over a reference to the string.
- optional_style_value(unsafe { web_css_typed_om_parse_numeric_value(css_text.clone().into_raw()) })
+ typed_om::parse_a_numeric_value(css_text)
}
pub(crate) unsafe extern "C" fn append_style_value(values: *mut c_void, value: *const c_void) {
@@ -188,29 +138,33 @@ pub(crate) fn parse_values(
property: Utf16String,
css_text: Utf16String,
) -> WebIdlResult<MarkedVec<'_, AnyCSSStyleValue>> {
- // NB: Steps 1 to 4 parse with the tables of the properties, and result in the iterations of the value.
- let mut values: Vec<RetainedStyleValue> = Vec::new();
- let mut name_or_error = 0;
- // SAFETY: This hands over references to the strings, and the context lives through the call.
- let parsed = unsafe {
- web_css_typed_om_parse_value(
- property.into_raw(),
- css_text.into_raw(),
- (&raw mut values).cast(),
- append_style_value,
- &raw mut name_or_error,
- )
+ // 1. If property is not a custom property name string, set property to property ASCII lowercased.
+ // 2. If property is not a valid CSS property, throw a TypeError.
+ let Some((name, property_id)) = typed_om::property_from_name(&property) else {
+ return Err(Exception::TypeError(Utf16String::from_utf8(&format!(
+ "'{}' is not a valid CSS property",
+ to_rust_string(&property)
+ ))));
};
- // SAFETY: C++ hands over a reference to a string.
- let name_or_error = unsafe { Utf16String::from_raw_owned(name_or_error) };
- if !parsed {
- return Err(Exception::TypeError(name_or_error));
- }
+
+ // 3. Attempt to parse cssText according to property’s grammar.
+ // If this fails, throw a TypeError.
+ // Otherwise, let whole value be the parsed result.
+ let Some(whole_value) = typed_om::parse_value_for_property(property_id, &css_text) else {
+ return Err(Exception::TypeError(Utf16String::from_utf8(&format!(
+ "Failed to parse '{}' as a value for '{}' property",
+ to_rust_string(&css_text),
+ to_rust_string(&property)
+ ))));
+ };
+
+ // 4. Subdivide into iterations whole value, according to property, and let values be the result.
+ let values = subdivide_into_iterations(whole_value, property_id);
// 5. For each value in values, replace it with the result of reifying value for property.
let reified_values = MarkedVec::new(vm);
for value in &values {
- reified_values.push(reify(vm, value, &name_or_error));
+ reified_values.push(reify(vm, value, &name));
}
// 6. If parseMultiple is false, return values[0]. Otherwise, return values.
@@ -261,8 +215,7 @@ pub(crate) fn reify(vm: &Vm, value: &RetainedStyleValue, property: &Utf16String)
Reification::Number { value, is_integer } => {
// NB: Determine whether the associated property expects 0 to be a <length>.
// FIXME: Do this for registered custom properties.
- // SAFETY: This hands over a reference to the string.
- if value == 0.0 && unsafe { web_css_typed_om_zero_is_a_length(property.clone().into_raw(), is_integer) } {
+ if value == 0.0 && typed_om::zero_is_a_length(property, is_integer) {
return unit_value(vm, 0.0, "px");
}
unit_value(vm, value, "number")
diff --git a/Libraries/LibWeb/CSS/TypedOM.cpp b/Libraries/LibWeb/CSS/TypedOM.cpp
index 73a714e0048..4a4e3a0b79c 100644
--- a/Libraries/LibWeb/CSS/TypedOM.cpp
+++ b/Libraries/LibWeb/CSS/TypedOM.cpp
@@ -9,28 +9,9 @@
#include <LibWeb/CSS/CSSKeywordValue.h>
#include <LibWeb/CSS/CSSNumericValue.h>
#include <LibWeb/CSS/CSSUnitValue.h>
-#include <LibWeb/CSS/Keyword.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/PropertyID.h>
#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
-#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
-#include <LibWeb/CSS/StyleValues/CustomIdentStyleValue.h>
-#include <LibWeb/CSS/StyleValues/FlexStyleValue.h>
-#include <LibWeb/CSS/StyleValues/FrequencyStyleValue.h>
-#include <LibWeb/CSS/StyleValues/IntegerStyleValue.h>
-#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
-#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
-#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
-#include <LibWeb/CSS/StyleValues/OpacityValueStyleValue.h>
-#include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
-#include <LibWeb/CSS/StyleValues/ResolutionStyleValue.h>
-#include <LibWeb/CSS/StyleValues/StyleValueList.h>
-#include <LibWeb/CSS/StyleValues/TimeStyleValue.h>
-// What the Rust implementation of the CSS Typed OM (Libraries/LibWeb/Bindings/Rust/src/css) and LibWeb's C++ code ask
-// of each other. The tables of the properties and the entry points of the parser are in C++ for now, so what depends
-// on them is here.
+// What LibWeb's C++ code asks of the Rust implementation of the CSS Typed OM (Libraries/LibWeb/Bindings/Rust/src/css).
namespace Web::CSS {
@@ -172,262 +153,4 @@ Utf16String CSSKeywordValue::value() const
return Utf16String::from_raw(web_css_keyword_value_value(const_cast<CSSKeywordValue*>(this)));
}
-static StyleValueData const* into_rust(StyleValue const& value)
-{
- return StyleValueFFI::rust_style_value_retain(value.rust_style_value_data());
-}
-
-static PropertyID property_id_from_abi(u16 property_id)
-{
- return static_cast<PropertyID>(property_id);
-}
-
-// The order of `enum TypedOmValueType` in Bindings/Rust/src/css/typed_om.rs.
-enum class TypedOmValueType : u8 {
- Image,
- TransformFunction,
- TransformList,
-};
-
-extern "C" {
-
-// Declared in Bindings/Rust/src/css/typed_om.rs.
-bool web_css_typed_om_property_accepts_type(u16 property_id, TypedOmValueType value_type);
-StyleValueData const* web_css_typed_om_numeric_style_value(u16 property_id_abi, StyleValueData const* value_data, FfiCalcNode const* calculation_data, FfiNumericType numeric_type);
-StyleValueData const* web_css_typed_om_calculated_style_value(u16 property_id_abi, FfiCalcNode const* calculation_data, FfiNumericType numeric_type, bool perform_type_check);
-StyleValueData const* web_css_typed_om_keyword_style_value(u16 property_id_abi, FlatPtr raw_value, bool perform_type_check);
-StyleValueData const* web_css_typed_om_style_value_list(StyleValueData const* const* values, size_t count, bool comma);
-StyleValueData const* web_css_typed_om_parse_numeric_value(FlatPtr raw_css_text);
-bool web_css_typed_om_parse_value(FlatPtr raw_property, FlatPtr raw_css_text, void* values, void (*append)(void*, StyleValueData const*), FlatPtr* name_or_error);
-bool web_css_typed_om_zero_is_a_length(FlatPtr raw_property, bool is_integer);
-
-bool web_css_typed_om_property_accepts_type(u16 property_id, TypedOmValueType value_type)
-{
- auto const to_value_type = [&] {
- switch (value_type) {
- case TypedOmValueType::Image:
- return ValueType::Image;
- case TypedOmValueType::TransformFunction:
- return ValueType::TransformFunction;
- case TypedOmValueType::TransformList:
- return ValueType::TransformList;
- }
- VERIFY_NOT_REACHED();
- };
- return property_accepts_type(property_id_from_abi(property_id), to_value_type());
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
-StyleValueData const* web_css_typed_om_numeric_style_value(u16 property_id_abi, StyleValueData const* value_data, FfiCalcNode const* calculation_data, FfiNumericType numeric_type)
-{
- auto property_id = property_id_from_abi(property_id_abi);
- auto value = StyleValue::adopt_rust_style_value_data(value_data);
- auto calculation = CalcNodeRef::adopt(calculation_data);
-
- // If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of value is a
- // CSSUnitValue that is outside of that range, replace that value with the result of wrapping it in a fresh
- // CSSMathSum whose values internal slot contains only that part of value.
- auto wrap_in_math_sum = [&] {
- return into_rust(*CalculatedStyleValue::create(move(calculation), NumericType::from_ffi(numeric_type).release_value(), CalculationContext::for_property(property_id)));
- };
-
- if (value->is_number()) {
- auto number = value->as_number().number();
-
- // NB: Our parser represents an <opacity-value> as an opacity value that holds the number.
- if (property_accepts_type(property_id, ValueType::OpacityValue))
- return into_rust(*OpacityValueStyleValue::create(value));
-
- // NB: Prefer <number> to <integer> when both are accepted.
- if (property_accepts_type(property_id, ValueType::Number))
- return property_accepts_number(property_id, number) ? into_rust(*value) : wrap_in_math_sum();
-
- if (property_accepts_type(property_id, ValueType::Integer)) {
- auto integer = round_to_nearest_integer(number);
- // NB: A number that is not an integer does not match <integer>, so it's wrapped in a CSSMathSum, like a
- // value outside of the accepted range. It then gets rounded when computed.
- if (static_cast<double>(integer) != number)
- return wrap_in_math_sum();
- if (property_accepts_integer(property_id, integer))
- return into_rust(*IntegerStyleValue::create(integer));
- return wrap_in_math_sum();
- }
- return nullptr;
- }
-
- if (value->is_percentage()) {
- // NB: Our parser represents an <opacity-value> as an opacity value that holds the percentage.
- if (property_accepts_type(property_id, ValueType::OpacityValue))
- return into_rust(*OpacityValueStyleValue::create(value));
- if (!property_accepts_type(property_id, ValueType::Percentage))
- return nullptr;
- return property_accepts_percentage(property_id, value->as_percentage().percentage()) ? into_rust(*value) : wrap_in_math_sum();
- }
-
- if (value->is_flex()) {
- // NB: Out-of-range flex values cannot be deferred in a calculation.
- if (property_accepts_type(property_id, ValueType::Flex) && property_accepts_flex(property_id, value->as_flex().flex()))
- return into_rust(*value);
- return nullptr;
- }
-
- auto dimension_value = [&](ValueType value_type, bool is_accepted) -> StyleValueData const* {
- if (!property_accepts_type(property_id, value_type))
- return nullptr;
- return is_accepted ? into_rust(*value) : wrap_in_math_sum();
- };
- if (value->is_angle())
- return dimension_value(ValueType::Angle, property_accepts_angle(property_id, value->as_angle().angle()));
- if (value->is_frequency())
- return dimension_value(ValueType::Frequency, property_accepts_frequency(property_id, value->as_frequency().frequency()));
- if (value->is_length())
- return dimension_value(ValueType::Length, property_accepts_length(property_id, value->as_length().length()));
- if (value->is_resolution())
- return dimension_value(ValueType::Resolution, property_accepts_resolution(property_id, value->as_resolution().resolution()));
- if (value->is_time())
- return dimension_value(ValueType::Time, property_accepts_time(property_id, value->as_time().time()));
- VERIFY_NOT_REACHED();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
-StyleValueData const* web_css_typed_om_calculated_style_value(u16 property_id_abi, FfiCalcNode const* calculation_data, FfiNumericType numeric_type, bool perform_type_check)
-{
- auto property_id = property_id_from_abi(property_id_abi);
- auto calculation = CalcNodeRef::adopt(calculation_data);
- auto type = NumericType::from_ffi(numeric_type).release_value();
- auto context = CalculationContext::for_property(property_id);
-
- auto matches = [&] {
- if (type.matches_angle(context.percentages_resolve_as))
- return property_accepts_type(property_id, ValueType::Angle);
- if (type.matches_flex(context.percentages_resolve_as)) {
- // https://drafts.csswg.org/css-grid-2/#fr-unit
- // NB: <flex> values "cannot be represented in or combined with other unit types in calc() expressions".
- return property_id == PropertyID::Custom && property_accepts_type(property_id, ValueType::Flex);
- }
- if (type.matches_frequency(context.percentages_resolve_as))
- return property_accepts_type(property_id, ValueType::Frequency);
- if (type.matches_length(context.percentages_resolve_as))
- return property_accepts_type(property_id, ValueType::Length);
- if (type.matches_number(context.percentages_resolve_as))
- return property_accepts_type(property_id, ValueType::Number) || property_accepts_type(property_id, ValueType::Integer) || property_accepts_type(property_id, ValueType::OpacityValue);
- if (type.matches_percentage())
- return property_accepts_type(property_id, ValueType::Percentage) || property_accepts_type(property_id, ValueType::OpacityValue);
- if (type.matches_resolution(context.percentages_resolve_as))
- return property_accepts_type(property_id, ValueType::Resolution);
- if (type.matches_time(context.percentages_resolve_as))
- return property_accepts_type(property_id, ValueType::Time);
- return false;
- }();
- if (perform_type_check && !matches)
- return nullptr;
-
- auto is_number_or_percentage = type.matches_number({}) || type.matches_percentage();
- auto calculated_value = CalculatedStyleValue::create(move(calculation), move(type), move(context));
-
- // NB: Our parser represents an <opacity-value> as an opacity value that holds the calculation.
- if (property_accepts_type(property_id, ValueType::OpacityValue) && is_number_or_percentage)
- return into_rust(*OpacityValueStyleValue::create(move(calculated_value)));
-
- return into_rust(*calculated_value);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
-StyleValueData const* web_css_typed_om_keyword_style_value(u16 property_id_abi, FlatPtr raw_value, bool perform_type_check)
-{
- auto property_id = property_id_from_abi(property_id_abi);
- auto value = Utf16FlyString { Utf16String::from_raw(raw_value) };
- auto keyword = keyword_from_string(value);
-
- // https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue-match-a-grammar
- // NB: The keywords listed for a property are not all valid on their own, like `hanging` for text-indent, and a
- // property may accept identifiers that are not listed, like a <custom-ident> or the axis keywords of
- // scroll-snap-type. So we check if the property accepts the value, as an identifier, when parsed.
- auto const matches_grammar = [&] {
- if (keyword.has_value() && is_css_wide_keyword(*keyword))
- return true;
- return parse_css_value(Parser::ParsingParams {}, serialize_an_identifier(value), property_id) != nullptr;
- };
- if (perform_type_check && !matches_grammar())
- return nullptr;
-
- if (keyword.has_value()) {
- // NB: Style computation expects the same internal representation that the CSS parser produces for the
- // property. For example, `display` keywords become a DisplayStyleValue, and keyword combinations like
- // `text-decoration-line` or `white-space-trim` become a list even when only one keyword is given. So we
- // parse the keyword as a value of the property to get that representation. List-valued properties are
- // instead wrapped in a list by StylePropertyMap.
- if (!is_css_wide_keyword(*keyword) && property_id != PropertyID::Custom && !property_is_list_valued(property_id)) {
- if (auto parsed_value = parse_css_value(Parser::ParsingParams {}, value.view(), property_id))
- return into_rust(*parsed_value);
- }
- return into_rust(*KeywordStyleValue::create(*keyword));
- }
- return into_rust(*CustomIdentStyleValue::create(value));
-}
-
-StyleValueData const* web_css_typed_om_style_value_list(StyleValueData const* const* values, size_t count, bool comma)
-{
- StyleValueVector list;
- list.ensure_capacity(count);
- for (size_t i = 0; i < count; ++i)
- list.unchecked_append(StyleValue::adopt_rust_style_value_data(values[i]));
- return into_rust(*StyleValueList::create(move(list), comma ? StyleValueList::Separator::Comma : StyleValueList::Separator::Space));
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-parse
-StyleValueData const* web_css_typed_om_parse_numeric_value(FlatPtr raw_css_text)
-{
- auto css_text = Utf16String::from_raw(raw_css_text);
- for (auto value_type : { ValueType::Number, ValueType::Percentage, ValueType::Length, ValueType::LengthPercentage, ValueType::Angle, ValueType::Time, ValueType::Frequency, ValueType::Resolution, ValueType::Flex }) {
- if (auto value = parse_css_type(Parser::ParsingParams {}, css_text, value_type))
- return into_rust(*value);
- }
- return nullptr;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#parse-a-cssstylevalue
-bool web_css_typed_om_parse_value(FlatPtr raw_property, FlatPtr raw_css_text, void* values, void (*append)(void*, StyleValueData const*), FlatPtr* name_or_error)
-{
- auto property_name = Utf16FlyString { Utf16String::from_raw(raw_property) };
- auto css_text = Utf16String::from_raw(raw_css_text);
-
- // 1. If property is not a custom property name string, set property to property ASCII lowercased.
- // 2. If property is not a valid CSS property, throw a TypeError.
- auto property = PropertyNameAndID::from_name(property_name);
- if (!property.has_value()) {
- *name_or_error = Utf16String::formatted("'{}' is not a valid CSS property", property_name).into_raw();
- return false;
- }
-
- // 3. Attempt to parse cssText according to property’s grammar.
- // If this fails, throw a TypeError.
- // Otherwise, let whole value be the parsed result.
- auto whole_value = parse_css_value(Parser::ParsingParams {}, css_text, property->id());
- if (!whole_value) {
- *name_or_error = Utf16String::formatted("Failed to parse '{}' as a value for '{}' property", css_text, property_name).into_raw();
- return false;
- }
-
- // 4. Subdivide into iterations whole value, according to property, and let values be the result.
- for (auto const& value : whole_value->subdivide_into_iterations(property.value()))
- append(values, into_rust(*value));
-
- *name_or_error = property->name().to_utf16_string().into_raw();
- return true;
-}
-
-// Whether the property expects a 0 to be a <length>.
-bool web_css_typed_om_zero_is_a_length(FlatPtr raw_property, bool is_integer)
-{
- auto property = Utf16String::from_raw(raw_property);
- if (!property.is_ascii())
- return false;
- auto property_id = property_id_from_string(property);
- if (!property_id.has_value() || property_id == PropertyID::Custom || !property_accepts_type(*property_id, ValueType::Length))
- return false;
- return is_integer || (!property_accepts_type(*property_id, ValueType::Number) && !property_accepts_type(*property_id, ValueType::Integer));
-}
-}
-
}
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rs
index b9aa648c3eb..bf47eb2059f 100644
--- a/Libraries/LibWeb/Rust/build.rs
+++ b/Libraries/LibWeb/Rust/build.rs
@@ -935,7 +935,6 @@ fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(),
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 mut numeric_range_rows = vec![String::new(); levels.len()];
let value_types = [
"anchor",
"anchor-size",
@@ -1062,43 +1061,6 @@ fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(),
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 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[index] = ranges.join(", ");
}
let mut output = String::new();
@@ -1561,6 +1523,7 @@ fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(),
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 {
@@ -1664,6 +1627,42 @@ fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(),
}
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())
diff --git a/Libraries/LibWeb/Rust/src/css/calc.rs b/Libraries/LibWeb/Rust/src/css/calc.rs
index 97b1053aaac..e792d30f3ec 100644
--- a/Libraries/LibWeb/Rust/src/css/calc.rs
+++ b/Libraries/LibWeb/Rust/src/css/calc.rs
@@ -308,7 +308,7 @@ impl CalcNumericType {
}
}
-fn base_type_from_value_type(value_type: u8) -> Option<u8> {
+pub(crate) fn base_type_from_value_type(value_type: u8) -> Option<u8> {
match value_type {
value_type::ANGLE => Some(1),
value_type::FLEX => Some(5),
diff --git a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
index 4e7039f9206..d31fc4c3395 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
@@ -129,7 +129,6 @@ pub struct FfiValueParsingContext<'a> {
pub struct RandomFunctionIndex(std::cell::Cell<usize>);
impl RandomFunctionIndex {
- #[cfg(test)]
pub(crate) fn new(index: usize) -> Self {
Self(std::cell::Cell::new(index))
}
@@ -336,7 +335,7 @@ fn clamp_to_single_precision_range(value: f64) -> f64 {
value.clamp(f32::MIN as f64, f32::MAX as f64)
}
-fn round_to_nearest_integer(value: f64) -> i32 {
+pub(crate) fn round_to_nearest_integer(value: f64) -> i32 {
if value.is_nan() {
return 0;
}
diff --git a/Libraries/LibWeb/Rust/src/css/property_metadata.rs b/Libraries/LibWeb/Rust/src/css/property_metadata.rs
index 63495dccbaa..90f0f7c4511 100644
--- a/Libraries/LibWeb/Rust/src/css/property_metadata.rs
+++ b/Libraries/LibWeb/Rust/src/css/property_metadata.rs
@@ -218,7 +218,7 @@ pub struct FfiPropertyNumericRange {
}
pub fn property_numeric_ranges(property_id: u16) -> &'static [FfiPropertyNumericRange] {
- PROPERTY_NUMERIC_RANGES[longhand_index(property_id)]
+ PROPERTY_NUMERIC_RANGES[property_index(property_id)]
}
/// Returns the longhand property identifiers in computation order.
diff --git a/Libraries/LibWeb/Rust/src/css/style_value.rs b/Libraries/LibWeb/Rust/src/css/style_value.rs
index 7dbd286c3ed..51fa0104f28 100644
--- a/Libraries/LibWeb/Rust/src/css/style_value.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_value.rs
@@ -1674,6 +1674,10 @@ pub struct RetainedNumericRangeByType {
}
impl RetainedNumericRangeByType {
+ pub(crate) fn new(value_type: u8, min: f64, max: f64) -> Self {
+ Self { value_type, min, max }
+ }
+
pub(crate) fn value_type(&self) -> u8 {
self.value_type
}
diff --git a/Libraries/LibWeb/Rust/src/css/typed_om.rs b/Libraries/LibWeb/Rust/src/css/typed_om.rs
index ce9c59f1ede..635e0bd14b6 100644
--- a/Libraries/LibWeb/Rust/src/css/typed_om.rs
+++ b/Libraries/LibWeb/Rust/src/css/typed_om.rs
@@ -12,23 +12,40 @@ use std::collections::BTreeMap;
use std::sync::Arc;
pub use crate::css::calc::{CalcNode, CalcNumericType as NumericType, FfiNumericType};
-use crate::css::calc::{CalcNumericValue, canonical_unit_code};
+use crate::css::calc::{CalcNumericValue, base_type_from_value_type, canonical_unit_code, resolve_as_for_value_type};
use crate::css::css_enums::{keyword, keyword_from_ascii_case_insensitive};
+use crate::css::css_string::CssString;
use crate::css::dimension_units::{
ANGLE_UNIT_CANONICAL_RATIOS, ANGLE_UNIT_NAMES, FLEX_UNIT_CANONICAL_RATIOS, FLEX_UNIT_NAMES,
FREQUENCY_UNIT_CANONICAL_RATIOS, FREQUENCY_UNIT_NAMES, RESOLUTION_UNIT_CANONICAL_RATIOS, RESOLUTION_UNIT_NAMES,
TIME_UNIT_CANONICAL_RATIOS, TIME_UNIT_NAMES,
};
+use crate::css::ffi_support::FfiUtf16View;
use crate::css::parser::arbitrary_substitution::SubstitutionFunctionsPresence;
use crate::css::parser::arbitrary_substitution::collect_arbitrary_substitution_function_presence;
-use crate::css::parser::value_parser::{component_values_from_source, is_css_wide_keyword};
-use crate::css::property_metadata::is_custom_property_name;
+use crate::css::parser::value_parser::{
+ FfiParseStatus, FfiValueParsingContext, FfiValueParsingContextKind, ParseContext, RandomFunctionIndex,
+ component_values_from_source, is_css_wide_keyword, round_to_nearest_integer, rust_parse_css_value,
+ rust_parse_entire_css_primitive_from_source,
+};
pub use crate::css::property_metadata::property_is_shorthand;
+use crate::css::property_metadata::{
+ is_custom_property_name, property_accepted_value_types, property_id, property_id_from_name, property_name,
+ property_numeric_ranges, property_percentages_resolve_to,
+};
use crate::css::serialize::{SerializationMode, TextSink, serialize_style_value};
use crate::css::style_compute::{LENGTH_UNIT_CANONICAL_PX_RATIOS, LENGTH_UNIT_NAMES};
-use crate::css::style_value::StyleValueData;
use crate::css::style_value::rust_style_value_create_grid_track_size_list;
pub use crate::css::style_value::{ReifiedUnresolvedSegment, RetainedStyleValueData as RetainedStyleValue};
+use crate::css::style_value::{
+ RetainedNumericRangeByType, StyleValueData, rust_style_value_create_calculated, rust_style_value_create_value_list,
+};
+use crate::css::style_value_arc::StyleValueArc;
+use crate::css::value_codes::{
+ VALUE_TYPE_ANGLE, VALUE_TYPE_FLEX, VALUE_TYPE_FREQUENCY, VALUE_TYPE_IMAGE, VALUE_TYPE_INTEGER, VALUE_TYPE_LENGTH,
+ VALUE_TYPE_LENGTH_PERCENTAGE, VALUE_TYPE_NUMBER, VALUE_TYPE_OPACITY_VALUE, VALUE_TYPE_PERCENTAGE,
+ VALUE_TYPE_RESOLUTION, VALUE_TYPE_TIME, VALUE_TYPE_TRANSFORM_FUNCTION, VALUE_TYPE_TRANSFORM_LIST,
+};
/// The base types of a numeric type, as indices of [`NumericType::exponents`].
pub const BASE_TYPE_LENGTH: usize = 0;
@@ -699,3 +716,346 @@ pub fn transform_matrix(value: &RetainedStyleValue) -> Option<[f32; 16]> {
)
.then_some(matrix)
}
+
+/// The value types of a property that the CSS Typed OM asks about by name.
+#[derive(Clone, Copy)]
+pub enum TypedOmValueType {
+ Image,
+ TransformFunction,
+ TransformList,
+}
+
+/// Whether a value that is not a shorthand's can be of the value type. A custom property takes no fixed types.
+fn property_accepts_value_type(property_id: u16, value_type: u8) -> bool {
+ property_id != property_id::CUSTOM && property_accepted_value_types(property_id).contains(&value_type)
+}
+
+pub fn property_accepts_type(property_id: u16, value_type: TypedOmValueType) -> bool {
+ property_accepts_value_type(
+ property_id,
+ match value_type {
+ TypedOmValueType::Image => VALUE_TYPE_IMAGE,
+ TypedOmValueType::TransformFunction => VALUE_TYPE_TRANSFORM_FUNCTION,
+ TypedOmValueType::TransformList => VALUE_TYPE_TRANSFORM_LIST,
+ },
+ )
+}
+
+/// Whether the value is in the range of the value type of the property. A bound that the tables write as the limit of
+/// a float stands for no bound at all.
+fn property_accepts_value_in_range(property_id: u16, value_type: u8, value: f64) -> bool {
+ if !property_accepts_value_type(property_id, value_type) {
+ return false;
+ }
+ property_numeric_ranges(property_id)
+ .iter()
+ .find(|range| range.value_type == value_type)
+ .is_none_or(|range| {
+ (range.min == f32::MIN as f64 || value >= range.min) && (range.max == f32::MAX as f64 || value <= range.max)
+ })
+}
+
+fn percentages_resolve_as(property_id: u16) -> Option<u8> {
+ if property_id == property_id::CUSTOM {
+ return None;
+ }
+ property_percentages_resolve_to(property_id)
+}
+
+/// A calculation with the context of the property, https://drafts.csswg.org/css-values-4/#calc-type-checking
+fn calculated_value(property_id: u16, calculation: Arc<CalcNode>, numeric_type: NumericType) -> RetainedStyleValue {
+ let resolve_as = percentages_resolve_as(property_id);
+ let ranges: Vec<_> = if property_id == property_id::CUSTOM {
+ Vec::new()
+ } else {
+ property_numeric_ranges(property_id)
+ .iter()
+ .map(|range| RetainedNumericRangeByType::new(range.value_type, range.min, range.max))
+ .collect()
+ };
+ let calculation = Arc::into_raw(calculation);
+ // SAFETY: This hands over one strong reference to the calculation, and the ranges are readable for their length.
+ let value = unsafe {
+ rust_style_value_create_calculated(
+ calculation,
+ FfiNumericType::from_calc(Some(numeric_type)),
+ resolve_as.is_some(),
+ resolve_as == Some(VALUE_TYPE_NUMBER),
+ resolve_as.and_then(base_type_from_value_type).unwrap_or(0),
+ resolve_as.unwrap_or(0),
+ property_accepts_value_type(property_id, VALUE_TYPE_INTEGER),
+ ranges.as_ptr(),
+ ranges.len(),
+ )
+ };
+ // SAFETY: The call hands over a strong reference to a new value.
+ unsafe { RetainedStyleValue::from_raw(value.cast()) }
+}
+
+fn opacity_value(value: RetainedStyleValue) -> RetainedStyleValue {
+ RetainedStyleValue::from_arc(StyleValueArc::new(StyleValueData::OpacityValue { value }))
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+pub fn numeric_style_value(
+ property_id: u16,
+ value: RetainedStyleValue,
+ calculation: Arc<CalcNode>,
+ numeric_type: NumericType,
+) -> Option<RetainedStyleValue> {
+ // If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of value is a
+ // CSSUnitValue that is outside of that range, replace that value with the result of wrapping it in a fresh
+ // CSSMathSum whose values internal slot contains only that part of value.
+ let wrap_in_math_sum = || calculated_value(property_id, calculation.clone(), numeric_type);
+ let accepted = |value_type: u8, number: f64| property_accepts_value_in_range(property_id, value_type, number);
+ let in_range_or_wrapped = |value_type: u8, number: f64, value: RetainedStyleValue| {
+ if !property_accepts_value_type(property_id, value_type) {
+ return None;
+ }
+ Some(if accepted(value_type, number) {
+ value
+ } else {
+ wrap_in_math_sum()
+ })
+ };
+
+ match *value.data() {
+ StyleValueData::Number { value: number } => {
+ // NB: Our parser represents an <opacity-value> as an opacity value that holds the number.
+ if property_accepts_value_type(property_id, VALUE_TYPE_OPACITY_VALUE) {
+ return Some(opacity_value(value));
+ }
+
+ // NB: Prefer <number> to <integer> when both are accepted.
+ if property_accepts_value_type(property_id, VALUE_TYPE_NUMBER) {
+ return in_range_or_wrapped(VALUE_TYPE_NUMBER, number, value);
+ }
+
+ if property_accepts_value_type(property_id, VALUE_TYPE_INTEGER) {
+ let integer = round_to_nearest_integer(number);
+ // NB: A number that is not an integer does not match <integer>, so it's wrapped in a CSSMathSum, like a
+ // value outside of the accepted range. It then gets rounded when computed.
+ if f64::from(integer) != number || !accepted(VALUE_TYPE_INTEGER, f64::from(integer)) {
+ return Some(wrap_in_math_sum());
+ }
+ return Some(RetainedStyleValue::from_arc(StyleValueArc::new(
+ StyleValueData::Integer { value: integer },
+ )));
+ }
+ None
+ }
+ StyleValueData::Percentage { value: percentage } => {
+ // NB: Our parser represents an <opacity-value> as an opacity value that holds the percentage.
+ if property_accepts_value_type(property_id, VALUE_TYPE_OPACITY_VALUE) {
+ return Some(opacity_value(value));
+ }
+ in_range_or_wrapped(VALUE_TYPE_PERCENTAGE, percentage, value)
+ }
+ // NB: Out-of-range flex values cannot be deferred in a calculation.
+ StyleValueData::Flex { value: flex, .. } => accepted(VALUE_TYPE_FLEX, flex).then_some(value),
+ StyleValueData::Angle { value: angle, .. } => in_range_or_wrapped(VALUE_TYPE_ANGLE, angle, value),
+ StyleValueData::Frequency { value: frequency, .. } => {
+ in_range_or_wrapped(VALUE_TYPE_FREQUENCY, frequency, value)
+ }
+ StyleValueData::Length { value: length, .. } => in_range_or_wrapped(VALUE_TYPE_LENGTH, length, value),
+ StyleValueData::Resolution { value: resolution, .. } => {
+ in_range_or_wrapped(VALUE_TYPE_RESOLUTION, resolution, value)
+ }
+ StyleValueData::Time { value: time, .. } => in_range_or_wrapped(VALUE_TYPE_TIME, time, value),
+ _ => unreachable!("a numeric value is one of the numeric style values"),
+ }
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+pub fn calculated_style_value(
+ property_id: u16,
+ calculation: Arc<CalcNode>,
+ numeric_type: NumericType,
+ perform_type_check: bool,
+) -> Option<RetainedStyleValue> {
+ let resolve_as = resolve_as_for_value_type(percentages_resolve_as(property_id));
+ let accepts = |value_type: u8| property_accepts_value_type(property_id, value_type);
+
+ let matches = if numeric_type.matches_dimension(BASE_TYPE_ANGLE, resolve_as) {
+ accepts(VALUE_TYPE_ANGLE)
+ } else if numeric_type.matches_dimension(BASE_TYPE_FLEX, resolve_as) {
+ // https://drafts.csswg.org/css-grid-2/#fr-unit
+ // NB: <flex> values "cannot be represented in or combined with other unit types in calc() expressions".
+ false
+ } else if numeric_type.matches_dimension(BASE_TYPE_FREQUENCY, resolve_as) {
+ accepts(VALUE_TYPE_FREQUENCY)
+ } else if numeric_type.matches_dimension(BASE_TYPE_LENGTH, resolve_as) {
+ accepts(VALUE_TYPE_LENGTH)
+ } else if numeric_type.matches_number(resolve_as) {
+ accepts(VALUE_TYPE_NUMBER) || accepts(VALUE_TYPE_INTEGER) || accepts(VALUE_TYPE_OPACITY_VALUE)
+ } else if numeric_type.matches_percentage() {
+ accepts(VALUE_TYPE_PERCENTAGE) || accepts(VALUE_TYPE_OPACITY_VALUE)
+ } else if numeric_type.matches_dimension(BASE_TYPE_RESOLUTION, resolve_as) {
+ accepts(VALUE_TYPE_RESOLUTION)
+ } else if numeric_type.matches_dimension(BASE_TYPE_TIME, resolve_as) {
+ accepts(VALUE_TYPE_TIME)
+ } else {
+ false
+ };
+ if perform_type_check && !matches {
+ return None;
+ }
+
+ let is_number_or_percentage = numeric_type.matches_number(None) || numeric_type.matches_percentage();
+ let calculated = calculated_value(property_id, calculation, numeric_type);
+
+ // NB: Our parser represents an <opacity-value> as an opacity value that holds the calculation.
+ if accepts(VALUE_TYPE_OPACITY_VALUE) && is_number_or_percentage {
+ return Some(opacity_value(calculated));
+ }
+ Some(calculated)
+}
+
+/// The value of the text for the property, with no document to parse it for.
+pub fn parse_value_for_property(property_id: u16, css_text: &ak::Utf16String) -> Option<RetainedStyleValue> {
+ let units = css_text.to_utf16();
+ if units.is_empty() {
+ return None;
+ }
+ let value_context = FfiValueParsingContext {
+ kind: FfiValueParsingContextKind::Property,
+ value: property_id,
+ secondary_value: 0,
+ name: FfiUtf16View::default(),
+ };
+ let random_function_index = RandomFunctionIndex::new(0);
+ let context = ParseContext {
+ value_contexts: ak::Span::new(core::slice::from_ref(&value_context)),
+ random_function_index: Some(&random_function_index),
+ ..Default::default()
+ };
+ let mut status = FfiParseStatus::NotHandled;
+ // SAFETY: The context and the text are live through the call.
+ let value = unsafe {
+ rust_parse_css_value(
+ Some(&context),
+ property_id,
+ FfiUtf16View::from_utf16(units.as_ref()),
+ Some(&mut status),
+ )
+ };
+ // SAFETY: A parsed value comes with a strong reference.
+ (!value.is_null()).then(|| unsafe { RetainedStyleValue::from_raw(value) })
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+pub fn keyword_style_value(
+ property_id: u16,
+ value: &ak::Utf16String,
+ perform_type_check: bool,
+ property_is_list_valued: bool,
+) -> Option<RetainedStyleValue> {
+ let units = value.to_utf16();
+ let keyword = keyword_from_ascii_case_insensitive(units.as_ref());
+ let is_css_wide = keyword.is_some_and(is_css_wide_keyword);
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue-match-a-grammar
+ // NB: The keywords listed for a property are not all valid on their own, like `hanging` for text-indent, and a
+ // property may accept identifiers that are not listed, like a <custom-ident> or the axis keywords of
+ // scroll-snap-type. So we check if the property accepts the value, as an identifier, when parsed.
+ if perform_type_check
+ && !is_css_wide
+ && parse_value_for_property(property_id, &serialize_an_identifier(value)).is_none()
+ {
+ return None;
+ }
+
+ let Some(keyword) = keyword else {
+ return Some(RetainedStyleValue::from_arc(StyleValueArc::new(
+ StyleValueData::CustomIdent {
+ custom_ident: CssString::from_utf16(units.as_ref()),
+ },
+ )));
+ };
+
+ // NB: Style computation expects the same internal representation that the CSS parser produces for the
+ // property. For example, `display` keywords become a DisplayStyleValue, and keyword combinations like
+ // `text-decoration-line` or `white-space-trim` become a list even when only one keyword is given. So we
+ // parse the keyword as a value of the property to get that representation. List-valued properties are
+ // instead wrapped in a list by StylePropertyMap.
+ if !is_css_wide
+ && property_id != property_id::CUSTOM
+ && !property_is_list_valued
+ && let Some(parsed_value) = parse_value_for_property(property_id, value)
+ {
+ return Some(parsed_value);
+ }
+ Some(RetainedStyleValue::from_arc(StyleValueArc::new(
+ StyleValueData::Keyword { keyword },
+ )))
+}
+
+/// A list of the values, separated by commas or spaces.
+pub fn style_value_list(values: Vec<RetainedStyleValue>, comma: bool) -> RetainedStyleValue {
+ let values: Vec<_> = values.into_iter().map(RetainedStyleValue::into_raw).collect();
+ // NB: These are the C++ enumerators StyleValueList::Separator::Space and Comma.
+ let separator = u8::from(comma);
+ // SAFETY: This hands over one strong reference to each of the values.
+ let list = unsafe { rust_style_value_create_value_list(values.as_ptr().cast(), values.len(), separator, false) };
+ // SAFETY: The call hands over a strong reference to a new value.
+ unsafe { RetainedStyleValue::from_raw(list.cast()) }
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-parse
+pub fn parse_a_numeric_value(css_text: &ak::Utf16String) -> Option<RetainedStyleValue> {
+ let units = css_text.to_utf16();
+ if units.is_empty() {
+ return None;
+ }
+ let context = ParseContext::default();
+ [
+ VALUE_TYPE_NUMBER,
+ VALUE_TYPE_PERCENTAGE,
+ VALUE_TYPE_LENGTH,
+ VALUE_TYPE_LENGTH_PERCENTAGE,
+ VALUE_TYPE_ANGLE,
+ VALUE_TYPE_TIME,
+ VALUE_TYPE_FREQUENCY,
+ VALUE_TYPE_RESOLUTION,
+ VALUE_TYPE_FLEX,
+ ]
+ .into_iter()
+ .find_map(|value_type| {
+ // SAFETY: The context and the text are live through the call.
+ let value = unsafe {
+ rust_parse_entire_css_primitive_from_source(
+ Some(&context),
+ value_type,
+ FfiUtf16View::from_utf16(units.as_ref()),
+ f32::MIN as f64,
+ f32::MAX as f64,
+ )
+ };
+ // SAFETY: A parsed value comes with a strong reference.
+ (!value.is_null()).then(|| unsafe { RetainedStyleValue::from_raw(value) })
+ })
+}
+
+/// The canonical name and the id of the property with the name, if there is one.
+pub fn property_from_name(name: &ak::Utf16String) -> Option<(ak::Utf16String, u16)> {
+ let units = name.to_utf16();
+ let property_id = property_id_from_name(units.as_ref())?;
+ if property_id == property_id::CUSTOM {
+ return Some((name.clone(), property_id));
+ }
+ Some((ak::Utf16String::from_utf8(property_name(property_id)), property_id))
+}
+
+/// Whether the property expects a 0 to be a <length>.
+pub fn zero_is_a_length(property: &ak::Utf16String, is_integer: bool) -> bool {
+ let units = property.to_utf16();
+ let Some(property_id) = property_id_from_name(units.as_ref()) else {
+ return false;
+ };
+ if !property_accepts_value_type(property_id, VALUE_TYPE_LENGTH) {
+ return false;
+ }
+ is_integer
+ || (!property_accepts_value_type(property_id, VALUE_TYPE_NUMBER)
+ && !property_accepts_value_type(property_id, VALUE_TYPE_INTEGER))
+}
diff --git a/Libraries/LibWeb/Rust/src/css/value_codes.rs b/Libraries/LibWeb/Rust/src/css/value_codes.rs
index b93348f524a..d6687221fa0 100644
--- a/Libraries/LibWeb/Rust/src/css/value_codes.rs
+++ b/Libraries/LibWeb/Rust/src/css/value_codes.rs
@@ -31,6 +31,8 @@ pub(crate) const VALUE_TYPE_RECT: u8 = 34;
pub(crate) const VALUE_TYPE_RESOLUTION: u8 = 35;
pub(crate) const VALUE_TYPE_STRING: u8 = 37;
pub(crate) const VALUE_TYPE_TIME: u8 = 38;
+pub(crate) const VALUE_TYPE_TRANSFORM_FUNCTION: u8 = 40;
+pub(crate) const VALUE_TYPE_TRANSFORM_LIST: u8 = 41;
pub(crate) const VALUE_TYPE_URL: u8 = 42;
// The `CSS::ColorStyleValue::ColorType` discriminants.